Skip to main content

durable_workflow/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod cancellation_context;
4mod cancellation_replay_clock;
5mod cancellation_scope;
6mod cancellation_scope_history;
7mod cancellation_scope_replay;
8mod cooperative_cancellation;
9mod runtime_payloads;
10mod runtime_uploads;
11
12pub use cancellation_context::{
13    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
14};
15pub use cancellation_scope::CancellationScopeOpenReceipt;
16#[doc(hidden)]
17pub use cancellation_scope_history::{
18    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
19};
20#[doc(hidden)]
21pub use cancellation_scope_replay::CancellationScopeRequested;
22
23pub use cooperative_cancellation::{
24    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
25    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
26    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
27    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
28};
29
30use std::{
31    any::{type_name, Any, TypeId},
32    collections::{BTreeMap, BTreeSet, HashMap},
33    future::Future,
34    io::{self, Read},
35    pin::Pin,
36    sync::{
37        atomic::{AtomicBool, Ordering},
38        Arc, Mutex, OnceLock,
39    },
40    task::{Context as TaskContext, Poll},
41    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
42};
43
44use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
45use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
46use chrono::DateTime;
47use futures_util::{
48    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
49};
50use serde::{
51    de::DeserializeOwned,
52    ser::{SerializeMap, SerializeSeq},
53    Deserialize, Deserializer, Serialize, Serializer,
54};
55pub use serde_json::{json, Value};
56use sha2::{Digest, Sha256};
57use thiserror::Error;
58pub use uuid::Uuid;
59
60pub const WORKER_PROTOCOL_VERSION: &str = "1.19";
61const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
62/// First additive worker protocol that defines portable worker-affinity features.
63pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
64pub const CONTROL_PLANE_VERSION: &str = "2";
65pub const DEFAULT_CODEC: &str = "avro";
66pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
67/// Worker-registration capability for authored condition-wait occurrence identity.
68pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
69    "condition_wait_occurrence_identity";
70/// Worker-registration capability for portable memo upserts.
71pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
72/// Worker-registration capability for server-routed read-only queries.
73pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
74/// Worker-registration capability for canonical typed search attributes.
75pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
76/// Worker-registration capability for synchronous workflow updates.
77pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
78/// Worker-registration capability for durable named input streams.
79pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
80/// Worker-registration capability for persisted first-completion selection.
81pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
82pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
83pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
84pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
85pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
86pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
87/// First additive worker protocol that defines query-task transport.
88pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
89/// First additive worker protocol that defines typed search-attribute upserts.
90pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
91/// First additive worker protocol that defines portable memo upserts.
92pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
93/// First additive worker protocol that preserves declared search-attribute types.
94pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
95/// First additive worker protocol that defines external durable condition waits.
96pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
97/// First additive worker protocol that preserves authored condition-wait occurrences.
98pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
99/// First additive worker protocol that defines durable selection groups.
100pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
101
102pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
103    let Some((major, minor)) = version.split_once('.') else {
104        return false;
105    };
106    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
107}
108
109fn validate_user_signal_name(signal_name: &str) -> Result<()> {
110    if signal_name == MESSAGE_STREAM_SIGNAL {
111        return Err(Error::Codec(format!(
112            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
113        )));
114    }
115    Ok(())
116}
117
118const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
119const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
120    "Workflow task waiting for scheduled history.";
121const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
122const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
123const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
124const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
125const MAX_MEMO_ENTRIES: usize = 100;
126const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
127const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
128
129const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
130    "lease_expired",
131    "query_task_not_found",
132    "query_task_not_leased",
133    "query_task_timed_out",
134];
135
136/// Truthful service-worker manifest for features this SDK currently refuses.
137pub fn portable_worker_affinity_capability_manifest() -> Value {
138    json!({
139        "local_activities": {
140            "supported": false,
141            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
142            "reason": "rust_worker_does_not_execute_record_local_activity",
143        },
144        "worker_sessions": {
145            "supported": false,
146            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
147            "reason": "rust_worker_has_no_typed_session_lifecycle",
148        },
149        "sticky_execution": {
150            "supported": false,
151            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
152            "reason": "rust_worker_uses_complete_durable_history_replay",
153        },
154    })
155}
156
157/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
158pub const AVRO_VALUE_SCHEMA_JSON: &str =
159    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
160pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
161pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
162const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
163
164static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
165static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
166    OnceLock::new();
167
168#[derive(Clone, Copy)]
169enum RequestProtocol {
170    ControlPlane,
171    Worker(&'static str),
172}
173
174pub type Result<T> = std::result::Result<T, Error>;
175
176#[derive(Debug, Error)]
177pub enum Error {
178    #[error("transport error: {0}")]
179    Transport(#[from] reqwest::Error),
180    #[error(
181        "invalid Durable Workflow base URL: omit the SDK-owned /api suffix and pass the Server or Cloud runtime base URL; the SDK appends /api automatically"
182    )]
183    InvalidBaseUrl,
184    #[error("json error: {0}")]
185    Json(#[from] serde_json::Error),
186    #[error("http {status}: {body}")]
187    Http {
188        status: reqwest::StatusCode,
189        body: String,
190    },
191    #[error("codec error: {0}")]
192    Codec(String),
193    #[error(transparent)]
194    QueryFailed(QueryFailure),
195    #[error(transparent)]
196    Protocol(ProtocolFailure),
197    #[error(transparent)]
198    NonDeterministicReplay(ReplayFailure),
199    #[error(transparent)]
200    ChildWorkflowFailed(ChildWorkflowFailure),
201    #[error(transparent)]
202    ActivityFailed(ActivityFailure),
203    #[error(transparent)]
204    ParallelFailed(ParallelFailure),
205    #[error(transparent)]
206    SagaCompensationFailed(SagaCompensationFailure),
207    #[error(transparent)]
208    InvalidParallelGroup(ParallelGroupError),
209    #[error(transparent)]
210    DurableOperationCancelled(DurableOperationCancelled),
211    #[error(transparent)]
212    WorkflowCancellationRequested(WorkflowCancellationRequested),
213    #[error(transparent)]
214    CooperativeCancellationRequested(CooperativeCancellationRequested),
215    #[error(transparent)]
216    CancellationScopeRequested(CancellationScopeRequested),
217    #[error(transparent)]
218    WorkflowCommandRejected(WorkflowCommandRejection),
219    #[error(transparent)]
220    WorkflowFailed(WorkflowTerminalOutcome),
221    #[error(transparent)]
222    WorkflowCancelled(WorkflowTerminalOutcome),
223    #[error(transparent)]
224    WorkflowTerminated(WorkflowTerminalOutcome),
225    #[error(transparent)]
226    WorkflowTimedOut(WorkflowTerminalOutcome),
227    #[error(transparent)]
228    ActivityTaskRejected(ActivityTaskRejection),
229    #[error("workflow handler {0:?} is not registered")]
230    WorkflowNotRegistered(String),
231    #[error("activity handler {0:?} is not registered")]
232    ActivityNotRegistered(String),
233    #[error(
234        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
235    )]
236    HandlerType {
237        handler_kind: HandlerKind,
238        handler_name: String,
239        value_kind: HandlerValueKind,
240        rust_type: &'static str,
241        message: String,
242    },
243    #[error("workflow future yielded without emitting a durable command")]
244    WorkflowYieldedWithoutCommand,
245    #[error(
246        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
247    )]
248    MissingWorkflowCommandIdentity,
249    #[error("workflow state lock is poisoned")]
250    WorkflowStatePoisoned,
251    #[error("timer duration is too large for the worker protocol")]
252    TimerDurationOverflow,
253    #[error(transparent)]
254    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
255    #[error(transparent)]
256    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
257    #[error("operation timed out")]
258    Timeout,
259    #[error(
260        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
261    )]
262    MissingRoleCredentials {
263        role: &'static str,
264        opposite_role: &'static str,
265    },
266    #[error("worker loop error: {0}")]
267    WorkerLoop(String),
268    #[error(
269        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
270    )]
271    UnsupportedUpdateValidators { workflow_type: String },
272    #[error("{primary}; worker deregistration also failed: {deregistration}")]
273    WorkerShutdown {
274        primary: Box<Error>,
275        deregistration: Box<Error>,
276    },
277    #[error("invalid child workflow options: {0}")]
278    InvalidChildWorkflowOptions(String),
279    #[error("invalid workflow memo update: {0}")]
280    InvalidMemoUpdate(String),
281    #[error(
282        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
283    )]
284    WorkflowMemoUpdatesUnavailable,
285    #[error("cooperative cancellation is unavailable: {0}")]
286    CooperativeCancellationUnavailable(String),
287    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
288    CancellationScopeExecutionUnavailable,
289    #[error("invalid cooperative cancellation: {0}")]
290    InvalidCooperativeCancellation(String),
291    #[error("activity execution no longer owns its claim: {0}")]
292    ActivityExecutionAbandoned(String),
293    #[error(transparent)]
294    InvalidActivityOptions(ActivityOptionsError),
295    #[error(transparent)]
296    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
297    #[doc(hidden)]
298    #[error("workflow requested continue as new")]
299    ContinueAsNew(ContinueAsNewRequest),
300}
301
302/// Validation failure for a durable condition-wait definition.
303#[derive(Clone, Debug, Error, PartialEq, Eq)]
304pub enum ConditionWaitOptionsError {
305    #[error("condition_key must be non-empty")]
306    EmptyKey,
307    #[error("condition_definition_fingerprint must be non-empty")]
308    EmptyPredicateIdentity,
309    #[error("condition timeout is too large for the worker protocol")]
310    TimeoutOverflow,
311}
312
313/// Stable identity and optional durable timeout for a condition wait.
314///
315/// `predicate_identity` is recorded as the worker protocol's
316/// `condition_definition_fingerprint` and must change whenever predicate
317/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
318/// is written inline; it derives this identity from the predicate tokens.
319#[derive(Clone, Debug, PartialEq, Eq)]
320pub struct ConditionWaitOptions {
321    condition_key: String,
322    predicate_identity: String,
323    timeout: Option<Duration>,
324}
325
326impl ConditionWaitOptions {
327    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
328        Self {
329            condition_key: condition_key.into(),
330            predicate_identity: predicate_identity.into(),
331            timeout: None,
332        }
333    }
334
335    pub fn timeout(mut self, timeout: Duration) -> Self {
336        self.timeout = Some(timeout);
337        self
338    }
339
340    fn validate(
341        &self,
342    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
343        let condition_key = self.condition_key.trim();
344        if condition_key.is_empty() {
345            return Err(ConditionWaitOptionsError::EmptyKey);
346        }
347        let predicate_identity = self.predicate_identity.trim();
348        if predicate_identity.is_empty() {
349            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
350        }
351        let timeout_seconds = self
352            .timeout
353            .map(|timeout| {
354                timeout
355                    .as_secs()
356                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
357                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
358            })
359            .transpose()?;
360
361        Ok(ValidatedConditionWaitOptions {
362            condition_key: condition_key.to_string(),
363            predicate_identity: predicate_identity.to_string(),
364            timeout_seconds,
365        })
366    }
367}
368
369#[derive(Clone, Debug, PartialEq, Eq)]
370struct ValidatedConditionWaitOptions {
371    condition_key: String,
372    predicate_identity: String,
373    timeout_seconds: Option<u64>,
374}
375
376const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
377
378/// Unambiguous terminal result of a durable condition wait.
379#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
380#[serde(rename_all = "snake_case")]
381pub enum ConditionWaitResult {
382    Satisfied,
383    TimedOut,
384}
385
386impl ConditionWaitResult {
387    pub fn is_satisfied(self) -> bool {
388        self == Self::Satisfied
389    }
390
391    pub fn is_timed_out(self) -> bool {
392        self == Self::TimedOut
393    }
394}
395
396/// Build the stable condition definition identity used by [`wait_condition!`].
397#[doc(hidden)]
398pub fn __condition_definition_fingerprint(source: &str) -> String {
399    let mut digest = Sha256::new();
400    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
401    digest.update(source.as_bytes());
402    format!("sha256:{:x}", digest.finalize())
403}
404
405/// Create a durable condition wait whose predicate definition is fingerprinted
406/// from its inline Rust tokens.
407///
408/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
409/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
410#[macro_export]
411macro_rules! wait_condition {
412    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
413        $ctx.wait_condition(
414            $crate::ConditionWaitOptions::new(
415                $key,
416                $crate::__condition_definition_fingerprint(concat!(
417                    module_path!(),
418                    "\0",
419                    stringify!($predicate)
420                )),
421            )
422            .timeout($timeout),
423            $predicate,
424        )
425    }};
426    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
427        $ctx.wait_condition(
428            $crate::ConditionWaitOptions::new(
429                $key,
430                $crate::__condition_definition_fingerprint(concat!(
431                    module_path!(),
432                    "\0",
433                    stringify!($predicate)
434                )),
435            ),
436            $predicate,
437        )
438    }};
439}
440
441const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
442const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
443const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
444const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
445const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
446
447/// Validation failure for a typed workflow search-attribute update.
448#[derive(Clone, Debug, Error, PartialEq, Eq)]
449pub enum SearchAttributeUpdateError {
450    #[error("search-attribute update requires at least one attribute")]
451    Empty,
452    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
453    InvalidKey(String),
454    #[error("search-attribute update exceeds the limit of 100 attributes")]
455    TooManyAttributes,
456    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
457    ValueTooLong {
458        key: String,
459        kind: &'static str,
460        limit: usize,
461    },
462    #[error(
463        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
464    )]
465    EmptyString(String),
466    #[error("search attribute {0:?} has a non-finite float value")]
467    NonFiniteFloat(String),
468    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
469    InvalidDateTime(String),
470    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
471    PayloadTooLarge,
472}
473
474/// One public typed search-attribute value.
475#[derive(Clone, Debug, PartialEq)]
476pub enum SearchAttributeValue {
477    String(String),
478    Keyword(String),
479    KeywordList(Vec<String>),
480    Int(i64),
481    Float(f64),
482    Bool(bool),
483    DateTime(String),
484    Delete,
485}
486
487impl SearchAttributeValue {
488    fn type_name(&self) -> Option<&'static str> {
489        match self {
490            Self::String(_) => Some("string"),
491            Self::Keyword(_) => Some("keyword"),
492            Self::KeywordList(_) => Some("keyword_list"),
493            Self::Int(_) => Some("int"),
494            Self::Float(_) => Some("float"),
495            Self::Bool(_) => Some("bool"),
496            Self::DateTime(_) => Some("datetime"),
497            Self::Delete => None,
498        }
499    }
500
501    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
502        let normalize_string = |value: String, kind: &'static str, limit: usize| {
503            let value = value.trim().to_string();
504            if value.is_empty() {
505                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
506            }
507            if value.len() > limit {
508                return Err(SearchAttributeUpdateError::ValueTooLong {
509                    key: key.to_string(),
510                    kind,
511                    limit,
512                });
513            }
514            Ok(value)
515        };
516
517        match self {
518            Self::String(value) => Ok(Self::String(normalize_string(
519                value,
520                "string",
521                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
522            )?)),
523            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
524                value,
525                "keyword",
526                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
527            )?)),
528            Self::KeywordList(values) => {
529                let values = values
530                    .into_iter()
531                    .map(|value| {
532                        let value = value.trim().to_string();
533                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
534                            return Err(SearchAttributeUpdateError::ValueTooLong {
535                                key: key.to_string(),
536                                kind: "keyword-list entry",
537                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
538                            });
539                        }
540                        Ok(value)
541                    })
542                    .collect::<std::result::Result<Vec<_>, _>>()?;
543                Ok(Self::KeywordList(values))
544            }
545            Self::Float(value) if !value.is_finite() => {
546                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
547            }
548            Self::DateTime(value) => {
549                let value =
550                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
551                if DateTime::parse_from_rfc3339(&value).is_err() {
552                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
553                }
554                Ok(Self::DateTime(value))
555            }
556            value => Ok(value),
557        }
558    }
559
560    fn into_json(self) -> Value {
561        match self {
562            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
563                Value::String(value)
564            }
565            Self::KeywordList(values) => {
566                Value::Array(values.into_iter().map(Value::String).collect())
567            }
568            Self::Int(value) => json!(value),
569            Self::Float(value) => json!(value),
570            Self::Bool(value) => json!(value),
571            Self::Delete => Value::Null,
572        }
573    }
574}
575
576/// Validated typed workflow-side search-attribute mutation.
577#[derive(Clone, Debug, Default, PartialEq)]
578pub struct SearchAttributeUpdate {
579    attributes: BTreeMap<String, SearchAttributeValue>,
580}
581
582impl SearchAttributeUpdate {
583    pub fn new() -> Self {
584        Self::default()
585    }
586
587    pub fn set(
588        mut self,
589        key: impl Into<String>,
590        value: SearchAttributeValue,
591    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
592        let key = key.into();
593        validate_search_attribute_key(&key)?;
594        if !self.attributes.contains_key(&key)
595            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
596        {
597            return Err(SearchAttributeUpdateError::TooManyAttributes);
598        }
599        self.attributes.insert(key.clone(), value.normalized(&key)?);
600        self.validate_size()?;
601        Ok(self)
602    }
603
604    pub fn string(
605        self,
606        key: impl Into<String>,
607        value: impl Into<String>,
608    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
609        self.set(key, SearchAttributeValue::String(value.into()))
610    }
611
612    pub fn keyword(
613        self,
614        key: impl Into<String>,
615        value: impl Into<String>,
616    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
617        self.set(key, SearchAttributeValue::Keyword(value.into()))
618    }
619
620    pub fn keyword_list<I, V>(
621        self,
622        key: impl Into<String>,
623        values: I,
624    ) -> std::result::Result<Self, SearchAttributeUpdateError>
625    where
626        I: IntoIterator<Item = V>,
627        V: Into<String>,
628    {
629        self.set(
630            key,
631            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
632        )
633    }
634
635    pub fn int(
636        self,
637        key: impl Into<String>,
638        value: i64,
639    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
640        self.set(key, SearchAttributeValue::Int(value))
641    }
642
643    pub fn float(
644        self,
645        key: impl Into<String>,
646        value: f64,
647    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
648        self.set(key, SearchAttributeValue::Float(value))
649    }
650
651    pub fn bool(
652        self,
653        key: impl Into<String>,
654        value: bool,
655    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
656        self.set(key, SearchAttributeValue::Bool(value))
657    }
658
659    pub fn datetime(
660        self,
661        key: impl Into<String>,
662        value: impl Into<String>,
663    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
664        self.set(key, SearchAttributeValue::DateTime(value.into()))
665    }
666
667    pub fn delete(
668        self,
669        key: impl Into<String>,
670    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
671        self.set(key, SearchAttributeValue::Delete)
672    }
673
674    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
675        let (attributes, _) = self.clone().into_wire_parts();
676        if serde_json::to_vec(&attributes)
677            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
678            .unwrap_or(true)
679        {
680            return Err(SearchAttributeUpdateError::PayloadTooLarge);
681        }
682        Ok(())
683    }
684
685    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
686        let mut attributes = serde_json::Map::new();
687        let mut attribute_types = BTreeMap::new();
688        for (key, value) in self.attributes {
689            if let Some(type_name) = value.type_name() {
690                attribute_types.insert(key.clone(), type_name.to_string());
691            }
692            attributes.insert(key, value.into_json());
693        }
694        (Value::Object(attributes), attribute_types)
695    }
696
697    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
698        if self.attributes.is_empty() {
699            return Err(SearchAttributeUpdateError::Empty);
700        }
701        self.validate_size()
702    }
703}
704
705fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
706    let valid = !key.is_empty()
707        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
708        && key
709            .bytes()
710            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
711    if valid {
712        Ok(())
713    } else {
714        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
715    }
716}
717
718/// The registered handler family reported by [`Error::HandlerType`].
719#[derive(Clone, Copy, Debug, PartialEq, Eq)]
720pub enum HandlerKind {
721    Workflow,
722    Activity,
723}
724
725impl std::fmt::Display for HandlerKind {
726    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
727        formatter.write_str(match self {
728            Self::Workflow => "workflow",
729            Self::Activity => "activity",
730        })
731    }
732}
733
734/// Whether a typed handler failed to adapt its input or result.
735#[derive(Clone, Copy, Debug, PartialEq, Eq)]
736pub enum HandlerValueKind {
737    Input,
738    Result,
739}
740
741impl std::fmt::Display for HandlerValueKind {
742    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
743        formatter.write_str(match self {
744            Self::Input => "input",
745            Self::Result => "result",
746        })
747    }
748}
749
750/// The lifecycle command sent to a workflow execution.
751#[derive(Clone, Copy, Debug, PartialEq, Eq)]
752pub enum WorkflowCommandKind {
753    Cancel,
754    Terminate,
755}
756
757impl WorkflowCommandKind {
758    fn as_str(self) -> &'static str {
759        match self {
760            Self::Cancel => "cancel",
761            Self::Terminate => "terminate",
762        }
763    }
764}
765
766/// Optional structured fields for a cancellation or termination request.
767#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
768pub struct WorkflowCommandOptions {
769    #[serde(skip_serializing_if = "Option::is_none")]
770    pub reason: Option<String>,
771    #[serde(skip_serializing_if = "Option::is_none")]
772    pub request_id: Option<String>,
773}
774
775/// Server-enforced timeout policy for a workflow start.
776///
777/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
778/// only bounds how long the caller waits. A server deadline produces a terminal
779/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
780/// `run_timeout`.
781#[derive(Clone, Debug, PartialEq, Eq)]
782pub struct WorkflowStartOptions {
783    pub execution_timeout_seconds: u64,
784    pub run_timeout_seconds: u64,
785}
786
787impl Default for WorkflowStartOptions {
788    fn default() -> Self {
789        Self {
790            execution_timeout_seconds: 3600,
791            run_timeout_seconds: 600,
792        }
793    }
794}
795
796impl WorkflowStartOptions {
797    pub fn new() -> Self {
798        Self::default()
799    }
800
801    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
802        self.execution_timeout_seconds = seconds;
803        self
804    }
805
806    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
807        self.run_timeout_seconds = seconds;
808        self
809    }
810
811    fn validate(&self) -> Result<()> {
812        if self.execution_timeout_seconds == 0 {
813            return Err(Error::Codec(
814                "execution_timeout_seconds must be at least 1".to_string(),
815            ));
816        }
817        if self.run_timeout_seconds == 0 {
818            return Err(Error::Codec(
819                "run_timeout_seconds must be at least 1".to_string(),
820            ));
821        }
822        if self.run_timeout_seconds > self.execution_timeout_seconds {
823            return Err(Error::Codec(
824                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
825            ));
826        }
827
828        Ok(())
829    }
830}
831
832/// Optional routing overrides for a continue-as-new transition.
833///
834/// Omitted values retain the current workflow type and task queue. Server-owned
835/// instance metadata is not accepted here and is carried by the server.
836#[derive(Clone, Debug, Default, PartialEq, Eq)]
837pub struct ContinueAsNewOptions {
838    pub workflow_type: Option<String>,
839    pub task_queue: Option<String>,
840}
841
842impl ContinueAsNewOptions {
843    pub fn new() -> Self {
844        Self::default()
845    }
846
847    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
848        self.workflow_type = Some(workflow_type.into());
849        self
850    }
851
852    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
853        self.task_queue = Some(task_queue.into());
854        self
855    }
856
857    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
858        for (field, value) in [
859            ("workflow_type", self.workflow_type.as_deref()),
860            ("task_queue", self.task_queue.as_deref()),
861        ] {
862            if value.is_some_and(|value| value.trim().is_empty()) {
863                return Err(ContinueAsNewOptionsError {
864                    field,
865                    message: format!("{field} must not be empty"),
866                });
867            }
868        }
869        Ok(())
870    }
871}
872
873/// A stable validation error raised before a continue-as-new command is emitted.
874#[derive(Clone, Debug, Error, PartialEq, Eq)]
875#[error("invalid continue-as-new option {field}: {message}")]
876pub struct ContinueAsNewOptionsError {
877    pub field: &'static str,
878    pub message: String,
879}
880
881/// Public history-budget information attached to the current workflow task.
882#[derive(Clone, Debug, Default, PartialEq, Eq)]
883pub struct WorkflowHistoryBudget {
884    pub event_count: u64,
885    pub size_bytes: Option<u64>,
886    pub continue_as_new_recommended: bool,
887    pub pressure: Option<String>,
888}
889
890#[doc(hidden)]
891#[derive(Clone, Debug)]
892pub struct ContinueAsNewRequest {
893    arguments: AvroValue,
894    options: ContinueAsNewOptions,
895}
896
897impl WorkflowCommandOptions {
898    pub fn new() -> Self {
899        Self::default()
900    }
901
902    pub fn reason(mut self, reason: impl Into<String>) -> Self {
903        self.reason = Some(reason.into());
904        self
905    }
906
907    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
908        self.request_id = Some(request_id.into());
909        self
910    }
911}
912
913/// The accepted, machine-readable result of a lifecycle command.
914#[derive(Clone, Debug, PartialEq)]
915pub struct WorkflowCommandResult {
916    pub command: WorkflowCommandKind,
917    pub workflow_id: String,
918    pub run_id: Option<String>,
919    pub outcome: Option<String>,
920    pub reason: Option<String>,
921    pub command_status: Option<String>,
922    pub raw: Value,
923}
924
925/// A new run continuing a failed run from its recorded activity boundary.
926#[derive(Clone, Debug, PartialEq)]
927pub struct WorkflowRedriveResult {
928    pub workflow_id: String,
929    pub source_run_id: String,
930    pub run_id: String,
931    pub resume_step_sequence: u64,
932    pub raw: Value,
933}
934
935/// A stable rejection returned by instance- or selected-run lifecycle commands.
936#[derive(Clone, Debug, Error)]
937#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
938pub struct WorkflowCommandRejection {
939    pub command: WorkflowCommandKind,
940    pub status: u16,
941    pub reason: String,
942    pub message: String,
943    pub workflow_id: String,
944    pub run_id: Option<String>,
945    pub target_scope: Option<String>,
946    pub body: Value,
947}
948
949/// Stable terminal categories returned by [`WorkflowHandle::result`].
950#[derive(Clone, Copy, Debug, PartialEq, Eq)]
951pub enum WorkflowTerminalKind {
952    Failed,
953    Cancelled,
954    Terminated,
955    TimedOut,
956}
957
958/// A typed terminal workflow outcome with durable identity and failure metadata.
959///
960/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
961/// of parsing its display representation. Fields remain `None` when an older
962/// server did not publish that metadata.
963#[derive(Clone, Debug, Error)]
964#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
965pub struct WorkflowTerminalOutcome {
966    pub kind: WorkflowTerminalKind,
967    pub workflow_id: String,
968    pub run_id: Option<String>,
969    pub reason: String,
970    pub failure_category: Option<String>,
971    pub failure_id: Option<String>,
972    pub exception_type: Option<String>,
973    pub exception_class: Option<String>,
974    pub non_retryable: Option<bool>,
975    pub message: Option<String>,
976    pub exception: Option<Value>,
977    pub raw: Value,
978}
979
980/// A worker-side activity settlement or heartbeat rejected by durable state.
981#[derive(Clone, Debug, Error)]
982#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
983pub struct ActivityTaskRejection {
984    pub operation: String,
985    pub status: u16,
986    pub reason: String,
987    pub task_id: String,
988    pub activity_attempt_id: String,
989    pub cancel_requested: bool,
990    pub can_continue: Option<bool>,
991    pub run_closed_reason: Option<String>,
992    pub body: Value,
993}
994
995/// Stable validation categories for [`ActivityOptions`].
996#[derive(Clone, Copy, Debug, PartialEq, Eq)]
997pub enum ActivityOptionsErrorKind {
998    EmptyTaskQueue,
999    EmptyRetryPolicy,
1000    InvalidMaxAttempts,
1001    BackoffWithoutRetryBudget,
1002    TooManyBackoffIntervals,
1003    InvalidBackoffCoefficient,
1004    BackoffGenerationTooLarge,
1005    BackoffOverflow,
1006    EmptyNonRetryableErrorType,
1007    TimeoutNotPositive,
1008    MissingTotalTimeout,
1009    TimeoutOverflow,
1010    TimeoutOrder,
1011}
1012
1013/// A machine-readable activity-options validation failure.
1014#[derive(Clone, Debug, Error, PartialEq, Eq)]
1015#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1016pub struct ActivityOptionsError {
1017    pub kind: ActivityOptionsErrorKind,
1018    pub field: Option<&'static str>,
1019    pub message: String,
1020}
1021
1022impl ActivityOptionsError {
1023    fn new(
1024        kind: ActivityOptionsErrorKind,
1025        field: Option<&'static str>,
1026        message: impl Into<String>,
1027    ) -> Self {
1028        Self {
1029            kind,
1030            field,
1031            message: message.into(),
1032        }
1033    }
1034}
1035
1036/// Stable terminal categories returned when an awaited activity does not succeed.
1037#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1038pub enum ActivityFailureKind {
1039    Failed,
1040    Cancelled,
1041    TimedOut,
1042}
1043
1044/// A stable, machine-readable terminal activity failure.
1045///
1046/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1047/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1048#[derive(Clone, Debug, Error, PartialEq)]
1049#[error("activity failed ({reason}): {message}")]
1050pub struct ActivityFailure {
1051    pub kind: ActivityFailureKind,
1052    pub reason: String,
1053    pub message: String,
1054    pub activity_execution_id: Option<String>,
1055    pub activity_attempt_id: Option<String>,
1056    pub activity_type: Option<String>,
1057    pub activity_class: Option<String>,
1058    pub attempt_number: Option<u64>,
1059    pub failure_id: Option<String>,
1060    pub failure_category: Option<String>,
1061    pub timeout_kind: Option<String>,
1062    pub non_retryable: bool,
1063    pub exception_type: Option<String>,
1064    pub exception_class: Option<String>,
1065    pub code: Option<Value>,
1066    pub exception: Option<Value>,
1067}
1068
1069/// Stable terminal categories returned when an awaited child does not succeed.
1070#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1071pub enum ChildWorkflowFailureKind {
1072    Failed,
1073    Cancelled,
1074    Terminated,
1075}
1076
1077/// A stable, machine-readable child workflow failure delivered to its parent.
1078///
1079/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1080/// of parsing the display message. Child and parent identifiers retain the
1081/// relationship recorded in durable history across worker restarts.
1082#[derive(Clone, Debug, Error)]
1083#[error("child workflow failed ({reason}): {message}")]
1084pub struct ChildWorkflowFailure {
1085    pub kind: ChildWorkflowFailureKind,
1086    pub reason: String,
1087    pub message: String,
1088    pub parent_workflow_id: Option<String>,
1089    pub parent_workflow_run_id: Option<String>,
1090    pub child_workflow_id: Option<String>,
1091    pub child_workflow_run_id: Option<String>,
1092    pub child_workflow_type: Option<String>,
1093    pub failure_id: Option<String>,
1094    pub failure_category: Option<String>,
1095    pub exception_type: Option<String>,
1096    pub exception_class: Option<String>,
1097    pub non_retryable: bool,
1098    pub code: Option<Value>,
1099    pub exception: Option<Value>,
1100}
1101
1102/// The identity of one durable workflow execution.
1103#[derive(Clone, Debug, PartialEq, Eq)]
1104pub struct WorkflowIdentity {
1105    pub workflow_id: Option<String>,
1106    pub run_id: Option<String>,
1107}
1108
1109/// A successful child result together with its durable parent-child identity.
1110#[derive(Clone, Debug, PartialEq)]
1111pub struct ChildWorkflowResult {
1112    pub parent: WorkflowIdentity,
1113    pub child: WorkflowIdentity,
1114    pub child_workflow_type: Option<String>,
1115    pub result: Value,
1116}
1117
1118/// Lossless successful child result for fixed Avro Value workflows.
1119#[derive(Clone, Debug, PartialEq)]
1120pub struct ChildWorkflowAvroResult {
1121    pub parent: WorkflowIdentity,
1122    pub child: WorkflowIdentity,
1123    pub child_workflow_type: Option<String>,
1124    pub result: AvroValue,
1125}
1126
1127/// Stable user-facing identity for one member of a durable selection group.
1128#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1129#[serde(untagged)]
1130pub enum SelectionKey {
1131    Index(usize),
1132    Name(String),
1133}
1134
1135impl From<usize> for SelectionKey {
1136    fn from(value: usize) -> Self {
1137        Self::Index(value)
1138    }
1139}
1140
1141impl From<String> for SelectionKey {
1142    fn from(value: String) -> Self {
1143        Self::Name(value)
1144    }
1145}
1146
1147impl From<&str> for SelectionKey {
1148    fn from(value: &str) -> Self {
1149        Self::Name(value.to_string())
1150    }
1151}
1152
1153/// Typed result of explicitly awaiting a cancelled non-winning operation.
1154#[derive(Clone, Debug, Error, PartialEq, Eq)]
1155#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1156pub struct DurableOperationCancelled {
1157    pub selection_group_id: String,
1158    pub member_key: SelectionKey,
1159    pub member_index: usize,
1160    pub operation_kind: String,
1161    pub operation_identity: String,
1162}
1163
1164/// Stable identity for one enclosing deterministic parallel group.
1165///
1166/// The same fields are attached to every ordinary activity, timer, or child
1167/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1168/// no Rust-specific wire command is introduced.
1169#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1170pub struct ParallelGroupMetadata {
1171    pub parallel_group_id: String,
1172    pub parallel_group_kind: String,
1173    pub parallel_group_base_sequence: u64,
1174    pub parallel_group_size: usize,
1175    pub parallel_group_index: usize,
1176    #[serde(default, skip_serializing_if = "Option::is_none")]
1177    pub parallel_group_mode: Option<String>,
1178    #[serde(default, skip_serializing_if = "Option::is_none")]
1179    pub selection_member_key: Option<SelectionKey>,
1180    #[serde(default, skip_serializing_if = "Option::is_none")]
1181    pub selection_member_index: Option<usize>,
1182    #[serde(default, skip_serializing_if = "Option::is_none")]
1183    pub selection_member_base_sequence: Option<u64>,
1184    #[serde(default, skip_serializing_if = "Option::is_none")]
1185    pub selection_member_size: Option<usize>,
1186    #[serde(default, skip_serializing_if = "Option::is_none")]
1187    pub selection_member_kind: Option<String>,
1188}
1189
1190/// One input-ordered result returned by [`WorkflowContext::parallel`].
1191#[derive(Clone, Debug, PartialEq)]
1192pub enum ParallelResult {
1193    Activity(Value),
1194    ChildWorkflow(ChildWorkflowResult),
1195    Timer,
1196    Signal(Vec<Value>),
1197    Condition(ConditionWaitResult),
1198    Group(Vec<ParallelResult>),
1199}
1200
1201/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1202#[derive(Clone, Debug, PartialEq)]
1203pub enum ParallelAvroResult {
1204    Activity(AvroValue),
1205    ChildWorkflow(ChildWorkflowAvroResult),
1206    Timer,
1207    Signal(Vec<AvroValue>),
1208    Condition(ConditionWaitResult),
1209    Group(Vec<ParallelAvroResult>),
1210}
1211
1212impl ParallelAvroResult {
1213    fn into_json_result(self) -> Result<ParallelResult> {
1214        match self {
1215            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1216            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1217                parent: result.parent,
1218                child: result.child,
1219                child_workflow_type: result.child_workflow_type,
1220                result: result.result.into_json()?,
1221            })),
1222            Self::Timer => Ok(ParallelResult::Timer),
1223            Self::Signal(values) => Ok(ParallelResult::Signal(
1224                values
1225                    .into_iter()
1226                    .map(AvroValue::into_json)
1227                    .collect::<Result<Vec<_>>>()?,
1228            )),
1229            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1230            Self::Group(results) => Ok(ParallelResult::Group(
1231                results
1232                    .into_iter()
1233                    .map(Self::into_json_result)
1234                    .collect::<Result<Vec<_>>>()?,
1235            )),
1236        }
1237    }
1238}
1239
1240/// One successful leaf retained when another parallel member failed.
1241#[derive(Clone, Debug, PartialEq)]
1242pub struct ParallelCompletion {
1243    pub member_path: Vec<usize>,
1244    pub result: ParallelResult,
1245}
1246
1247/// A deterministic join failed after some siblings had already completed.
1248///
1249/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1250/// error. `completed` is declaration ordered and contains only durable
1251/// successes observed in the same replay. Late sibling completions can add
1252/// entries on a later replay without changing `member_path` or the selected
1253/// positional failure.
1254#[derive(Debug, Error)]
1255#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1256pub struct ParallelFailure {
1257    pub group_id: String,
1258    pub member_path: Vec<usize>,
1259    pub group_path: Vec<ParallelGroupMetadata>,
1260    pub completed: Vec<ParallelCompletion>,
1261    #[source]
1262    pub cause: Box<Error>,
1263}
1264
1265/// Stable validation error returned before an invalid group emits commands.
1266#[derive(Clone, Debug, Error, PartialEq, Eq)]
1267#[error("invalid deterministic parallel group ({reason}): {message}")]
1268pub struct ParallelGroupError {
1269    pub reason: &'static str,
1270    pub member_path: Vec<usize>,
1271    pub message: String,
1272}
1273
1274/// Cooperative workflow cancellation observed at an author-controlled point.
1275#[derive(Clone, Debug, Error, PartialEq, Eq)]
1276#[error("workflow cancellation was requested")]
1277pub struct WorkflowCancellationRequested;
1278
1279/// A forward saga failure followed by a terminal compensation failure.
1280#[derive(Debug, Error)]
1281#[error(
1282    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1283)]
1284pub struct SagaCompensationFailure {
1285    pub initiating_failure: Box<Error>,
1286    pub compensation_failure: Box<Error>,
1287    pub compensation_activity_type: String,
1288    pub compensation_registration_order: usize,
1289}
1290
1291/// Server behavior when a parent closes while its child is still open.
1292#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1293pub enum ParentClosePolicy {
1294    #[default]
1295    Abandon,
1296    /// Legacy terminal cancellation without cooperative cleanup.
1297    RequestCancel,
1298    /// Request cooperative cleanup with the original lineage and deadline.
1299    RequestCancellation,
1300    Terminate,
1301}
1302
1303impl ParentClosePolicy {
1304    fn as_str(self) -> &'static str {
1305        match self {
1306            Self::Abandon => "abandon",
1307            Self::RequestCancel => "request_cancel",
1308            Self::RequestCancellation => "request_cancellation",
1309            Self::Terminate => "terminate",
1310        }
1311    }
1312}
1313
1314/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1315#[non_exhaustive]
1316#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1317pub enum CancellationPolicy {
1318    /// Request cancellation and continue without waiting. Historical Activity default.
1319    TryCancel,
1320    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1321    WaitCancellationCompleted,
1322    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1323    #[default]
1324    Abandon,
1325}
1326
1327impl CancellationPolicy {
1328    fn as_str(self) -> &'static str {
1329        match self {
1330            Self::TryCancel => "try_cancel",
1331            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1332            Self::Abandon => "abandon",
1333        }
1334    }
1335}
1336
1337/// Durable retry policy for one child workflow invocation.
1338#[derive(Clone, Debug, Default, PartialEq, Eq)]
1339pub struct ChildWorkflowRetryPolicy {
1340    pub max_attempts: Option<u32>,
1341    pub backoff_seconds: Vec<u64>,
1342    pub non_retryable_error_types: Vec<String>,
1343}
1344
1345/// Options recorded with a child-workflow command.
1346///
1347/// The task queue is mandatory so routing is explicit and replay-stable.
1348#[derive(Clone, Debug, PartialEq, Eq)]
1349pub struct ChildWorkflowOptions {
1350    pub task_queue: String,
1351    pub parent_close_policy: ParentClosePolicy,
1352    pub cancellation_policy: CancellationPolicy,
1353    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1354    pub execution_timeout_seconds: Option<u64>,
1355    pub run_timeout_seconds: Option<u64>,
1356}
1357
1358impl ChildWorkflowOptions {
1359    pub fn new(task_queue: impl Into<String>) -> Self {
1360        Self {
1361            task_queue: task_queue.into(),
1362            parent_close_policy: ParentClosePolicy::Abandon,
1363            cancellation_policy: CancellationPolicy::Abandon,
1364            retry_policy: None,
1365            execution_timeout_seconds: None,
1366            run_timeout_seconds: None,
1367        }
1368    }
1369
1370    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1371        self.parent_close_policy = policy;
1372        self
1373    }
1374
1375    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1376        self.cancellation_policy = policy;
1377        self
1378    }
1379
1380    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1381        self.retry_policy = Some(policy);
1382        self
1383    }
1384
1385    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1386        self.execution_timeout_seconds = Some(seconds);
1387        self
1388    }
1389
1390    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1391        self.run_timeout_seconds = Some(seconds);
1392        self
1393    }
1394}
1395
1396/// Backoff intervals for one durable activity retry policy.
1397#[derive(Clone, Debug, PartialEq, Eq)]
1398pub enum ActivityBackoff {
1399    /// Use these intervals between attempts. The server repeats the final
1400    /// interval if the retry budget contains more attempts than entries.
1401    Explicit(Vec<Duration>),
1402    /// Generate one interval for every retry using integer exponential growth.
1403    Exponential {
1404        initial_interval: Duration,
1405        coefficient: u32,
1406        maximum_interval: Option<Duration>,
1407    },
1408}
1409
1410/// Durable server-side retry policy for one activity execution.
1411#[derive(Clone, Debug, Default, PartialEq, Eq)]
1412pub struct ActivityRetryPolicy {
1413    pub max_attempts: Option<u32>,
1414    pub backoff: Option<ActivityBackoff>,
1415    pub non_retryable_error_types: Vec<String>,
1416}
1417
1418impl ActivityRetryPolicy {
1419    /// Start a policy with a finite attempt budget, including the first attempt.
1420    pub fn new(max_attempts: u32) -> Self {
1421        Self {
1422            max_attempts: Some(max_attempts),
1423            ..Self::default()
1424        }
1425    }
1426
1427    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1428        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1429        self
1430    }
1431
1432    pub fn exponential_backoff(
1433        mut self,
1434        initial_interval: Duration,
1435        coefficient: u32,
1436        maximum_interval: Option<Duration>,
1437    ) -> Self {
1438        self.backoff = Some(ActivityBackoff::Exponential {
1439            initial_interval,
1440            coefficient,
1441            maximum_interval,
1442        });
1443        self
1444    }
1445
1446    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1447        self.non_retryable_error_types.push(error_type.into());
1448        self
1449    }
1450
1451    pub fn non_retryable_error_types(
1452        mut self,
1453        error_types: impl IntoIterator<Item = impl Into<String>>,
1454    ) -> Self {
1455        self.non_retryable_error_types
1456            .extend(error_types.into_iter().map(Into::into));
1457        self
1458    }
1459}
1460
1461/// Options recorded atomically on one deterministic `schedule_activity` command.
1462///
1463/// Durations are rounded up to whole seconds when encoded, so the server never
1464/// receives a shorter timeout or backoff than the caller requested.
1465#[derive(Clone, Debug, Default, PartialEq, Eq)]
1466pub struct ActivityOptions {
1467    pub task_queue: Option<String>,
1468    pub retry_policy: Option<ActivityRetryPolicy>,
1469    pub start_to_close_timeout: Option<Duration>,
1470    pub schedule_to_start_timeout: Option<Duration>,
1471    pub schedule_to_close_timeout: Option<Duration>,
1472    pub heartbeat_timeout: Option<Duration>,
1473    pub cancellation_policy: Option<CancellationPolicy>,
1474}
1475
1476impl ActivityOptions {
1477    pub fn new() -> Self {
1478        Self::default()
1479    }
1480
1481    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1482        self.task_queue = Some(task_queue.into());
1483        self
1484    }
1485
1486    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1487        self.retry_policy = Some(policy);
1488        self
1489    }
1490
1491    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1492        self.start_to_close_timeout = Some(timeout);
1493        self
1494    }
1495
1496    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1497        self.schedule_to_start_timeout = Some(timeout);
1498        self
1499    }
1500
1501    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1502        self.schedule_to_close_timeout = Some(timeout);
1503        self
1504    }
1505
1506    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1507        self.heartbeat_timeout = Some(timeout);
1508        self
1509    }
1510
1511    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1512        self.cancellation_policy = Some(policy);
1513        self
1514    }
1515
1516    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1517        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1518            && self.schedule_to_close_timeout.is_none()
1519        {
1520            return Err(ActivityOptionsError::new(
1521                ActivityOptionsErrorKind::MissingTotalTimeout,
1522                Some("schedule_to_close_timeout"),
1523                "remote Activity Abandon requires a finite positive total timeout",
1524            ));
1525        }
1526        if self
1527            .task_queue
1528            .as_deref()
1529            .is_some_and(|queue| queue.trim().is_empty())
1530        {
1531            return Err(ActivityOptionsError::new(
1532                ActivityOptionsErrorKind::EmptyTaskQueue,
1533                Some("task_queue"),
1534                "task_queue must not be empty",
1535            ));
1536        }
1537
1538        for (field, value) in [
1539            ("start_to_close_timeout", self.start_to_close_timeout),
1540            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1541            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1542            ("heartbeat_timeout", self.heartbeat_timeout),
1543        ] {
1544            if value.is_some_and(|value| value.is_zero()) {
1545                return Err(ActivityOptionsError::new(
1546                    ActivityOptionsErrorKind::TimeoutNotPositive,
1547                    Some(field),
1548                    format!("{field} must be positive"),
1549                ));
1550            }
1551        }
1552
1553        validate_timeout_order(
1554            "heartbeat_timeout",
1555            self.heartbeat_timeout,
1556            "start_to_close_timeout",
1557            self.start_to_close_timeout,
1558        )?;
1559        validate_timeout_order(
1560            "start_to_close_timeout",
1561            self.start_to_close_timeout,
1562            "schedule_to_close_timeout",
1563            self.schedule_to_close_timeout,
1564        )?;
1565        validate_timeout_order(
1566            "schedule_to_start_timeout",
1567            self.schedule_to_start_timeout,
1568            "schedule_to_close_timeout",
1569            self.schedule_to_close_timeout,
1570        )?;
1571
1572        Ok(ValidatedActivityOptions {
1573            task_queue: self.task_queue.clone(),
1574            retry_policy: self
1575                .retry_policy
1576                .as_ref()
1577                .map(validate_activity_retry_policy)
1578                .transpose()?,
1579            start_to_close_timeout: timeout_seconds(
1580                "start_to_close_timeout",
1581                self.start_to_close_timeout,
1582            )?,
1583            schedule_to_start_timeout: timeout_seconds(
1584                "schedule_to_start_timeout",
1585                self.schedule_to_start_timeout,
1586            )?,
1587            schedule_to_close_timeout: timeout_seconds(
1588                "schedule_to_close_timeout",
1589                self.schedule_to_close_timeout,
1590            )?,
1591            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1592            cancellation_policy: self.cancellation_policy,
1593        })
1594    }
1595}
1596
1597/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1598///
1599/// Constructors capture arguments but perform no I/O. The join validates the
1600/// complete tree, attaches the existing parallel-group metadata to every
1601/// ordinary command, schedules all leaves, and then suspends.
1602pub enum ParallelOperation {
1603    Activity {
1604        activity_type: String,
1605        options: ActivityOptions,
1606        arguments: Result<AvroValue>,
1607    },
1608    ChildWorkflow {
1609        workflow_type: String,
1610        options: ChildWorkflowOptions,
1611        arguments: Result<AvroValue>,
1612    },
1613    Timer(Duration),
1614    Signal(String),
1615    Condition {
1616        options: ConditionWaitOptions,
1617        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1618    },
1619    Group(Vec<ParallelOperation>),
1620}
1621
1622impl ParallelOperation {
1623    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1624        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1625    }
1626
1627    pub fn activity_with_options<T: Serialize>(
1628        activity_type: impl Into<String>,
1629        options: ActivityOptions,
1630        args: T,
1631    ) -> Self {
1632        Self::Activity {
1633            activity_type: activity_type.into(),
1634            options,
1635            arguments: AvroValue::from_serialize(&args),
1636        }
1637    }
1638
1639    pub fn child_workflow<T: Serialize>(
1640        workflow_type: impl Into<String>,
1641        options: ChildWorkflowOptions,
1642        args: T,
1643    ) -> Self {
1644        Self::ChildWorkflow {
1645            workflow_type: workflow_type.into(),
1646            options,
1647            arguments: AvroValue::from_serialize(&args),
1648        }
1649    }
1650
1651    pub fn timer(duration: Duration) -> Self {
1652        Self::Timer(duration)
1653    }
1654
1655    pub fn signal(signal_name: impl Into<String>) -> Self {
1656        Self::Signal(signal_name.into())
1657    }
1658
1659    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1660    where
1661        F: Fn() -> Result<bool> + Send + 'static,
1662    {
1663        Self::Condition {
1664            options,
1665            predicate: Box::new(predicate),
1666        }
1667    }
1668
1669    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1670        Self::Group(operations)
1671    }
1672}
1673
1674#[derive(Clone, Debug)]
1675struct ValidatedActivityOptions {
1676    task_queue: Option<String>,
1677    retry_policy: Option<Value>,
1678    start_to_close_timeout: Option<u64>,
1679    schedule_to_start_timeout: Option<u64>,
1680    schedule_to_close_timeout: Option<u64>,
1681    heartbeat_timeout: Option<u64>,
1682    cancellation_policy: Option<CancellationPolicy>,
1683}
1684
1685fn validate_timeout_order(
1686    smaller_name: &'static str,
1687    smaller: Option<Duration>,
1688    larger_name: &'static str,
1689    larger: Option<Duration>,
1690) -> std::result::Result<(), ActivityOptionsError> {
1691    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1692        return Err(ActivityOptionsError::new(
1693            ActivityOptionsErrorKind::TimeoutOrder,
1694            Some(smaller_name),
1695            format!("{smaller_name} must be <= {larger_name}"),
1696        ));
1697    }
1698    Ok(())
1699}
1700
1701fn timeout_seconds(
1702    field: &'static str,
1703    value: Option<Duration>,
1704) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1705    value
1706        .map(|value| {
1707            activity_protocol_seconds(value).ok_or_else(|| {
1708                ActivityOptionsError::new(
1709                    ActivityOptionsErrorKind::TimeoutOverflow,
1710                    Some(field),
1711                    format!("{field} is too large for the worker protocol"),
1712                )
1713            })
1714        })
1715        .transpose()
1716}
1717
1718fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1719    value
1720        .as_secs()
1721        .checked_add(u64::from(value.subsec_nanos() > 0))
1722}
1723
1724fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1725    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1726}
1727
1728fn validate_activity_retry_policy(
1729    policy: &ActivityRetryPolicy,
1730) -> std::result::Result<Value, ActivityOptionsError> {
1731    if policy.max_attempts.is_none()
1732        && policy.backoff.is_none()
1733        && policy.non_retryable_error_types.is_empty()
1734    {
1735        return Err(ActivityOptionsError::new(
1736            ActivityOptionsErrorKind::EmptyRetryPolicy,
1737            Some("retry_policy"),
1738            "retry_policy must configure at least one field",
1739        ));
1740    }
1741    if policy.max_attempts == Some(0) {
1742        return Err(ActivityOptionsError::new(
1743            ActivityOptionsErrorKind::InvalidMaxAttempts,
1744            Some("retry_policy.max_attempts"),
1745            "max_attempts must be >= 1",
1746        ));
1747    }
1748    if policy
1749        .non_retryable_error_types
1750        .iter()
1751        .any(|error_type| error_type.trim().is_empty())
1752    {
1753        return Err(ActivityOptionsError::new(
1754            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1755            Some("retry_policy.non_retryable_error_types"),
1756            "non_retryable_error_types must not contain empty values",
1757        ));
1758    }
1759
1760    let backoff_seconds = match &policy.backoff {
1761        None => None,
1762        Some(backoff) => {
1763            let max_attempts = policy.max_attempts.ok_or_else(|| {
1764                ActivityOptionsError::new(
1765                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1766                    Some("retry_policy.backoff"),
1767                    "backoff requires max_attempts",
1768                )
1769            })?;
1770            let retry_count = max_attempts.saturating_sub(1) as usize;
1771            let intervals = match backoff {
1772                ActivityBackoff::Explicit(intervals) => {
1773                    if intervals.len() > retry_count {
1774                        return Err(ActivityOptionsError::new(
1775                            ActivityOptionsErrorKind::TooManyBackoffIntervals,
1776                            Some("retry_policy.backoff"),
1777                            "backoff interval count must not exceed max_attempts - 1",
1778                        ));
1779                    }
1780                    intervals.clone()
1781                }
1782                ActivityBackoff::Exponential {
1783                    initial_interval,
1784                    coefficient,
1785                    maximum_interval,
1786                } => {
1787                    if *coefficient < 1 {
1788                        return Err(ActivityOptionsError::new(
1789                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1790                            Some("retry_policy.backoff.coefficient"),
1791                            "backoff coefficient must be >= 1",
1792                        ));
1793                    }
1794                    if retry_count > 10_000 {
1795                        return Err(ActivityOptionsError::new(
1796                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1797                            Some("retry_policy.max_attempts"),
1798                            "generated backoff supports at most 10000 retry intervals",
1799                        ));
1800                    }
1801                    let mut current = *initial_interval;
1802                    let mut intervals = Vec::with_capacity(retry_count);
1803                    for _ in 0..retry_count {
1804                        let interval = maximum_interval
1805                            .map(|maximum| current.min(maximum))
1806                            .unwrap_or(current);
1807                        intervals.push(interval);
1808                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1809                            break;
1810                        }
1811                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1812                            ActivityOptionsError::new(
1813                                ActivityOptionsErrorKind::BackoffOverflow,
1814                                Some("retry_policy.backoff"),
1815                                "generated backoff interval overflowed",
1816                            )
1817                        })?;
1818                    }
1819                    intervals
1820                }
1821            };
1822            Some(
1823                intervals
1824                    .into_iter()
1825                    .map(|interval| {
1826                        activity_protocol_seconds(interval).ok_or_else(|| {
1827                            ActivityOptionsError::new(
1828                                ActivityOptionsErrorKind::BackoffOverflow,
1829                                Some("retry_policy.backoff"),
1830                                "backoff interval is too large for the worker protocol",
1831                            )
1832                        })
1833                    })
1834                    .collect::<std::result::Result<Vec<_>, _>>()?,
1835            )
1836        }
1837    };
1838
1839    let mut encoded = serde_json::Map::new();
1840    if let Some(max_attempts) = policy.max_attempts {
1841        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1842    }
1843    if let Some(backoff_seconds) = backoff_seconds {
1844        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1845    }
1846    if !policy.non_retryable_error_types.is_empty() {
1847        let mut canonical_error_types = Vec::new();
1848        for error_type in policy
1849            .non_retryable_error_types
1850            .iter()
1851            .map(|error_type| error_type.trim())
1852        {
1853            if !canonical_error_types.contains(&error_type) {
1854                canonical_error_types.push(error_type);
1855            }
1856        }
1857        encoded.insert(
1858            "non_retryable_error_types".to_string(),
1859            json!(canonical_error_types),
1860        );
1861    }
1862    Ok(Value::Object(encoded))
1863}
1864
1865/// A stable, machine-readable failure raised when workflow code no longer
1866/// reconstructs the durable command stream recorded in history.
1867#[derive(Clone, Debug, Error)]
1868#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1869pub struct ReplayFailure {
1870    pub reason: String,
1871    pub sequence: Option<u64>,
1872    pub expected: Option<String>,
1873    pub actual: Option<String>,
1874    pub message: String,
1875}
1876
1877impl ReplayFailure {
1878    fn new(
1879        reason: impl Into<String>,
1880        sequence: Option<u64>,
1881        expected: Option<String>,
1882        actual: Option<String>,
1883        message: impl Into<String>,
1884    ) -> Self {
1885        Self {
1886            reason: reason.into(),
1887            sequence,
1888            expected,
1889            actual,
1890            message: message.into(),
1891        }
1892    }
1893}
1894
1895/// A stable, machine-readable workflow query or query-task settlement failure.
1896#[derive(Clone, Debug, Error)]
1897#[error("query failed ({reason}, HTTP {status}): {message}")]
1898pub struct QueryFailure {
1899    pub status: u16,
1900    pub reason: String,
1901    pub message: String,
1902    pub body: Value,
1903}
1904
1905/// A stable failure returned when a server rejects an SDK protocol version.
1906#[derive(Clone, Debug, Error)]
1907#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
1908pub struct ProtocolFailure {
1909    pub status: u16,
1910    pub reason: String,
1911    pub message: String,
1912    pub supported_version: Option<String>,
1913    pub requested_version: Option<String>,
1914    pub body: Value,
1915}
1916
1917#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1918pub struct PayloadEnvelope {
1919    pub codec: String,
1920    pub blob: String,
1921}
1922
1923impl PayloadEnvelope {
1924    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
1925        encode_payload(value, DEFAULT_CODEC)
1926    }
1927
1928    /// Encode an explicit typed value, including the bytes branch that JSON
1929    /// serialization cannot represent.
1930    pub fn avro_value(value: &AvroValue) -> Result<Self> {
1931        encode_avro_value(value)
1932    }
1933}
1934
1935/// Native adapter for the fixed language-neutral Avro Value schema.
1936#[derive(Clone, Debug)]
1937pub enum AvroValue {
1938    Null,
1939    Boolean(bool),
1940    Long(i64),
1941    Double(f64),
1942    Bytes(Vec<u8>),
1943    String(String),
1944    Array(Vec<AvroValue>),
1945    Map(BTreeMap<String, AvroValue>),
1946}
1947
1948impl PartialEq for AvroValue {
1949    fn eq(&self, other: &Self) -> bool {
1950        match (self, other) {
1951            (Self::Null, Self::Null) => true,
1952            (Self::Boolean(left), Self::Boolean(right)) => left == right,
1953            (Self::Long(left), Self::Long(right)) => left == right,
1954            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
1955            (Self::Bytes(left), Self::Bytes(right)) => left == right,
1956            (Self::String(left), Self::String(right)) => left == right,
1957            (Self::Array(left), Self::Array(right)) => left == right,
1958            (Self::Map(left), Self::Map(right)) => left == right,
1959            _ => false,
1960        }
1961    }
1962}
1963
1964impl AvroValue {
1965    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
1966        Self::from_serde_value(
1967            serde_value::to_value(value).map_err(|error| {
1968                Error::Codec(format!("could not adapt value for Avro: {error}"))
1969            })?,
1970        )
1971    }
1972
1973    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
1974        use serde_value::Value as SerdeValue;
1975
1976        match value {
1977            SerdeValue::Unit => Ok(Self::Null),
1978            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
1979            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
1980            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
1981            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
1982            SerdeValue::I64(value) => Ok(Self::Long(value)),
1983            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
1984            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
1985            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
1986            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
1987                Error::Codec(
1988                    "integer_overflow: Avro Value long must be within signed 64-bit range"
1989                        .to_string(),
1990                )
1991            }),
1992            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
1993            SerdeValue::F64(value) => Self::finite_double(value),
1994            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
1995            SerdeValue::String(value) => Ok(Self::String(value)),
1996            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
1997            SerdeValue::Option(None) => Ok(Self::Null),
1998            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
1999                Self::from_serde_value(*value)
2000            }
2001            SerdeValue::Seq(values) => values
2002                .into_iter()
2003                .map(Self::from_serde_value)
2004                .collect::<Result<Vec<_>>>()
2005                .map(Self::Array),
2006            SerdeValue::Map(values) => values
2007                .into_iter()
2008                .map(|(key, value)| {
2009                    let SerdeValue::String(key) = key else {
2010                        return Err(Error::Codec(
2011                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2012                        ));
2013                    };
2014
2015                    Ok((key, Self::from_serde_value(value)?))
2016                })
2017                .collect::<Result<BTreeMap<_, _>>>()
2018                .map(Self::Map),
2019        }
2020    }
2021
2022    fn finite_double(value: f64) -> Result<Self> {
2023        if !value.is_finite() {
2024            return Err(Error::Codec(
2025                "non_finite_float: Avro Value doubles must be finite".to_string(),
2026            ));
2027        }
2028
2029        Ok(Self::Double(value))
2030    }
2031
2032    fn into_json(self) -> Result<Value> {
2033        match self {
2034            Self::Null => Ok(Value::Null),
2035            Self::Boolean(value) => Ok(Value::Bool(value)),
2036            Self::Long(value) => Ok(Value::Number(value.into())),
2037            Self::Double(value) => serde_json::Number::from_f64(value)
2038                .map(Value::Number)
2039                .ok_or_else(|| {
2040                    Error::Codec(
2041                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2042                    )
2043                }),
2044            Self::Bytes(value) => Ok(json!({
2045                "$type": "bytes",
2046                "base64": BASE64.encode(value),
2047            })),
2048            Self::String(value) => Ok(Value::String(value)),
2049            Self::Array(values) => values
2050                .into_iter()
2051                .map(Self::into_json)
2052                .collect::<Result<Vec<_>>>()
2053                .map(Value::Array),
2054            Self::Map(values) => values
2055                .into_iter()
2056                .map(|(key, value)| Ok((key, value.into_json()?)))
2057                .collect::<Result<serde_json::Map<_, _>>>()
2058                .map(Value::Object),
2059        }
2060    }
2061
2062    fn into_serde_value(self) -> serde_value::Value {
2063        use serde_value::Value as SerdeValue;
2064
2065        match self {
2066            Self::Null => SerdeValue::Unit,
2067            Self::Boolean(value) => SerdeValue::Bool(value),
2068            Self::Long(value) => SerdeValue::I64(value),
2069            Self::Double(value) => SerdeValue::F64(value),
2070            Self::Bytes(value) => SerdeValue::Bytes(value),
2071            Self::String(value) => SerdeValue::String(value),
2072            Self::Array(values) => {
2073                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2074            }
2075            Self::Map(values) => SerdeValue::Map(
2076                values
2077                    .into_iter()
2078                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2079                    .collect(),
2080            ),
2081        }
2082    }
2083
2084    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2085        self.into_serde_value().deserialize_into().map_err(|error| {
2086            Error::Codec(format!(
2087                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2088            ))
2089        })
2090    }
2091}
2092
2093impl Serialize for AvroValue {
2094    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2095    where
2096        S: Serializer,
2097    {
2098        match self {
2099            Self::Null => serializer.serialize_unit(),
2100            Self::Boolean(value) => serializer.serialize_bool(*value),
2101            Self::Long(value) => serializer.serialize_i64(*value),
2102            Self::Double(value) => serializer.serialize_f64(*value),
2103            Self::Bytes(value) => serializer.serialize_bytes(value),
2104            Self::String(value) => serializer.serialize_str(value),
2105            Self::Array(values) => {
2106                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2107                for value in values {
2108                    sequence.serialize_element(value)?;
2109                }
2110                sequence.end()
2111            }
2112            Self::Map(values) => {
2113                let mut map = serializer.serialize_map(Some(values.len()))?;
2114                for (key, value) in values {
2115                    map.serialize_entry(key, value)?;
2116                }
2117                map.end()
2118            }
2119        }
2120    }
2121}
2122
2123pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2124    let datum = avro_value_to_datum(value)?;
2125    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2126        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2127    let mut bytes = Vec::with_capacity(datum.len() + 10);
2128    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2129    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2130    bytes.extend_from_slice(&datum);
2131    Ok(PayloadEnvelope {
2132        codec: DEFAULT_CODEC.to_string(),
2133        blob: BASE64.encode(bytes),
2134    })
2135}
2136
2137pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2138    if envelope.codec != DEFAULT_CODEC {
2139        return Err(unsupported_payload_codec(&envelope.codec));
2140    }
2141    decode_avro_value_blob(&envelope.blob)
2142}
2143
2144pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2145    let blob = match codec {
2146        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2147        other => return Err(unsupported_payload_codec(other)),
2148    };
2149
2150    Ok(PayloadEnvelope {
2151        codec: codec.to_string(),
2152        blob,
2153    })
2154}
2155
2156pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2157    match envelope.codec.as_str() {
2158        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2159        other => Err(unsupported_payload_codec(other)),
2160    }
2161}
2162
2163fn handler_type_error<T>(
2164    handler_kind: HandlerKind,
2165    handler_name: &str,
2166    value_kind: HandlerValueKind,
2167    message: impl Into<String>,
2168) -> Error {
2169    Error::HandlerType {
2170        handler_kind,
2171        handler_name: handler_name.to_string(),
2172        value_kind,
2173        rust_type: type_name::<T>(),
2174        message: message.into(),
2175    }
2176}
2177
2178fn decode_handler_input<T: DeserializeOwned>(
2179    arguments: AvroValue,
2180    handler_kind: HandlerKind,
2181    handler_name: &str,
2182) -> Result<T> {
2183    let argument = match arguments {
2184        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2185            arguments.pop().expect("one typed handler argument")
2186        }
2187        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2188        AvroValue::Array(arguments) => {
2189            return Err(handler_type_error::<T>(
2190                handler_kind,
2191                handler_name,
2192                HandlerValueKind::Input,
2193                format!(
2194                    "typed handlers accept one request value, but the task carried {} arguments",
2195                    arguments.len()
2196                ),
2197            ));
2198        }
2199        argument => argument,
2200    };
2201
2202    argument.deserialize().map_err(|error| {
2203        handler_type_error::<T>(
2204            handler_kind,
2205            handler_name,
2206            HandlerValueKind::Input,
2207            error.to_string(),
2208        )
2209    })
2210}
2211
2212fn encode_handler_result<T: Serialize>(
2213    result: &T,
2214    handler_kind: HandlerKind,
2215    handler_name: &str,
2216) -> Result<AvroValue> {
2217    AvroValue::from_serialize(result).map_err(|error| {
2218        handler_type_error::<T>(
2219            handler_kind,
2220            handler_name,
2221            HandlerValueKind::Result,
2222            error.to_string(),
2223        )
2224    })
2225}
2226
2227fn decode_handler_result<T: DeserializeOwned>(
2228    result: AvroValue,
2229    handler_kind: HandlerKind,
2230    handler_name: &str,
2231) -> Result<T> {
2232    result.deserialize().map_err(|error| {
2233        handler_type_error::<T>(
2234            handler_kind,
2235            handler_name,
2236            HandlerValueKind::Result,
2237            error.to_string(),
2238        )
2239    })
2240}
2241
2242#[cfg(test)]
2243fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2244    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2245}
2246
2247fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2248    validate_payload_codec(fallback_codec)?;
2249
2250    if value.is_null() {
2251        return Ok(Value::Null);
2252    }
2253
2254    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2255        return decode_blob(blob, codec);
2256    }
2257
2258    if let Some(blob) = value.as_str() {
2259        return decode_blob(blob, fallback_codec);
2260    }
2261
2262    Err(untagged_payload_value())
2263}
2264
2265fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2266    let envelope = match codec {
2267        DEFAULT_CODEC => encode_avro_value(value)?,
2268        other => return Err(unsupported_payload_codec(other)),
2269    };
2270    Ok(serde_json::to_value(envelope)?)
2271}
2272
2273fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2274    validate_payload_codec(fallback_codec)?;
2275
2276    if value.is_null() {
2277        return Ok(AvroValue::Null);
2278    }
2279
2280    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2281        validate_payload_codec(codec)?;
2282        return decode_avro_value_blob(blob);
2283    }
2284
2285    if let Some(blob) = value.as_str() {
2286        return match fallback_codec {
2287            DEFAULT_CODEC => decode_avro_value_blob(blob),
2288            other => Err(unsupported_payload_codec(other)),
2289        };
2290    }
2291
2292    Err(untagged_payload_value())
2293}
2294
2295fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2296    match value {
2297        AvroValue::Null => AvroValue::Array(Vec::new()),
2298        AvroValue::Array(_) => value,
2299        other => AvroValue::Array(vec![other]),
2300    }
2301}
2302
2303fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2304    match codec {
2305        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2306        other => Err(unsupported_payload_codec(other)),
2307    }
2308}
2309
2310fn validate_payload_codec(codec: &str) -> Result<()> {
2311    match codec {
2312        DEFAULT_CODEC => Ok(()),
2313        MISSING_TASK_PAYLOAD_CODEC => {
2314            Err(invalid_task_payload_codec("task payload_codec is missing"))
2315        }
2316        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2317        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2318            "task payload_codec must be a string",
2319        )),
2320        other => Err(unsupported_payload_codec(other)),
2321    }
2322}
2323
2324fn invalid_task_payload_codec(reason: &str) -> Error {
2325    Error::Codec(format!(
2326        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2327    ))
2328}
2329
2330fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2331    let Some(object) = value.as_object() else {
2332        return Ok(None);
2333    };
2334    if !object.contains_key("codec") && !object.contains_key("blob") {
2335        return Ok(None);
2336    }
2337
2338    let codec = object
2339        .get("codec")
2340        .and_then(Value::as_str)
2341        .ok_or_else(invalid_payload_envelope)?;
2342    validate_payload_codec(codec)?;
2343    let blob = object
2344        .get("blob")
2345        .and_then(Value::as_str)
2346        .ok_or_else(invalid_payload_envelope)?;
2347    Ok(Some((codec, blob)))
2348}
2349
2350fn invalid_payload_envelope() -> Error {
2351    Error::Codec(
2352        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2353            .to_string(),
2354    )
2355}
2356
2357fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2358    for command in commands {
2359        let Some(command) = command.as_object() else {
2360            continue;
2361        };
2362        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2363            continue;
2364        };
2365        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2366            continue;
2367        };
2368
2369        if let Some(codec) = command.get("payload_codec") {
2370            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2371            validate_payload_codec(codec)?;
2372        }
2373
2374        let payload = command
2375            .get(payload_field)
2376            .ok_or_else(invalid_payload_envelope)?;
2377        if runtime_payloads::Reference::parse(payload)?.is_none() {
2378            validate_outbound_payload_envelope(payload)?;
2379        }
2380    }
2381    Ok(())
2382}
2383
2384fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2385    if commands.iter().any(|command| {
2386        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2387            && command
2388                .get("condition_wait_occurrence_id")
2389                .and_then(Value::as_str)
2390                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2391    }) {
2392        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2393    } else if commands.iter().any(|command| {
2394        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2395            && command.get("attribute_types").is_some()
2396    }) {
2397        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2398    } else if commands
2399        .iter()
2400        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2401    {
2402        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2403    } else if commands
2404        .iter()
2405        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2406    {
2407        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2408    } else if commands.iter().any(|command| {
2409        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2410    }) {
2411        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2412    } else {
2413        WORKER_PROTOCOL_VERSION
2414    }
2415}
2416
2417fn workflow_completion_protocol_version_with_message_streams(
2418    commands: &[Value],
2419    has_message_stream_metadata: bool,
2420) -> &'static str {
2421    let command_protocol = workflow_completion_protocol_version(commands);
2422    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2423        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2424    } else {
2425        command_protocol
2426    }
2427}
2428
2429fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2430    match command_type {
2431        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2432        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2433        "start_service_operation" => Some("request_payload"),
2434        "upsert_memo" => Some("entries"),
2435        _ => None,
2436    }
2437}
2438
2439fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2440    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2441        return Err(untagged_payload_value());
2442    };
2443    validate_payload_codec(codec)?;
2444    decode_avro_value_blob(blob)?;
2445    Ok(())
2446}
2447
2448fn unsupported_payload_codec(codec: &str) -> Error {
2449    Error::Codec(format!(
2450        "unsupported_payload_codec: workflow payload codec {codec:?} is not supported by Durable Workflow 2.0; use codec=\"avro\" with the fixed Avro Value schema and single-object framing. JSON remains the HTTP document transport, not a workflow payload codec"
2451    ))
2452}
2453
2454fn untagged_payload_value() -> Error {
2455    Error::Codec(
2456        "unsupported_payload_codec: untagged durable payload values are not supported by Durable Workflow 2.0; use codec=\"avro\" with the fixed Avro Value schema and single-object framing. JSON remains the HTTP document transport, not a workflow payload codec"
2457            .to_string(),
2458    )
2459}
2460
2461fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2462    let bytes = BASE64.decode(blob).map_err(|err| {
2463        Error::Codec(format!(
2464            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2465        ))
2466    })?;
2467
2468    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2469        return Err(unsupported_payload_codec("json"));
2470    }
2471
2472    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2473        return Err(Error::Codec(
2474            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2475        ));
2476    }
2477
2478    let fingerprint: [u8; 8] = bytes[2..10]
2479        .try_into()
2480        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2481    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2482        return Err(Error::Codec(format!(
2483            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2484            fingerprint
2485                .iter()
2486                .map(|byte| format!("{byte:02x}"))
2487                .collect::<String>()
2488        )));
2489    }
2490
2491    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2492    // The current fingerprint selects the current immutable schema, so reader
2493    // resolution would only re-walk the same recursive union. Future retained
2494    // writer fingerprints supply a distinct reader schema in this branch.
2495    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2496    if datum_reader.truncated {
2497        return Err(Error::Codec(
2498            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2499        ));
2500    }
2501    let datum = datum.map_err(|err| {
2502        Error::Codec(format!(
2503            "invalid_payload_framing: malformed Avro Value datum: {err}"
2504        ))
2505    })?;
2506    if datum_reader.remaining() != 0 {
2507        return Err(Error::Codec(format!(
2508            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2509            datum_reader.remaining()
2510        )));
2511    }
2512    avro_value_from_datum(datum)
2513}
2514
2515struct StrictAvroDatumReader<'a> {
2516    bytes: &'a [u8],
2517    offset: usize,
2518    truncated: bool,
2519}
2520
2521impl<'a> StrictAvroDatumReader<'a> {
2522    fn new(bytes: &'a [u8]) -> Self {
2523        Self {
2524            bytes,
2525            offset: 0,
2526            truncated: false,
2527        }
2528    }
2529
2530    fn remaining(&self) -> usize {
2531        self.bytes.len() - self.offset
2532    }
2533}
2534
2535impl Read for StrictAvroDatumReader<'_> {
2536    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2537        let count = buffer.len().min(self.remaining());
2538        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2539        self.offset += count;
2540        if count < buffer.len() {
2541            self.truncated = true;
2542        }
2543
2544        Ok(count)
2545    }
2546}
2547
2548fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2549    let branch = match value {
2550        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2551        AvroValue::Boolean(value) => AvroDatum::Union(
2552            1,
2553            Box::new(AvroDatum::Record(vec![(
2554                "boolean".to_string(),
2555                AvroDatum::Boolean(*value),
2556            )])),
2557        ),
2558        AvroValue::Long(value) => AvroDatum::Union(
2559            2,
2560            Box::new(AvroDatum::Record(vec![(
2561                "long".to_string(),
2562                AvroDatum::Long(*value),
2563            )])),
2564        ),
2565        AvroValue::Double(value) => {
2566            if !value.is_finite() {
2567                return Err(Error::Codec(
2568                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2569                ));
2570            }
2571            AvroDatum::Union(
2572                3,
2573                Box::new(AvroDatum::Record(vec![(
2574                    "double".to_string(),
2575                    AvroDatum::Double(*value),
2576                )])),
2577            )
2578        }
2579        AvroValue::Bytes(value) => AvroDatum::Union(
2580            4,
2581            Box::new(AvroDatum::Record(vec![(
2582                "bytes".to_string(),
2583                AvroDatum::Bytes(value.clone()),
2584            )])),
2585        ),
2586        AvroValue::String(value) => AvroDatum::Union(
2587            5,
2588            Box::new(AvroDatum::Record(vec![(
2589                "string".to_string(),
2590                AvroDatum::String(value.clone()),
2591            )])),
2592        ),
2593        AvroValue::Array(values) => AvroDatum::Union(
2594            6,
2595            Box::new(AvroDatum::Record(vec![(
2596                "items".to_string(),
2597                AvroDatum::Array(
2598                    values
2599                        .iter()
2600                        .map(avro_value_to_datum)
2601                        .collect::<Result<Vec<_>>>()?,
2602                ),
2603            )])),
2604        ),
2605        AvroValue::Map(values) => AvroDatum::Union(
2606            7,
2607            Box::new(AvroDatum::Record(vec![(
2608                "entries".to_string(),
2609                AvroDatum::Array(
2610                    values
2611                        .iter()
2612                        .map(|(key, value)| {
2613                            Ok(AvroDatum::Record(vec![
2614                                ("key".to_string(), AvroDatum::String(key.clone())),
2615                                ("value".to_string(), avro_value_to_datum(value)?),
2616                            ]))
2617                        })
2618                        .collect::<Result<Vec<_>>>()?,
2619                ),
2620            )])),
2621        ),
2622    };
2623    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2624}
2625
2626fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2627    let AvroDatum::Record(mut outer) = datum else {
2628        return Err(Error::Codec(
2629            "invalid_payload_framing: datum is not a Value record".to_string(),
2630        ));
2631    };
2632    let (_, branch) = outer
2633        .pop()
2634        .filter(|(name, _)| name == "value")
2635        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2636    let AvroDatum::Union(_, branch) = branch else {
2637        return Err(Error::Codec(
2638            "invalid_payload_framing: invalid Value union".to_string(),
2639        ));
2640    };
2641    match *branch {
2642        AvroDatum::Null => Ok(AvroValue::Null),
2643        AvroDatum::Record(mut fields) => {
2644            let (name, value) = fields.pop().ok_or_else(|| {
2645                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2646            })?;
2647            match (name.as_str(), value) {
2648                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2649                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2650                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2651                    Ok(AvroValue::Double(value))
2652                }
2653                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2654                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2655                ("items", AvroDatum::Array(values)) => values
2656                    .into_iter()
2657                    .map(avro_value_from_datum)
2658                    .collect::<Result<Vec<_>>>()
2659                    .map(AvroValue::Array),
2660                ("entries", AvroDatum::Map(values)) => values
2661                    .into_iter()
2662                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2663                    .collect::<Result<BTreeMap<_, _>>>()
2664                    .map(AvroValue::Map),
2665                _ => Err(Error::Codec(
2666                    "invalid_payload_framing: unknown Value branch".to_string(),
2667                )),
2668            }
2669        }
2670        _ => Err(Error::Codec(
2671            "invalid_payload_framing: invalid Value branch".to_string(),
2672        )),
2673    }
2674}
2675
2676fn avro_value_schema() -> Result<&'static Schema> {
2677    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2678        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2679            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2680    }) {
2681        Ok(schema) => Ok(schema),
2682        Err(message) => Err(Error::Codec(message.clone())),
2683    }
2684}
2685
2686fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2687    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2688        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2689        // have the same block representation when each ordered array record
2690        // contains the map key followed by its value, so this encoding-only
2691        // adaptation lets the official encoder retain BTreeMap wire order.
2692        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2693            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2694        let entries_schema = schema
2695            .pointer_mut("/fields/0/type/7/fields/0/type")
2696            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2697        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2698            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2699        }
2700        *entries_schema = json!({
2701            "type": "array",
2702            "items": {
2703                "type": "record",
2704                "name": "MapEntry",
2705                "fields": [
2706                    {"name": "key", "type": "string"},
2707                    {"name": "value", "type": "Value"}
2708                ]
2709            }
2710        });
2711        Schema::parse_str(&schema.to_string())
2712            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2713    }) {
2714        Ok(schema) => Ok(schema),
2715        Err(message) => Err(Error::Codec(message.clone())),
2716    }
2717}
2718
2719#[derive(Clone, Debug)]
2720pub struct Client {
2721    http: reqwest::Client,
2722    base_url: String,
2723    token: Option<String>,
2724    control_token: Option<String>,
2725    worker_token: Option<String>,
2726    namespace: String,
2727    max_external_payload_bytes: usize,
2728    worker_storage_admission: Option<WorkerStorageAdmission>,
2729    cooperative_worker_protocol: bool,
2730    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2731}
2732
2733impl Client {
2734    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2735        Self::builder(base_url).build()
2736    }
2737
2738    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2739        ClientBuilder {
2740            base_url: base_url.into(),
2741            token: None,
2742            control_token: None,
2743            worker_token: None,
2744            namespace: "default".to_string(),
2745            timeout: Duration::from_secs(60),
2746            max_external_payload_bytes: 64 * 1024 * 1024,
2747        }
2748    }
2749
2750    pub async fn health(&self) -> Result<Value> {
2751        self.request_json(
2752            reqwest::Method::GET,
2753            "/health",
2754            RequestProtocol::ControlPlane,
2755            Option::<&Value>::None,
2756        )
2757        .await
2758    }
2759
2760    pub async fn cluster_info(&self) -> Result<Value> {
2761        self.request_json(
2762            reqwest::Method::GET,
2763            "/cluster/info",
2764            RequestProtocol::ControlPlane,
2765            Option::<&Value>::None,
2766        )
2767        .await
2768    }
2769
2770    pub async fn start_workflow<T: Serialize>(
2771        &self,
2772        workflow_type: &str,
2773        task_queue: &str,
2774        workflow_id: &str,
2775        input: T,
2776    ) -> Result<WorkflowHandle> {
2777        self.start_workflow_with_options(
2778            workflow_type,
2779            task_queue,
2780            workflow_id,
2781            WorkflowStartOptions::default(),
2782            input,
2783        )
2784        .await
2785    }
2786
2787    /// Start a workflow with explicit server-enforced execution and run
2788    /// deadlines.
2789    pub async fn start_workflow_with_options<T: Serialize>(
2790        &self,
2791        workflow_type: &str,
2792        task_queue: &str,
2793        workflow_id: &str,
2794        options: WorkflowStartOptions,
2795        input: T,
2796    ) -> Result<WorkflowHandle> {
2797        options.validate()?;
2798        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2799        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2800        let body = json!({
2801            "workflow_id": workflow_id,
2802            "workflow_type": workflow_type,
2803            "task_queue": task_queue,
2804            "input": input_envelope,
2805            "execution_timeout_seconds": options.execution_timeout_seconds,
2806            "run_timeout_seconds": options.run_timeout_seconds
2807        });
2808
2809        let data: Value = self
2810            .request_json(
2811                reqwest::Method::POST,
2812                "/workflows",
2813                RequestProtocol::ControlPlane,
2814                Some(&body),
2815            )
2816            .await?;
2817
2818        Ok(WorkflowHandle {
2819            client: self.clone(),
2820            workflow_id: data
2821                .get("workflow_id")
2822                .and_then(Value::as_str)
2823                .unwrap_or(workflow_id)
2824                .to_string(),
2825            run_id: data
2826                .get("run_id")
2827                .and_then(Value::as_str)
2828                .map(str::to_string),
2829            workflow_type: data
2830                .get("workflow_type")
2831                .and_then(Value::as_str)
2832                .unwrap_or(workflow_type)
2833                .to_string(),
2834        })
2835    }
2836
2837    pub async fn signal_workflow<T: Serialize>(
2838        &self,
2839        workflow_id: &str,
2840        signal_name: &str,
2841        input: T,
2842    ) -> Result<Value> {
2843        self.signal_workflow_target(workflow_id, None, signal_name, input)
2844            .await
2845    }
2846
2847    /// Append one idempotently identified item to an instance-scoped input stream.
2848    pub async fn append_message_stream<T: Serialize>(
2849        &self,
2850        workflow_id: &str,
2851        stream_name: &str,
2852        message_id: &str,
2853        input: T,
2854    ) -> Result<Value> {
2855        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2856        let body = json!({
2857            "message_id": message_id,
2858            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2859        });
2860        self.request_json(
2861            reqwest::Method::POST,
2862            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2863            RequestProtocol::ControlPlane,
2864            Some(&body),
2865        )
2866        .await
2867    }
2868
2869    /// Signal only if `run_id` is still the current run for this instance.
2870    pub async fn signal_workflow_run<T: Serialize>(
2871        &self,
2872        workflow_id: &str,
2873        run_id: &str,
2874        signal_name: &str,
2875        input: T,
2876    ) -> Result<Value> {
2877        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2878            .await
2879    }
2880
2881    async fn signal_workflow_target<T: Serialize>(
2882        &self,
2883        workflow_id: &str,
2884        run_id: Option<&str>,
2885        signal_name: &str,
2886        input: T,
2887    ) -> Result<Value> {
2888        validate_user_signal_name(signal_name)?;
2889        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2890        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2891        let body = json!({
2892            "input": input_envelope
2893        });
2894        let path = match run_id {
2895            Some(run_id) => {
2896                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
2897            }
2898            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
2899        };
2900        self.request_json(
2901            reqwest::Method::POST,
2902            &path,
2903            RequestProtocol::ControlPlane,
2904            Some(&body),
2905        )
2906        .await
2907    }
2908
2909    /// Close the current run as cancelled immediately.
2910    ///
2911    /// Server revokes open tasks and timers without resuming workflow code for
2912    /// cleanup. Embedded Laravel's cooperative `requestCancellation()` is a
2913    /// separate capability, not yet available in service mode.
2914    pub async fn cancel_workflow(
2915        &self,
2916        workflow_id: &str,
2917        options: WorkflowCommandOptions,
2918    ) -> Result<WorkflowCommandResult> {
2919        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
2920            .await
2921    }
2922
2923    /// Close the selected run as cancelled, only if `run_id` is still current.
2924    pub async fn cancel_workflow_run(
2925        &self,
2926        workflow_id: &str,
2927        run_id: &str,
2928        options: WorkflowCommandOptions,
2929    ) -> Result<WorkflowCommandResult> {
2930        self.workflow_command(
2931            workflow_id,
2932            Some(run_id),
2933            WorkflowCommandKind::Cancel,
2934            options,
2935        )
2936        .await
2937    }
2938
2939    /// Forcefully terminate the current run for an instance.
2940    pub async fn terminate_workflow(
2941        &self,
2942        workflow_id: &str,
2943        options: WorkflowCommandOptions,
2944    ) -> Result<WorkflowCommandResult> {
2945        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
2946            .await
2947    }
2948
2949    /// Forcefully terminate only if `run_id` is still current.
2950    pub async fn terminate_workflow_run(
2951        &self,
2952        workflow_id: &str,
2953        run_id: &str,
2954        options: WorkflowCommandOptions,
2955    ) -> Result<WorkflowCommandResult> {
2956        self.workflow_command(
2957            workflow_id,
2958            Some(run_id),
2959            WorkflowCommandKind::Terminate,
2960            options,
2961        )
2962        .await
2963    }
2964
2965    /// Continue a failed run from its recorded activity failure boundary.
2966    pub async fn redrive_workflow_run(
2967        &self,
2968        workflow_id: &str,
2969        failed_run_id: &str,
2970        request_id: Option<&str>,
2971    ) -> Result<WorkflowRedriveResult> {
2972        let body = request_id
2973            .map(|id| json!({"request_id": id}))
2974            .unwrap_or_else(|| json!({}));
2975        let data: Value = self
2976            .request_json(
2977                reqwest::Method::POST,
2978                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
2979                RequestProtocol::ControlPlane,
2980                Some(&body),
2981            )
2982            .await?;
2983        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
2984            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
2985        {
2986            return Err(Error::Codec(
2987                "redrive response was not accepted".to_string(),
2988            ));
2989        }
2990        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
2991            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
2992        {
2993            return Err(Error::Codec(
2994                "redrive response does not match the requested source run".to_string(),
2995            ));
2996        }
2997        let run_id = data
2998            .get("run_id")
2999            .and_then(Value::as_str)
3000            .filter(|id| !id.is_empty() && *id != failed_run_id)
3001            .ok_or_else(|| {
3002                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3003            })?;
3004        let resume_step_sequence = data
3005            .get("resume_step_sequence")
3006            .and_then(Value::as_u64)
3007            .filter(|sequence| *sequence > 0)
3008            .ok_or_else(|| {
3009                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3010            })?;
3011        Ok(WorkflowRedriveResult {
3012            workflow_id: workflow_id.to_string(),
3013            source_run_id: failed_run_id.to_string(),
3014            run_id: run_id.to_string(),
3015            resume_step_sequence,
3016            raw: data,
3017        })
3018    }
3019
3020    async fn workflow_command(
3021        &self,
3022        workflow_id: &str,
3023        run_id: Option<&str>,
3024        command: WorkflowCommandKind,
3025        options: WorkflowCommandOptions,
3026    ) -> Result<WorkflowCommandResult> {
3027        let path = match run_id {
3028            Some(run_id) => format!(
3029                "/workflows/{workflow_id}/runs/{run_id}/{}",
3030                command.as_str()
3031            ),
3032            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3033        };
3034        let data = match self
3035            .request_json(
3036                reqwest::Method::POST,
3037                &path,
3038                RequestProtocol::ControlPlane,
3039                Some(&options),
3040            )
3041            .await
3042        {
3043            Ok(data) => data,
3044            Err(Error::Http { status, body }) => {
3045                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3046                    command,
3047                    status,
3048                    body,
3049                    workflow_id,
3050                    run_id,
3051                )));
3052            }
3053            Err(error) => return Err(error),
3054        };
3055
3056        Ok(workflow_command_result(command, data, workflow_id, run_id))
3057    }
3058
3059    /// Execute a named, read-only query against a running or completed workflow.
3060    ///
3061    /// Arguments and results use the platform payload envelope. Server and
3062    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3063    /// reason, HTTP status, and original response body.
3064    pub async fn query_workflow<T: Serialize>(
3065        &self,
3066        workflow_id: &str,
3067        query_name: &str,
3068        input: T,
3069    ) -> Result<Value> {
3070        self.query_workflow_target(workflow_id, None, query_name, input)
3071            .await
3072    }
3073
3074    /// Query only if `run_id` is still current, preventing accidental retargeting.
3075    pub async fn query_workflow_run<T: Serialize>(
3076        &self,
3077        workflow_id: &str,
3078        run_id: &str,
3079        query_name: &str,
3080        input: T,
3081    ) -> Result<Value> {
3082        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3083            .await
3084    }
3085
3086    /// Query a workflow and return the lossless fixed Avro Value result.
3087    pub async fn query_workflow_avro_value<T: Serialize>(
3088        &self,
3089        workflow_id: &str,
3090        query_name: &str,
3091        input: T,
3092    ) -> Result<AvroValue> {
3093        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3094            .await
3095    }
3096
3097    /// Query a selected run and return the lossless fixed Avro Value result.
3098    pub async fn query_workflow_run_avro_value<T: Serialize>(
3099        &self,
3100        workflow_id: &str,
3101        run_id: &str,
3102        query_name: &str,
3103        input: T,
3104    ) -> Result<AvroValue> {
3105        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3106            .await
3107    }
3108
3109    async fn query_workflow_avro_value_target<T: Serialize>(
3110        &self,
3111        workflow_id: &str,
3112        run_id: Option<&str>,
3113        query_name: &str,
3114        input: T,
3115    ) -> Result<AvroValue> {
3116        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3117        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3118        let path = match run_id {
3119            Some(run_id) => {
3120                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3121            }
3122            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3123        };
3124        let response: Value = match self
3125            .request_json(
3126                reqwest::Method::POST,
3127                &path,
3128                RequestProtocol::ControlPlane,
3129                Some(&body),
3130            )
3131            .await
3132        {
3133            Ok(response) => response,
3134            Err(Error::Http { status, body }) => {
3135                return Err(Error::QueryFailed(query_failure(status, body)));
3136            }
3137            Err(error) => return Err(error),
3138        };
3139
3140        let envelope = response
3141            .get("result_envelope")
3142            .filter(|envelope| !envelope.is_null())
3143            .ok_or_else(|| {
3144                Error::Codec(
3145                    "missing_payload_envelope: typed query result requires result_envelope"
3146                        .to_string(),
3147                )
3148            })?;
3149        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3150    }
3151
3152    async fn query_workflow_target<T: Serialize>(
3153        &self,
3154        workflow_id: &str,
3155        run_id: Option<&str>,
3156        query_name: &str,
3157        input: T,
3158    ) -> Result<Value> {
3159        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3160        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3161        let body = json!({
3162            "input": input_envelope
3163        });
3164        let path = match run_id {
3165            Some(run_id) => {
3166                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3167            }
3168            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3169        };
3170        let response: Value = match self
3171            .request_json(
3172                reqwest::Method::POST,
3173                &path,
3174                RequestProtocol::ControlPlane,
3175                Some(&body),
3176            )
3177            .await
3178        {
3179            Ok(response) => response,
3180            Err(Error::Http { status, body }) => {
3181                return Err(Error::QueryFailed(query_failure(status, body)));
3182            }
3183            Err(error) => return Err(error),
3184        };
3185
3186        if let Some(envelope) = response
3187            .get("result_envelope")
3188            .filter(|envelope| !envelope.is_null())
3189        {
3190            return decode_wire_value(envelope, DEFAULT_CODEC);
3191        }
3192
3193        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3194    }
3195
3196    /// Send a synchronous update using fixed Avro Value arguments.
3197    pub async fn update_workflow<T: Serialize>(
3198        &self,
3199        workflow_id: &str,
3200        update_name: &str,
3201        input: T,
3202        request_id: Option<&str>,
3203    ) -> Result<Value> {
3204        let response = self
3205            .update_workflow_response(workflow_id, update_name, input, request_id)
3206            .await?;
3207        if let Some(envelope) = response
3208            .get("result_envelope")
3209            .filter(|envelope| !envelope.is_null())
3210        {
3211            return decode_wire_value(envelope, DEFAULT_CODEC);
3212        }
3213        Ok(response.get("result").cloned().unwrap_or(response))
3214    }
3215
3216    /// Send a synchronous update and retain a bytes-capable Avro result.
3217    pub async fn update_workflow_avro_value<T: Serialize>(
3218        &self,
3219        workflow_id: &str,
3220        update_name: &str,
3221        input: T,
3222        request_id: Option<&str>,
3223    ) -> Result<AvroValue> {
3224        let response = self
3225            .update_workflow_response(workflow_id, update_name, input, request_id)
3226            .await?;
3227        let envelope = response
3228            .get("result_envelope")
3229            .filter(|envelope| !envelope.is_null())
3230            .ok_or_else(|| {
3231                Error::Codec(
3232                    "missing_payload_envelope: typed update result requires result_envelope"
3233                        .to_string(),
3234                )
3235            })?;
3236        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3237    }
3238
3239    async fn update_workflow_response<T: Serialize>(
3240        &self,
3241        workflow_id: &str,
3242        update_name: &str,
3243        input: T,
3244        request_id: Option<&str>,
3245    ) -> Result<Value> {
3246        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3247        let mut body = json!({
3248            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3249            "wait_for": "completed",
3250        });
3251        if let Some(request_id) = request_id {
3252            body["request_id"] = json!(request_id);
3253        }
3254        self.request_json(
3255            reqwest::Method::POST,
3256            &format!("/workflows/{workflow_id}/update/{update_name}"),
3257            RequestProtocol::ControlPlane,
3258            Some(&body),
3259        )
3260        .await
3261    }
3262
3263    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3264        let path = format!("/workflows/{workflow_id}");
3265        let mut data: WorkflowDescription = self
3266            .request_json(
3267                reqwest::Method::GET,
3268                &path,
3269                RequestProtocol::ControlPlane,
3270                Option::<&Value>::None,
3271            )
3272            .await?;
3273        data.decode_payloads()?;
3274        Ok(data)
3275    }
3276
3277    /// Describe one selected run, including historical terminal runs.
3278    pub async fn describe_workflow_run(
3279        &self,
3280        workflow_id: &str,
3281        run_id: &str,
3282    ) -> Result<WorkflowDescription> {
3283        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3284        let mut data: WorkflowDescription = self
3285            .request_json(
3286                reqwest::Method::GET,
3287                &path,
3288                RequestProtocol::ControlPlane,
3289                Option::<&Value>::None,
3290            )
3291            .await?;
3292        data.decode_payloads()?;
3293        Ok(data)
3294    }
3295
3296    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3297        let mut path = format!(
3298            "/workflows/{}/runs/{}/streams",
3299            percent_encode_path_segment(workflow_id),
3300            percent_encode_path_segment(run_id),
3301        );
3302        if let Some(stream_name) = stream_name {
3303            path.push('/');
3304            path.push_str(&percent_encode_path_segment(stream_name));
3305        }
3306        path
3307    }
3308
3309    /// List the run-scoped output streams already opened by a workflow.
3310    pub async fn list_workflow_streams(
3311        &self,
3312        workflow_id: &str,
3313        run_id: &str,
3314    ) -> Result<Vec<WorkflowStreamDescription>> {
3315        let response: WorkflowStreamListResponse = self
3316            .request_json(
3317                reqwest::Method::GET,
3318                &Self::workflow_stream_path(workflow_id, run_id, None),
3319                RequestProtocol::ControlPlane,
3320                Option::<&Value>::None,
3321            )
3322            .await?;
3323        Ok(response.streams)
3324    }
3325
3326    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3327    pub async fn describe_workflow_stream(
3328        &self,
3329        workflow_id: &str,
3330        run_id: &str,
3331        stream_name: &str,
3332    ) -> Result<WorkflowStreamDescription> {
3333        let response: WorkflowStreamDescriptionResponse = self
3334            .request_json(
3335                reqwest::Method::GET,
3336                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3337                RequestProtocol::ControlPlane,
3338                Option::<&Value>::None,
3339            )
3340            .await?;
3341        Ok(response.stream)
3342    }
3343
3344    /// Read one bounded page beginning at a zero-based offset.
3345    ///
3346    /// Delivery is at least once: persist `next_offset` only after processing
3347    /// the page. The future is cancellation-safe; dropping it cancels the
3348    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3349    /// service contract.
3350    pub async fn subscribe_workflow_stream(
3351        &self,
3352        workflow_id: &str,
3353        run_id: &str,
3354        stream_name: &str,
3355        from_offset: u64,
3356        max_items: usize,
3357        wait: Duration,
3358    ) -> Result<WorkflowStreamPage> {
3359        let max_items = max_items.clamp(1, 500);
3360        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3361        let path = format!(
3362            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3363            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3364        );
3365        let response: WorkflowStreamPageResponse = self
3366            .request_json_with_timeout(
3367                reqwest::Method::GET,
3368                &path,
3369                RequestProtocol::ControlPlane,
3370                Option::<&Value>::None,
3371                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3372            )
3373            .await?;
3374
3375        let items = response
3376            .items
3377            .into_iter()
3378            .map(|raw| {
3379                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3380                let envelope = raw.get("payload").cloned();
3381                let payload = envelope
3382                    .as_ref()
3383                    .filter(|value| value.get("blob").is_some())
3384                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3385                    .transpose()?
3386                    .map(AvroValue::into_json)
3387                    .transpose()?;
3388                Ok(WorkflowStreamItem {
3389                    offset,
3390                    payload,
3391                    payload_envelope: envelope,
3392                    payload_reference: raw
3393                        .get("payload_reference")
3394                        .and_then(Value::as_str)
3395                        .map(str::to_string),
3396                    payload_codec: raw
3397                        .get("payload_codec")
3398                        .and_then(Value::as_str)
3399                        .map(str::to_string),
3400                    idempotency_key: raw
3401                        .get("idempotency_key")
3402                        .and_then(Value::as_str)
3403                        .map(str::to_string),
3404                    item_type: raw
3405                        .get("item_type")
3406                        .and_then(Value::as_str)
3407                        .map(str::to_string),
3408                    content_type: raw
3409                        .get("content_type")
3410                        .and_then(Value::as_str)
3411                        .map(str::to_string),
3412                    origin: raw
3413                        .get("origin")
3414                        .and_then(Value::as_str)
3415                        .map(str::to_string),
3416                    origin_reference: raw
3417                        .get("origin_reference")
3418                        .and_then(Value::as_str)
3419                        .map(str::to_string),
3420                    emitted_at: raw
3421                        .get("emitted_at")
3422                        .and_then(Value::as_str)
3423                        .map(str::to_string),
3424                    raw,
3425                })
3426            })
3427            .collect::<Result<Vec<_>>>()?;
3428        Ok(WorkflowStreamPage {
3429            stream: response.stream,
3430            items,
3431            next_offset: response.next_offset,
3432            terminal: response.terminal,
3433        })
3434    }
3435
3436    /// Append inline Avro envelopes or opaque external payload references.
3437    pub async fn append_workflow_stream(
3438        &self,
3439        workflow_id: &str,
3440        run_id: &str,
3441        stream_name: &str,
3442        items: &[WorkflowStreamAppendItem],
3443        max_pending_items: Option<u64>,
3444    ) -> Result<WorkflowStreamAppendResult> {
3445        if items.is_empty() {
3446            return Err(Error::Codec(
3447                "workflow_stream_items_empty: append requires at least one item".to_string(),
3448            ));
3449        }
3450        let mut body = json!({
3451            "items": items
3452                .iter()
3453                .map(|item| item.wire_value(None))
3454                .collect::<Vec<_>>(),
3455        });
3456        if let Some(max_pending_items) = max_pending_items {
3457            if max_pending_items == 0 {
3458                return Err(Error::Codec(
3459                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3460                        .to_string(),
3461                ));
3462            }
3463            body["max_pending_items"] = json!(max_pending_items);
3464        }
3465        let response: WorkflowStreamAppendResponse = self
3466            .request_json(
3467                reqwest::Method::POST,
3468                &format!(
3469                    "{}/items",
3470                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3471                ),
3472                RequestProtocol::ControlPlane,
3473                Some(&body),
3474            )
3475            .await?;
3476        Ok(WorkflowStreamAppendResult {
3477            stream: response.stream,
3478            accepted_offsets: response.accepted_offsets,
3479            accepted: response.accepted,
3480            deduped: response.deduped,
3481        })
3482    }
3483
3484    /// Close a stream, or mark it errored when `error_reason` is supplied.
3485    pub async fn close_workflow_stream(
3486        &self,
3487        workflow_id: &str,
3488        run_id: &str,
3489        stream_name: &str,
3490        error_reason: Option<&str>,
3491        retention_seconds: Option<u64>,
3492    ) -> Result<WorkflowStreamDescription> {
3493        let mut body = json!({});
3494        if let Some(error_reason) = error_reason {
3495            body["error_reason"] = json!(error_reason);
3496        }
3497        if let Some(retention_seconds) = retention_seconds {
3498            if retention_seconds == 0 {
3499                return Err(Error::Codec(
3500                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3501                        .to_string(),
3502                ));
3503            }
3504            body["retention_seconds"] = json!(retention_seconds);
3505        }
3506        let response: WorkflowStreamDescriptionResponse = self
3507            .request_json(
3508                reqwest::Method::POST,
3509                &format!(
3510                    "{}/close",
3511                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3512                ),
3513                RequestProtocol::ControlPlane,
3514                Some(&body),
3515            )
3516            .await?;
3517        Ok(response.stream)
3518    }
3519
3520    pub async fn register_worker(
3521        &self,
3522        worker_id: &str,
3523        task_queue: &str,
3524        supported_workflow_types: Vec<String>,
3525        supported_activity_types: Vec<String>,
3526        max_concurrent_workflow_tasks: usize,
3527        max_concurrent_activity_tasks: usize,
3528    ) -> Result<RegisterWorkerResponse> {
3529        self.register_worker_with_capabilities(
3530            worker_id,
3531            task_queue,
3532            supported_workflow_types,
3533            supported_activity_types,
3534            max_concurrent_workflow_tasks,
3535            max_concurrent_activity_tasks,
3536            Vec::new(),
3537        )
3538        .await
3539    }
3540
3541    /// Register a worker and explicitly advertise additive worker capabilities.
3542    pub async fn register_worker_with_capabilities(
3543        &self,
3544        worker_id: &str,
3545        task_queue: &str,
3546        supported_workflow_types: Vec<String>,
3547        supported_activity_types: Vec<String>,
3548        max_concurrent_workflow_tasks: usize,
3549        max_concurrent_activity_tasks: usize,
3550        capabilities: Vec<String>,
3551    ) -> Result<RegisterWorkerResponse> {
3552        self.register_worker_with_command_contracts(
3553            worker_id,
3554            task_queue,
3555            supported_workflow_types,
3556            supported_activity_types,
3557            max_concurrent_workflow_tasks,
3558            max_concurrent_activity_tasks,
3559            capabilities,
3560            Value::Object(serde_json::Map::new()),
3561        )
3562        .await
3563    }
3564
3565    /// Register a worker and advertise its named query and update handlers.
3566    ///
3567    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3568    /// so a workflow contract with a non-empty or malformed
3569    /// `update_validators` declaration returns
3570    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3571    #[allow(clippy::too_many_arguments)]
3572    pub async fn register_worker_with_command_contracts(
3573        &self,
3574        worker_id: &str,
3575        task_queue: &str,
3576        supported_workflow_types: Vec<String>,
3577        supported_activity_types: Vec<String>,
3578        max_concurrent_workflow_tasks: usize,
3579        max_concurrent_activity_tasks: usize,
3580        capabilities: Vec<String>,
3581        workflow_command_contracts: Value,
3582    ) -> Result<RegisterWorkerResponse> {
3583        self.register_worker_with_definition_fingerprints(
3584            worker_id,
3585            task_queue,
3586            supported_workflow_types,
3587            supported_activity_types,
3588            max_concurrent_workflow_tasks,
3589            max_concurrent_activity_tasks,
3590            capabilities,
3591            workflow_command_contracts,
3592            None,
3593        )
3594        .await
3595    }
3596
3597    #[allow(clippy::too_many_arguments)]
3598    async fn register_worker_with_definition_fingerprints(
3599        &self,
3600        worker_id: &str,
3601        task_queue: &str,
3602        supported_workflow_types: Vec<String>,
3603        supported_activity_types: Vec<String>,
3604        max_concurrent_workflow_tasks: usize,
3605        max_concurrent_activity_tasks: usize,
3606        capabilities: Vec<String>,
3607        workflow_command_contracts: Value,
3608        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3609    ) -> Result<RegisterWorkerResponse> {
3610        if let Some(contracts) = workflow_command_contracts.as_object() {
3611            for (workflow_type, contract) in contracts {
3612                let Some(update_validators) = contract.get("update_validators") else {
3613                    continue;
3614                };
3615                if !update_validators
3616                    .as_array()
3617                    .is_some_and(|validators| validators.is_empty())
3618                {
3619                    return Err(Error::UnsupportedUpdateValidators {
3620                        workflow_type: workflow_type.clone(),
3621                    });
3622                }
3623            }
3624        }
3625
3626        let mut body = json!({
3627            "worker_id": worker_id,
3628            "task_queue": task_queue,
3629            "runtime": "rust",
3630            "sdk_version": SDK_VERSION,
3631            "supported_workflow_types": supported_workflow_types,
3632            "supported_activity_types": supported_activity_types,
3633            "capabilities": capabilities,
3634            "capability_manifest": portable_worker_affinity_capability_manifest(),
3635            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3636            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3637        });
3638        if workflow_command_contracts
3639            .as_object()
3640            .is_some_and(|contracts| !contracts.is_empty())
3641        {
3642            body["workflow_command_contracts"] = workflow_command_contracts;
3643        }
3644        if let Some(fingerprints) = workflow_definition_fingerprints {
3645            body["workflow_definition_fingerprints"] = json!(fingerprints);
3646        }
3647
3648        let response: Value = self
3649            .request_json(
3650                reqwest::Method::POST,
3651                "/worker/register",
3652                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3653                Some(&body),
3654            )
3655            .await?;
3656        if self.cooperative_worker_protocol {
3657            let compatible = response["registered"].as_bool() == Some(true)
3658                && response["worker_id"].as_str() == Some(worker_id)
3659                && response["namespace"].as_str() == Some(self.namespace.as_str())
3660                && response["task_queue"].as_str() == Some(task_queue)
3661                && response["protocol_version"]
3662                    .as_str()
3663                    .is_some_and(cooperative_cancellation::supports_protocol)
3664                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3665                    == Some(true)
3666                && response["capabilities"].as_array().is_some_and(|accepted| {
3667                    capabilities.iter().all(|capability| {
3668                        accepted
3669                            .iter()
3670                            .any(|value| value.as_str() == Some(capability.as_str()))
3671                    })
3672                });
3673            if !compatible {
3674                let error = Error::CooperativeCancellationUnavailable(
3675                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3676                );
3677                if response["registered"].as_bool() == Some(true)
3678                    && response["worker_id"].as_str() == Some(worker_id)
3679                {
3680                    if let Err(deregistration) =
3681                        self.deregister_worker_registration(worker_id).await
3682                    {
3683                        return Err(Error::WorkerShutdown {
3684                            primary: Box::new(error),
3685                            deregistration: Box::new(deregistration),
3686                        });
3687                    }
3688                }
3689                return Err(error);
3690            }
3691        }
3692        Ok(serde_json::from_value(response)?)
3693    }
3694
3695    /// Gracefully remove one worker's registration through the worker plane.
3696    ///
3697    /// This operation is separate from operator-facing worker management. It
3698    /// uses worker-protocol authentication and returns the server's lease
3699    /// recovery result.
3700    pub async fn deregister_worker_registration(
3701        &self,
3702        worker_id: &str,
3703    ) -> Result<WorkerDeregistrationEnvelope> {
3704        let path = format!(
3705            "/worker/registrations/{}",
3706            percent_encode_path_segment(worker_id)
3707        );
3708        self.request_json(
3709            reqwest::Method::DELETE,
3710            &path,
3711            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3712            Option::<&Value>::None,
3713        )
3714        .await
3715    }
3716
3717    /// Long-poll for an ephemeral, read-only workflow query task.
3718    pub async fn poll_query_task(
3719        &self,
3720        worker_id: &str,
3721        task_queue: &str,
3722        timeout: Duration,
3723    ) -> Result<Option<QueryTask>> {
3724        Ok(self
3725            .poll_query_task_response(worker_id, task_queue, timeout)
3726            .await?
3727            .task)
3728    }
3729
3730    /// Poll a query task while preserving server stop and drain metadata.
3731    pub async fn poll_query_task_response(
3732        &self,
3733        worker_id: &str,
3734        task_queue: &str,
3735        timeout: Duration,
3736    ) -> Result<PollQueryTaskResponse> {
3737        let poll_request_id = unique_request_id("rust-query-poll");
3738        self.poll_query_task_response_with_request_id(
3739            worker_id,
3740            task_queue,
3741            timeout,
3742            &poll_request_id,
3743            1,
3744        )
3745        .await
3746    }
3747
3748    async fn poll_query_task_response_with_request_id(
3749        &self,
3750        worker_id: &str,
3751        task_queue: &str,
3752        timeout: Duration,
3753        poll_request_id: &str,
3754        transport_retries: usize,
3755    ) -> Result<PollQueryTaskResponse> {
3756        let timeout_seconds = long_poll_timeout_seconds(timeout);
3757        let body = json!({
3758            "worker_id": worker_id,
3759            "task_queue": task_queue,
3760            "poll_request_id": poll_request_id,
3761            "timeout_seconds": timeout_seconds,
3762        });
3763        self.poll_request_json(
3764            "/worker/query-tasks/poll",
3765            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3766            &body,
3767            timeout + Duration::from_secs(5),
3768            transport_retries,
3769        )
3770        .await
3771    }
3772
3773    /// Complete a query task without appending workflow history.
3774    pub async fn complete_query_task<T: Serialize>(
3775        &self,
3776        query_task_id: &str,
3777        lease_owner: &str,
3778        query_task_attempt: u64,
3779        result: T,
3780        codec: &str,
3781    ) -> Result<Value> {
3782        let typed_result = AvroValue::from_serialize(&result)?;
3783        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3784        self.complete_query_task_with_envelope(
3785            query_task_id,
3786            lease_owner,
3787            query_task_attempt,
3788            typed_result.into_json()?,
3789            result_envelope,
3790        )
3791        .await
3792    }
3793
3794    async fn complete_query_task_with_envelope(
3795        &self,
3796        query_task_id: &str,
3797        lease_owner: &str,
3798        query_task_attempt: u64,
3799        result: Value,
3800        result_envelope: Value,
3801    ) -> Result<Value> {
3802        let body = json!({
3803            "lease_owner": lease_owner,
3804            "query_task_attempt": query_task_attempt,
3805            "result": result,
3806            "result_envelope": result_envelope,
3807        });
3808        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3809        let response = self
3810            .request_json(
3811                reqwest::Method::POST,
3812                &path,
3813                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3814                Some(&body),
3815            )
3816            .await;
3817        query_task_response(response)
3818    }
3819
3820    /// Report a stable machine-readable query-task failure.
3821    pub async fn fail_query_task(
3822        &self,
3823        query_task_id: &str,
3824        lease_owner: &str,
3825        query_task_attempt: u64,
3826        message: impl Into<String>,
3827        reason: impl Into<String>,
3828        failure_type: impl Into<String>,
3829    ) -> Result<Value> {
3830        let body = json!({
3831            "lease_owner": lease_owner,
3832            "query_task_attempt": query_task_attempt,
3833            "failure": {
3834                "message": message.into(),
3835                "reason": reason.into(),
3836                "type": failure_type.into(),
3837            }
3838        });
3839        let path = format!("/worker/query-tasks/{query_task_id}/fail");
3840        let response = self
3841            .request_json(
3842                reqwest::Method::POST,
3843                &path,
3844                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3845                Some(&body),
3846            )
3847            .await;
3848        query_task_response(response)
3849    }
3850
3851    pub async fn heartbeat_worker(
3852        &self,
3853        worker_id: &str,
3854        workflow_available: usize,
3855        activity_available: usize,
3856    ) -> Result<Value> {
3857        let body = json!({
3858            "worker_id": worker_id,
3859            "task_slots": {
3860                "workflow_available": workflow_available,
3861                "activity_available": activity_available
3862            },
3863            "process_metrics": {
3864                "process_id": std::process::id(),
3865                "process_uptime_seconds": 0
3866            }
3867        });
3868
3869        self.request_json(
3870            reqwest::Method::POST,
3871            "/worker/heartbeat",
3872            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3873            Some(&body),
3874        )
3875        .await
3876    }
3877
3878    pub async fn poll_workflow_task(
3879        &self,
3880        worker_id: &str,
3881        task_queue: &str,
3882        timeout: Duration,
3883    ) -> Result<Option<WorkflowTask>> {
3884        Ok(self
3885            .poll_workflow_task_response(worker_id, task_queue, timeout)
3886            .await?
3887            .task)
3888    }
3889
3890    pub async fn poll_workflow_task_response(
3891        &self,
3892        worker_id: &str,
3893        task_queue: &str,
3894        timeout: Duration,
3895    ) -> Result<PollWorkflowTaskResponse> {
3896        let poll_request_id = unique_request_id("rust-workflow-poll");
3897        self.poll_workflow_task_response_with_request_id(
3898            worker_id,
3899            task_queue,
3900            timeout,
3901            &poll_request_id,
3902            1,
3903        )
3904        .await
3905    }
3906
3907    async fn poll_workflow_task_response_with_request_id(
3908        &self,
3909        worker_id: &str,
3910        task_queue: &str,
3911        timeout: Duration,
3912        poll_request_id: &str,
3913        transport_retries: usize,
3914    ) -> Result<PollWorkflowTaskResponse> {
3915        let body = json!({
3916            "worker_id": worker_id,
3917            "task_queue": task_queue,
3918            "poll_request_id": poll_request_id,
3919            "timeout_seconds": long_poll_timeout_seconds(timeout),
3920            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
3921        });
3922        let mut data: PollWorkflowTaskResponse = self
3923            .poll_request_json(
3924                "/worker/workflow-tasks/poll",
3925                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3926                &body,
3927                timeout + Duration::from_secs(5),
3928                transport_retries,
3929            )
3930            .await?;
3931
3932        if let Some(task) = data.task.as_mut() {
3933            self.fetch_remaining_workflow_history(worker_id, task)
3934                .await?;
3935        }
3936
3937        Ok(data)
3938    }
3939
3940    async fn fetch_remaining_workflow_history(
3941        &self,
3942        worker_id: &str,
3943        task: &mut WorkflowTask,
3944    ) -> Result<()> {
3945        let mut next_token = task.next_history_page_token.clone();
3946
3947        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
3948            let lease_owner = task
3949                .lease_owner
3950                .clone()
3951                .unwrap_or_else(|| worker_id.to_string());
3952            let page = self
3953                .workflow_task_history_page(
3954                    &task.task_id,
3955                    &lease_owner,
3956                    task.workflow_task_attempt,
3957                    &token,
3958                )
3959                .await?;
3960
3961            task.append_history_page(page);
3962
3963            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
3964                return Err(Error::Codec(
3965                    "workflow history pagination returned the same page token".to_string(),
3966                ));
3967            }
3968
3969            next_token = task.next_history_page_token.clone();
3970        }
3971
3972        Ok(())
3973    }
3974
3975    async fn workflow_task_history_page(
3976        &self,
3977        task_id: &str,
3978        lease_owner: &str,
3979        workflow_task_attempt: u64,
3980        next_history_page_token: &str,
3981    ) -> Result<WorkflowTaskHistoryPage> {
3982        let body = json!({
3983            "lease_owner": lease_owner,
3984            "workflow_task_attempt": workflow_task_attempt,
3985            "next_history_page_token": next_history_page_token
3986        });
3987        let path = format!("/worker/workflow-tasks/{task_id}/history");
3988
3989        self.request_json(
3990            reqwest::Method::POST,
3991            &path,
3992            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3993            Some(&body),
3994        )
3995        .await
3996    }
3997
3998    pub async fn complete_workflow_task(
3999        &self,
4000        task_id: &str,
4001        lease_owner: &str,
4002        workflow_task_attempt: u64,
4003        commands: Vec<Value>,
4004    ) -> Result<Value> {
4005        self.complete_workflow_task_with_message_streams(
4006            task_id,
4007            lease_owner,
4008            workflow_task_attempt,
4009            commands,
4010            Vec::new(),
4011            Vec::new(),
4012        )
4013        .await
4014    }
4015
4016    async fn complete_workflow_task_with_message_streams(
4017        &self,
4018        task_id: &str,
4019        lease_owner: &str,
4020        workflow_task_attempt: u64,
4021        commands: Vec<Value>,
4022        message_stream_cursors: Vec<Value>,
4023        message_stream_waits: Vec<Value>,
4024    ) -> Result<Value> {
4025        validate_workflow_task_commands(&commands)?;
4026        let has_message_stream_metadata =
4027            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4028        if has_message_stream_metadata
4029            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4030        {
4031            return Err(Error::Codec(
4032                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4033                    .to_string(),
4034            ));
4035        }
4036        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4037            &commands,
4038            has_message_stream_metadata,
4039        );
4040        let mut body = json!({
4041            "lease_owner": lease_owner,
4042            "workflow_task_attempt": workflow_task_attempt,
4043            "commands": commands
4044        });
4045        if !message_stream_cursors.is_empty() {
4046            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4047        }
4048        if !message_stream_waits.is_empty() {
4049            body["message_stream_waits"] = Value::Array(message_stream_waits);
4050        }
4051        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4052        self.request_json(
4053            reqwest::Method::POST,
4054            &path,
4055            RequestProtocol::Worker(protocol_version),
4056            Some(&body),
4057        )
4058        .await
4059    }
4060
4061    pub async fn fail_workflow_task(
4062        &self,
4063        task_id: &str,
4064        lease_owner: &str,
4065        workflow_task_attempt: u64,
4066        message: impl Into<String>,
4067    ) -> Result<Value> {
4068        self.fail_workflow_task_with_type(
4069            task_id,
4070            lease_owner,
4071            workflow_task_attempt,
4072            message,
4073            "RustWorkflowTaskFailure",
4074        )
4075        .await
4076    }
4077
4078    async fn fail_workflow_task_with_type(
4079        &self,
4080        task_id: &str,
4081        lease_owner: &str,
4082        workflow_task_attempt: u64,
4083        message: impl Into<String>,
4084        failure_type: &str,
4085    ) -> Result<Value> {
4086        let body = json!({
4087            "lease_owner": lease_owner,
4088            "workflow_task_attempt": workflow_task_attempt,
4089            "failure": {
4090                "message": message.into(),
4091                "type": failure_type
4092            }
4093        });
4094        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4095        self.request_json(
4096            reqwest::Method::POST,
4097            &path,
4098            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4099            Some(&body),
4100        )
4101        .await
4102    }
4103
4104    pub async fn poll_activity_task(
4105        &self,
4106        worker_id: &str,
4107        task_queue: &str,
4108        timeout: Duration,
4109    ) -> Result<Option<ActivityTask>> {
4110        Ok(self
4111            .poll_activity_task_response(worker_id, task_queue, timeout)
4112            .await?
4113            .task)
4114    }
4115
4116    /// Poll an activity task while preserving server stop and drain metadata.
4117    pub async fn poll_activity_task_response(
4118        &self,
4119        worker_id: &str,
4120        task_queue: &str,
4121        timeout: Duration,
4122    ) -> Result<PollActivityTaskResponse> {
4123        let poll_request_id = unique_request_id("rust-activity-poll");
4124        self.poll_activity_task_response_with_request_id(
4125            worker_id,
4126            task_queue,
4127            timeout,
4128            &poll_request_id,
4129            1,
4130        )
4131        .await
4132    }
4133
4134    async fn poll_activity_task_response_with_request_id(
4135        &self,
4136        worker_id: &str,
4137        task_queue: &str,
4138        timeout: Duration,
4139        poll_request_id: &str,
4140        transport_retries: usize,
4141    ) -> Result<PollActivityTaskResponse> {
4142        let body = json!({
4143            "worker_id": worker_id,
4144            "task_queue": task_queue,
4145            "poll_request_id": poll_request_id,
4146            "timeout_seconds": long_poll_timeout_seconds(timeout),
4147        });
4148        let data: PollActivityTaskResponse = self
4149            .poll_request_json(
4150                "/worker/activity-tasks/poll",
4151                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4152                &body,
4153                timeout + Duration::from_secs(5),
4154                transport_retries,
4155            )
4156            .await?;
4157        Ok(data)
4158    }
4159
4160    pub async fn complete_activity_task<T: Serialize>(
4161        &self,
4162        task_id: &str,
4163        activity_attempt_id: &str,
4164        lease_owner: &str,
4165        result: T,
4166        codec: &str,
4167    ) -> Result<Value> {
4168        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4169        let body = json!({
4170            "activity_attempt_id": activity_attempt_id,
4171            "lease_owner": lease_owner,
4172            "result": result
4173        });
4174        let path = format!("/worker/activity-tasks/{task_id}/complete");
4175        activity_task_response(
4176            self.request_json(
4177                reqwest::Method::POST,
4178                &path,
4179                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4180                Some(&body),
4181            )
4182            .await,
4183            "complete",
4184            task_id,
4185            activity_attempt_id,
4186        )
4187    }
4188
4189    pub async fn fail_activity_task(
4190        &self,
4191        task_id: &str,
4192        activity_attempt_id: &str,
4193        lease_owner: &str,
4194        message: impl Into<String>,
4195        non_retryable: bool,
4196    ) -> Result<Value> {
4197        let body = json!({
4198            "activity_attempt_id": activity_attempt_id,
4199            "lease_owner": lease_owner,
4200            "failure": {
4201                "message": message.into(),
4202                "type": "RustActivityFailure",
4203                "non_retryable": non_retryable
4204            }
4205        });
4206        let path = format!("/worker/activity-tasks/{task_id}/fail");
4207        activity_task_response(
4208            self.request_json(
4209                reqwest::Method::POST,
4210                &path,
4211                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4212                Some(&body),
4213            )
4214            .await,
4215            "fail",
4216            task_id,
4217            activity_attempt_id,
4218        )
4219    }
4220
4221    pub async fn heartbeat_activity_task<T: Serialize>(
4222        &self,
4223        task_id: &str,
4224        activity_attempt_id: &str,
4225        lease_owner: &str,
4226        details: T,
4227    ) -> Result<ActivityHeartbeatResponse> {
4228        let details = encode_typed_envelope(&AvroValue::from_serialize(&details)?, DEFAULT_CODEC)?;
4229        let body = json!({
4230            "activity_attempt_id": activity_attempt_id,
4231            "lease_owner": lease_owner,
4232            "details": details
4233        });
4234        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4235        activity_task_response(
4236            self.request_json(
4237                reqwest::Method::POST,
4238                &path,
4239                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4240                Some(&body),
4241            )
4242            .await,
4243            "heartbeat",
4244            task_id,
4245            activity_attempt_id,
4246        )
4247    }
4248
4249    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4250        &self,
4251        method: reqwest::Method,
4252        path: &str,
4253        protocol: RequestProtocol,
4254        body: Option<&B>,
4255    ) -> Result<T> {
4256        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4257            .await
4258    }
4259
4260    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4261        &self,
4262        method: reqwest::Method,
4263        path: &str,
4264        protocol: RequestProtocol,
4265        body: Option<&B>,
4266        timeout: Duration,
4267    ) -> Result<T> {
4268        let protocol = match protocol {
4269            RequestProtocol::Worker(version)
4270                if self.cooperative_worker_protocol
4271                    && version
4272                        .strip_prefix("1.")
4273                        .and_then(|minor| minor.parse::<u64>().ok())
4274                        .is_some_and(|minor| minor < 20) =>
4275            {
4276                RequestProtocol::Worker("1.20")
4277            }
4278            protocol => protocol,
4279        };
4280        let auth_token = self.auth_token(protocol)?;
4281        let mut request = self
4282            .http
4283            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4284            .timeout(timeout)
4285            .header(reqwest::header::ACCEPT, "application/json")
4286            .header(reqwest::header::CONTENT_TYPE, "application/json")
4287            .header("X-Namespace", &self.namespace);
4288
4289        match protocol {
4290            RequestProtocol::Worker(version) => {
4291                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4292            }
4293            RequestProtocol::ControlPlane => {
4294                request = request.header(
4295                    "X-Durable-Workflow-Control-Plane-Version",
4296                    CONTROL_PLANE_VERSION,
4297                );
4298            }
4299        }
4300
4301        if let Some(token) = auth_token {
4302            request = request.bearer_auth(token);
4303        }
4304
4305        if let Some(body) = body {
4306            let mut body = serde_json::to_value(body)?;
4307            if matches!(
4308                method,
4309                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4310            ) {
4311                self.externalize_runtime_payloads(&mut body, path, protocol)
4312                    .await?;
4313            }
4314            request = request.json(&body);
4315        }
4316
4317        let request = request.build()?;
4318        let request_body = request
4319            .body()
4320            .and_then(reqwest::Body::as_bytes)
4321            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4322        let poll_request_id = path.ends_with("/poll").then(|| {
4323            request_body
4324                .as_ref()
4325                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4326                .unwrap_or_default()
4327        });
4328        let mut storage_retries = 0_usize;
4329
4330        loop {
4331            // Keep the serialized body and lease/poll identity across admission pauses.
4332            let response = self
4333                .http
4334                .execute(request.try_clone().ok_or_else(|| {
4335                    Error::WorkerLoop("worker request body cannot be retried".to_string())
4336                })?)
4337                .await?;
4338            let status = response.status();
4339            let bytes = response.bytes().await?;
4340
4341            if !status.is_success() {
4342                let body = String::from_utf8_lossy(&bytes).to_string();
4343                if let Some(protocol) = protocol_failure(status, &body) {
4344                    return Err(Error::Protocol(protocol));
4345                }
4346                let error = Error::Http { status, body };
4347                if self
4348                    .wait_for_storage_admission(
4349                        &error,
4350                        protocol,
4351                        Some(path),
4352                        poll_request_id.as_deref(),
4353                        request_body.as_ref(),
4354                        &mut storage_retries,
4355                    )
4356                    .await
4357                {
4358                    continue;
4359                }
4360                return Err(error);
4361            }
4362
4363            if bytes.is_empty() {
4364                return Ok(serde_json::from_value(Value::Null)?);
4365            }
4366
4367            let mut value: Value = serde_json::from_slice(&bytes)?;
4368            self.resolve_runtime_payloads(&mut value, path, protocol)
4369                .await?;
4370            return Ok(serde_json::from_value(value)?);
4371        }
4372    }
4373
4374    async fn wait_for_storage_admission(
4375        &self,
4376        error: &Error,
4377        protocol: RequestProtocol,
4378        path: Option<&str>,
4379        poll_request_id: Option<&str>,
4380        request_body: Option<&Value>,
4381        retries: &mut usize,
4382    ) -> bool {
4383        let Some(admission) = self
4384            .worker_storage_admission
4385            .as_ref()
4386            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4387        else {
4388            return false;
4389        };
4390        let Some(advertised_delay) = worker_storage_admission_retry_after(error, poll_request_id)
4391            .or_else(|| {
4392                path.and_then(|path| {
4393                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4394                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4395                })
4396            })
4397        else {
4398            return false;
4399        };
4400        *retries = retries.saturating_add(1);
4401        let delay = worker_retry_delay(admission.policy, *retries)
4402            .max(advertised_delay)
4403            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4404        let deadline = tokio::time::Instant::now() + delay;
4405        loop {
4406            if admission.stop.load(Ordering::SeqCst) {
4407                return false;
4408            }
4409            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
4410            if remaining.is_zero() {
4411                return true;
4412            }
4413            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4414        }
4415    }
4416
4417    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4418        &self,
4419        path: &str,
4420        protocol: RequestProtocol,
4421        body: &B,
4422        timeout: Duration,
4423        max_retries: usize,
4424    ) -> Result<T> {
4425        let mut retries = 0;
4426
4427        loop {
4428            let response = self
4429                .request_json_with_timeout(
4430                    reqwest::Method::POST,
4431                    path,
4432                    protocol,
4433                    Some(body),
4434                    timeout,
4435                )
4436                .await;
4437
4438            match response {
4439                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4440                response => return worker_poll_response(response),
4441            }
4442        }
4443    }
4444
4445    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4446        match protocol {
4447            RequestProtocol::Worker(_) => {
4448                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4449                    return Ok(Some(token));
4450                }
4451                if self.control_token.is_some() {
4452                    return Err(Error::MissingRoleCredentials {
4453                        role: "worker",
4454                        opposite_role: "control",
4455                    });
4456                }
4457                Ok(None)
4458            }
4459            RequestProtocol::ControlPlane => {
4460                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4461                    return Ok(Some(token));
4462                }
4463                if self.worker_token.is_some() {
4464                    return Err(Error::MissingRoleCredentials {
4465                        role: "control",
4466                        opposite_role: "worker",
4467                    });
4468                }
4469                Ok(None)
4470            }
4471        }
4472    }
4473}
4474
4475fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4476    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4477    let reason = body
4478        .get("reason")
4479        .and_then(Value::as_str)
4480        .unwrap_or("query_rejected")
4481        .to_string();
4482    let message = body
4483        .get("message")
4484        .or_else(|| body.get("error"))
4485        .and_then(Value::as_str)
4486        .unwrap_or("workflow query was rejected")
4487        .to_string();
4488
4489    QueryFailure {
4490        status: status.as_u16(),
4491        reason,
4492        message,
4493        body,
4494    }
4495}
4496
4497fn workflow_command_result(
4498    command: WorkflowCommandKind,
4499    data: Value,
4500    workflow_id: &str,
4501    run_id: Option<&str>,
4502) -> WorkflowCommandResult {
4503    WorkflowCommandResult {
4504        command,
4505        workflow_id: data
4506            .get("workflow_id")
4507            .and_then(Value::as_str)
4508            .unwrap_or(workflow_id)
4509            .to_string(),
4510        run_id: data
4511            .get("run_id")
4512            .and_then(Value::as_str)
4513            .or(run_id)
4514            .map(str::to_string),
4515        outcome: data
4516            .get("outcome")
4517            .and_then(Value::as_str)
4518            .map(str::to_string),
4519        reason: data
4520            .get("reason")
4521            .and_then(Value::as_str)
4522            .map(str::to_string),
4523        command_status: data
4524            .get("command_status")
4525            .and_then(Value::as_str)
4526            .map(str::to_string),
4527        raw: data,
4528    }
4529}
4530
4531fn workflow_command_rejection(
4532    command: WorkflowCommandKind,
4533    status: reqwest::StatusCode,
4534    raw_body: String,
4535    workflow_id: &str,
4536    run_id: Option<&str>,
4537) -> WorkflowCommandRejection {
4538    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4539    WorkflowCommandRejection {
4540        command,
4541        status: status.as_u16(),
4542        reason: body
4543            .get("reason")
4544            .and_then(Value::as_str)
4545            .unwrap_or("workflow_command_rejected")
4546            .to_string(),
4547        message: body
4548            .get("message")
4549            .or_else(|| body.get("error"))
4550            .and_then(Value::as_str)
4551            .unwrap_or("workflow lifecycle command was rejected")
4552            .to_string(),
4553        workflow_id: body
4554            .get("workflow_id")
4555            .and_then(Value::as_str)
4556            .unwrap_or(workflow_id)
4557            .to_string(),
4558        run_id: body
4559            .get("run_id")
4560            .and_then(Value::as_str)
4561            .or(run_id)
4562            .map(str::to_string),
4563        target_scope: body
4564            .get("target_scope")
4565            .and_then(Value::as_str)
4566            .map(str::to_string),
4567        body,
4568    }
4569}
4570
4571fn query_task_response(response: Result<Value>) -> Result<Value> {
4572    match response {
4573        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4574        response => response,
4575    }
4576}
4577
4578fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4579    match response {
4580        Err(Error::Http { status, body })
4581            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4582        {
4583            Ok(serde_json::from_str(&body)?)
4584        }
4585        response => response,
4586    }
4587}
4588
4589fn worker_poll_body_is_stop(body: &str) -> bool {
4590    serde_json::from_str::<Value>(body)
4591        .ok()
4592        .is_some_and(|body| {
4593            worker_poll_is_stop(
4594                body.get("poll_status").and_then(Value::as_str),
4595                body.get("reason").and_then(Value::as_str),
4596            )
4597        })
4598}
4599
4600fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4601    matches!(poll_status, Some("draining" | "stopped"))
4602        || matches!(reason, Some("worker_draining" | "worker_stopped"))
4603}
4604
4605fn query_task_rejection_is_final(error: &Error) -> bool {
4606    matches!(
4607        error,
4608        Error::QueryFailed(failure)
4609            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
4610    )
4611}
4612
4613fn activity_task_response<T>(
4614    response: Result<T>,
4615    operation: &str,
4616    task_id: &str,
4617    activity_attempt_id: &str,
4618) -> Result<T> {
4619    match response {
4620        Err(Error::Http { status, body }) => {
4621            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
4622            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
4623                operation: operation.to_string(),
4624                status: status.as_u16(),
4625                reason: body
4626                    .get("reason")
4627                    .and_then(Value::as_str)
4628                    .unwrap_or("activity_task_rejected")
4629                    .to_string(),
4630                task_id: body
4631                    .get("task_id")
4632                    .and_then(Value::as_str)
4633                    .unwrap_or(task_id)
4634                    .to_string(),
4635                activity_attempt_id: body
4636                    .get("activity_attempt_id")
4637                    .and_then(Value::as_str)
4638                    .unwrap_or(activity_attempt_id)
4639                    .to_string(),
4640                cancel_requested: body
4641                    .get("cancel_requested")
4642                    .and_then(Value::as_bool)
4643                    .unwrap_or(false),
4644                can_continue: body.get("can_continue").and_then(Value::as_bool),
4645                run_closed_reason: body
4646                    .get("run_closed_reason")
4647                    .and_then(Value::as_str)
4648                    .map(str::to_string),
4649                body,
4650            }))
4651        }
4652        response => response,
4653    }
4654}
4655
4656fn activity_task_rejection_is_final(error: &Error) -> bool {
4657    matches!(
4658        error,
4659        Error::ActivityTaskRejected(rejection)
4660            if matches!(
4661                rejection.reason.as_str(),
4662                "run_cancelled"
4663                    | "run_terminated"
4664                    | "attempt_closed"
4665                    | "stale_attempt"
4666                    | "activity_cancelled"
4667                    | "task_cancelled"
4668                    | "run_closed"
4669                    | "activity_not_running"
4670                    | "attempt_not_found"
4671            )
4672    )
4673}
4674
4675fn workflow_task_completion_is_terminal_timeout(
4676    error: &Error,
4677    task_id: &str,
4678    workflow_task_attempt: u64,
4679    run_id: Option<&str>,
4680) -> bool {
4681    let Error::Http { status, body } = error else {
4682        return false;
4683    };
4684    if *status != reqwest::StatusCode::CONFLICT {
4685        return false;
4686    }
4687
4688    let Some(run_id) = run_id else {
4689        return false;
4690    };
4691    let Ok(body) = serde_json::from_str::<Value>(body) else {
4692        return false;
4693    };
4694
4695    body.get("recorded").and_then(Value::as_bool) == Some(false)
4696        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
4697        && body.get("run_status").and_then(Value::as_str) == Some("failed")
4698        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
4699        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
4700        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
4701}
4702
4703fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
4704    let body: Value = serde_json::from_str(raw_body).ok()?;
4705    let reason = body.get("reason")?.as_str()?;
4706    if !matches!(
4707        reason,
4708        "missing_protocol_version"
4709            | "unsupported_protocol_version"
4710            | "missing_control_plane_version"
4711            | "unsupported_control_plane_version"
4712    ) {
4713        return None;
4714    }
4715
4716    Some(ProtocolFailure {
4717        status: status.as_u16(),
4718        reason: reason.to_string(),
4719        message: body
4720            .get("message")
4721            .or_else(|| body.get("error"))
4722            .and_then(Value::as_str)
4723            .unwrap_or("protocol version rejected")
4724            .to_string(),
4725        supported_version: body
4726            .get("supported_version")
4727            .and_then(Value::as_str)
4728            .map(str::to_string),
4729        requested_version: body
4730            .get("requested_version")
4731            .and_then(Value::as_str)
4732            .map(str::to_string),
4733        body,
4734    })
4735}
4736
4737fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
4738    timeout
4739        .as_secs()
4740        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
4741        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
4742}
4743
4744fn worker_operation_is_retryable(error: &Error) -> bool {
4745    if worker_poll_capacity_retry_after(error).is_some()
4746        || worker_storage_admission_body(error).is_some()
4747        || worker_backend_unavailable_body(error).is_some()
4748        || worker_operation_is_explicitly_non_retryable(error)
4749    {
4750        return false;
4751    }
4752
4753    match error {
4754        Error::Transport(error) => {
4755            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
4756        }
4757        Error::Http { status, .. } => {
4758            matches!(
4759                *status,
4760                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
4761            ) || status.is_server_error()
4762        }
4763        _ => false,
4764    }
4765}
4766
4767fn worker_storage_admission_body(error: &Error) -> Option<Value> {
4768    let body: Value = match error {
4769        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
4770        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
4771        _ => return None,
4772    };
4773    matches!(
4774        body.get("reason").and_then(Value::as_str),
4775        Some("storage_pressure" | "storage_admission_unavailable")
4776    )
4777    .then_some(body)
4778}
4779
4780fn worker_storage_admission_retry_after(
4781    error: &Error,
4782    poll_request_id: Option<&str>,
4783) -> Option<Duration> {
4784    let Error::Http { status, .. } = error else {
4785        return None;
4786    };
4787    let body = worker_storage_admission_body(error)?;
4788    let delay = body.get("retry_after_seconds")?.as_u64()?;
4789    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
4790        || delay == 0
4791        || body.get("retryable") != Some(&Value::Bool(true))
4792        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
4793        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
4794        || body
4795            .get("request_admitted")
4796            .is_some_and(|admitted| admitted != &Value::Bool(false))
4797    {
4798        return None;
4799    }
4800    match poll_request_id {
4801        Some(id) => {
4802            if id.is_empty()
4803                || body.get("task") != Some(&Value::Null)
4804                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
4805                || body.get("poll_status") != body.get("reason")
4806                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
4807                || body.get("claim_admitted") != Some(&Value::Bool(false))
4808            {
4809                return None;
4810            }
4811        }
4812        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
4813        None => {}
4814    }
4815    Some(Duration::from_secs(delay))
4816}
4817
4818fn worker_backend_unavailable_retry_after(
4819    error: &Error,
4820    path: &str,
4821    poll_request_id: Option<&str>,
4822) -> Option<Duration> {
4823    let operation = match path {
4824        "/worker/register" => "register_worker",
4825        "/worker/heartbeat" => "heartbeat_worker",
4826        "/worker/workflow-tasks/poll" => "poll_workflow_task",
4827        "/worker/activity-tasks/poll" => "poll_activity_task",
4828        "/worker/query-tasks/poll" => "poll_query_task",
4829        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
4830        _ => return None,
4831    };
4832    let body = worker_backend_unavailable_body(error)?;
4833    let delay = body.get("retry_after_seconds")?.as_u64()?;
4834    if delay == 0
4835        || body.get("operation")?.as_str()? != operation
4836        || body.get("outcome")?.as_str()? != "unknown"
4837        || body.get("retryable") != Some(&Value::Bool(true))
4838        || body.get("worker_id")?.as_str()?.is_empty()
4839    {
4840        return None;
4841    }
4842    if let Some(id) = poll_request_id {
4843        if id.is_empty()
4844            || body.get("task") != Some(&Value::Null)
4845            || body.get("poll_status")?.as_str()? != "backend_unavailable"
4846            || body.get("poll_request_id")?.as_str()? != id
4847            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
4848        {
4849            return None;
4850        }
4851    } else if path.ends_with("/poll") {
4852        return None;
4853    }
4854    Some(Duration::from_secs(delay))
4855}
4856
4857fn worker_fenced_completion_retry_after(
4858    error: &Error,
4859    path: &str,
4860    request_body: Option<&Value>,
4861) -> Option<Duration> {
4862    let (operation, task_id, attempt_field) = if let Some(task_id) = path
4863        .strip_prefix("/worker/workflow-tasks/")
4864        .and_then(|tail| tail.strip_suffix("/complete"))
4865    {
4866        ("complete_workflow_task", task_id, "workflow_task_attempt")
4867    } else if let Some(task_id) = path
4868        .strip_prefix("/worker/activity-tasks/")
4869        .and_then(|tail| tail.strip_suffix("/complete"))
4870    {
4871        ("complete_activity_task", task_id, "activity_attempt_id")
4872    } else {
4873        return None;
4874    };
4875    if task_id.is_empty() || task_id.contains('/') {
4876        return None;
4877    }
4878
4879    let request = request_body?.as_object()?;
4880    let lease_owner = request.get("lease_owner")?.as_str()?;
4881    if lease_owner.is_empty() {
4882        return None;
4883    }
4884    let attempt = request.get(attempt_field)?;
4885    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
4886        || (attempt_field == "activity_attempt_id"
4887            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
4888    {
4889        return None;
4890    }
4891
4892    let body = worker_backend_unavailable_body(error)?;
4893    let delay = body.get("retry_after_seconds")?.as_u64()?;
4894    if delay == 0
4895        || body.get("operation")?.as_str()? != operation
4896        || body.get("outcome")?.as_str()? != "unknown"
4897        || body.get("retryable") != Some(&Value::Bool(true))
4898        || body.get("worker_id")?.as_str()? != lease_owner
4899        || body.get("task_queue") != Some(&Value::Null)
4900        || body.get("task_id")?.as_str()? != task_id
4901        || body.get("lease_owner")?.as_str()? != lease_owner
4902        || body.get(attempt_field) != Some(attempt)
4903    {
4904        return None;
4905    }
4906
4907    Some(Duration::from_secs(delay))
4908}
4909
4910fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
4911    let Error::Http { status, body } = error else {
4912        return None;
4913    };
4914    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
4915        return None;
4916    }
4917    let body: Value = serde_json::from_str(body).ok()?;
4918    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
4919}
4920
4921fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
4922    let Error::Http { body, .. } = error else {
4923        return false;
4924    };
4925
4926    serde_json::from_str::<Value>(body)
4927        .ok()
4928        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
4929        == Some(false)
4930}
4931
4932fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
4933    let Error::Http { status, body } = error else {
4934        return None;
4935    };
4936    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
4937        return None;
4938    }
4939
4940    let body = serde_json::from_str::<Value>(body).ok()?;
4941    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
4942        == Some("long_poll_capacity_exhausted")
4943        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
4944    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
4945        return None;
4946    }
4947
4948    Some(Duration::from_secs(
4949        body.get("retry_after_seconds")
4950            .and_then(Value::as_u64)
4951            .unwrap_or_default(),
4952    ))
4953}
4954
4955fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
4956    let exponent = retry.saturating_sub(1).min(31) as u32;
4957    policy
4958        .initial_backoff
4959        .saturating_mul(1_u32 << exponent)
4960        .min(policy.max_backoff)
4961}
4962
4963#[derive(Debug)]
4964pub struct ClientBuilder {
4965    base_url: String,
4966    token: Option<String>,
4967    control_token: Option<String>,
4968    worker_token: Option<String>,
4969    namespace: String,
4970    timeout: Duration,
4971    max_external_payload_bytes: usize,
4972}
4973
4974impl ClientBuilder {
4975    pub fn token(mut self, token: Option<String>) -> Self {
4976        self.token = token;
4977        self
4978    }
4979
4980    pub fn control_token(mut self, token: Option<String>) -> Self {
4981        self.control_token = token;
4982        self
4983    }
4984
4985    pub fn worker_token(mut self, token: Option<String>) -> Self {
4986        self.worker_token = token;
4987        self
4988    }
4989
4990    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
4991        self.namespace = namespace.into();
4992        self
4993    }
4994
4995    pub fn timeout(mut self, timeout: Duration) -> Self {
4996        self.timeout = timeout;
4997        self
4998    }
4999
5000    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5001    /// References are fetched only from this client's authenticated runtime.
5002    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5003        self.max_external_payload_bytes = bytes;
5004        self
5005    }
5006
5007    pub fn build(self) -> Result<Client> {
5008        let base_url = self.base_url.trim_end_matches('/').to_string();
5009        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5010            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5011            .unwrap_or_else(|_| base_url.ends_with("/api"));
5012
5013        if has_sdk_api_suffix {
5014            return Err(Error::InvalidBaseUrl);
5015        }
5016
5017        Ok(Client {
5018            http: reqwest::Client::builder()
5019                .timeout(self.timeout)
5020                .redirect(reqwest::redirect::Policy::none())
5021                .build()?,
5022            base_url,
5023            token: self.token,
5024            control_token: self.control_token,
5025            worker_token: self.worker_token,
5026            namespace: self.namespace,
5027            max_external_payload_bytes: self.max_external_payload_bytes,
5028            worker_storage_admission: None,
5029            cooperative_worker_protocol: false,
5030            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5031        })
5032    }
5033}
5034
5035#[derive(Clone, Debug)]
5036pub struct WorkflowHandle {
5037    client: Client,
5038    pub workflow_id: String,
5039    pub run_id: Option<String>,
5040    pub workflow_type: String,
5041}
5042
5043impl WorkflowHandle {
5044    /// Describe whichever run is current for this stable workflow instance.
5045    pub async fn describe(&self) -> Result<WorkflowDescription> {
5046        self.client.describe_workflow(&self.workflow_id).await
5047    }
5048
5049    /// Describe the run identity originally selected by this handle.
5050    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5051        let run_id = self.run_id.as_deref().ok_or_else(|| {
5052            Error::Codec("run_id is required for selected-run description".to_string())
5053        })?;
5054        self.client
5055            .describe_workflow_run(&self.workflow_id, run_id)
5056            .await
5057    }
5058
5059    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5060        self.client
5061            .signal_workflow(&self.workflow_id, signal_name, input)
5062            .await
5063    }
5064
5065    pub async fn append_message<T: Serialize>(
5066        &self,
5067        stream_name: &str,
5068        message_id: &str,
5069        input: T,
5070    ) -> Result<Value> {
5071        self.client
5072            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5073            .await
5074    }
5075
5076    /// Signal only if this handle's selected run is still current.
5077    pub async fn signal_selected_run<T: Serialize>(
5078        &self,
5079        signal_name: &str,
5080        input: T,
5081    ) -> Result<Value> {
5082        let run_id = self.run_id.as_deref().ok_or_else(|| {
5083            Error::Codec("run_id is required for selected-run signaling".to_string())
5084        })?;
5085        self.client
5086            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5087            .await
5088    }
5089
5090    /// Close whichever run is current as cancelled, without workflow cleanup.
5091    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5092        self.client
5093            .cancel_workflow(&self.workflow_id, options)
5094            .await
5095    }
5096
5097    /// Request cancellation only if this handle's selected run is still current.
5098    pub async fn cancel_selected_run(
5099        &self,
5100        options: WorkflowCommandOptions,
5101    ) -> Result<WorkflowCommandResult> {
5102        let run_id = self.run_id.as_deref().ok_or_else(|| {
5103            Error::Codec("run_id is required for selected-run cancellation".to_string())
5104        })?;
5105        self.client
5106            .cancel_workflow_run(&self.workflow_id, run_id, options)
5107            .await
5108    }
5109
5110    /// Forcefully terminate whichever run is current.
5111    pub async fn terminate(
5112        &self,
5113        options: WorkflowCommandOptions,
5114    ) -> Result<WorkflowCommandResult> {
5115        self.client
5116            .terminate_workflow(&self.workflow_id, options)
5117            .await
5118    }
5119
5120    /// Terminate only if this handle's selected run is still current.
5121    pub async fn terminate_selected_run(
5122        &self,
5123        options: WorkflowCommandOptions,
5124    ) -> Result<WorkflowCommandResult> {
5125        let run_id = self.run_id.as_deref().ok_or_else(|| {
5126            Error::Codec("run_id is required for selected-run termination".to_string())
5127        })?;
5128        self.client
5129            .terminate_workflow_run(&self.workflow_id, run_id, options)
5130            .await
5131    }
5132
5133    /// Continue this handle's failed run without repeating completed activities.
5134    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5135        let run_id = self
5136            .run_id
5137            .as_deref()
5138            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5139        self.client
5140            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5141            .await
5142    }
5143
5144    /// Execute a named, read-only query against this workflow.
5145    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5146        self.client
5147            .query_workflow(&self.workflow_id, query_name, input)
5148            .await
5149    }
5150
5151    pub async fn query_avro_value<T: Serialize>(
5152        &self,
5153        query_name: &str,
5154        input: T,
5155    ) -> Result<AvroValue> {
5156        self.client
5157            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5158            .await
5159    }
5160
5161    pub async fn update<T: Serialize>(
5162        &self,
5163        update_name: &str,
5164        input: T,
5165        request_id: Option<&str>,
5166    ) -> Result<Value> {
5167        self.client
5168            .update_workflow(&self.workflow_id, update_name, input, request_id)
5169            .await
5170    }
5171
5172    pub async fn update_avro_value<T: Serialize>(
5173        &self,
5174        update_name: &str,
5175        input: T,
5176        request_id: Option<&str>,
5177    ) -> Result<AvroValue> {
5178        self.client
5179            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5180            .await
5181    }
5182
5183    /// Query only if this handle's selected run is still current.
5184    pub async fn query_selected_run<T: Serialize>(
5185        &self,
5186        query_name: &str,
5187        input: T,
5188    ) -> Result<Value> {
5189        let run_id = self
5190            .run_id
5191            .as_deref()
5192            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5193        self.client
5194            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5195            .await
5196    }
5197
5198    /// Await the final terminal outcome of the current continue-as-new chain.
5199    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5200        self.result_target(options, None).await
5201    }
5202
5203    /// Await the final result without projecting Avro bytes through JSON.
5204    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5205        self.result_avro_value_target(options, None).await
5206    }
5207
5208    /// Await the final result and decode it into a Serde application type.
5209    pub async fn result_typed<T: DeserializeOwned>(
5210        &self,
5211        options: WorkflowResultOptions,
5212    ) -> Result<T> {
5213        let result = self.result_avro_value(options).await?;
5214        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5215    }
5216
5217    /// Await only the run identity originally selected by this handle.
5218    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5219        let run_id = self.run_id.as_deref().ok_or_else(|| {
5220            Error::Codec("run_id is required for selected-run result".to_string())
5221        })?;
5222        self.result_target(options, Some(run_id)).await
5223    }
5224
5225    /// Await the selected run's result on the lossless Avro Value surface.
5226    pub async fn result_selected_run_avro_value(
5227        &self,
5228        options: WorkflowResultOptions,
5229    ) -> Result<AvroValue> {
5230        let run_id = self.run_id.as_deref().ok_or_else(|| {
5231            Error::Codec("run_id is required for selected-run result".to_string())
5232        })?;
5233        self.result_avro_value_target(options, Some(run_id)).await
5234    }
5235
5236    /// Await the selected run and decode its result into a Serde type.
5237    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5238        &self,
5239        options: WorkflowResultOptions,
5240    ) -> Result<T> {
5241        let result = self.result_selected_run_avro_value(options).await?;
5242        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5243    }
5244
5245    async fn result_avro_value_target(
5246        &self,
5247        options: WorkflowResultOptions,
5248        selected_run_id: Option<&str>,
5249    ) -> Result<AvroValue> {
5250        let started = Instant::now();
5251
5252        loop {
5253            let description = match selected_run_id {
5254                Some(run_id) => {
5255                    self.client
5256                        .describe_workflow_run(&self.workflow_id, run_id)
5257                        .await?
5258                }
5259                None => self.describe().await?,
5260            };
5261            if description.is_completed() {
5262                return description.output_avro_value.ok_or_else(|| {
5263                    Error::Codec(
5264                        "missing_payload_envelope: typed workflow result requires output_envelope"
5265                            .to_string(),
5266                    )
5267                });
5268            }
5269            if description.is_terminal() {
5270                let outcome =
5271                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5272                return Err(match outcome.kind {
5273                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5274                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5275                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5276                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5277                });
5278            }
5279            if started.elapsed() >= options.timeout {
5280                return Err(Error::Timeout);
5281            }
5282            tokio::time::sleep(options.poll_interval).await;
5283        }
5284    }
5285
5286    async fn result_target(
5287        &self,
5288        options: WorkflowResultOptions,
5289        selected_run_id: Option<&str>,
5290    ) -> Result<Value> {
5291        let started = Instant::now();
5292
5293        loop {
5294            let description = match selected_run_id {
5295                Some(run_id) => {
5296                    self.client
5297                        .describe_workflow_run(&self.workflow_id, run_id)
5298                        .await?
5299                }
5300                None => self.describe().await?,
5301            };
5302            if description.is_completed() {
5303                return Ok(description.output.unwrap_or(Value::Null));
5304            }
5305
5306            if description.is_terminal() {
5307                let outcome =
5308                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5309                return Err(match outcome.kind {
5310                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5311                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5312                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5313                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5314                });
5315            }
5316
5317            if started.elapsed() >= options.timeout {
5318                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5319                    kind: WorkflowTerminalKind::TimedOut,
5320                    workflow_id: description
5321                        .workflow_id
5322                        .clone()
5323                        .unwrap_or_else(|| self.workflow_id.clone()),
5324                    run_id: description
5325                        .run_id
5326                        .clone()
5327                        .or_else(|| selected_run_id.map(str::to_string)),
5328                    reason: "result_wait_timeout".to_string(),
5329                    failure_category: Some("client_timeout".to_string()),
5330                    failure_id: None,
5331                    exception_type: None,
5332                    exception_class: None,
5333                    non_retryable: None,
5334                    message: Some(format!(
5335                        "workflow result was not terminal within {:?}",
5336                        options.timeout
5337                    )),
5338                    exception: None,
5339                    raw: description.raw_value(),
5340                }));
5341            }
5342
5343            tokio::time::sleep(options.poll_interval).await;
5344        }
5345    }
5346}
5347
5348#[derive(Clone, Copy, Debug)]
5349pub struct WorkflowResultOptions {
5350    pub poll_interval: Duration,
5351    pub timeout: Duration,
5352}
5353
5354impl Default for WorkflowResultOptions {
5355    fn default() -> Self {
5356        Self {
5357            poll_interval: Duration::from_millis(500),
5358            timeout: Duration::from_secs(30),
5359        }
5360    }
5361}
5362
5363#[derive(Clone, Debug, Deserialize)]
5364pub struct WorkflowDescription {
5365    pub workflow_id: Option<String>,
5366    pub run_id: Option<String>,
5367    pub workflow_type: Option<String>,
5368    pub status: Option<String>,
5369    #[serde(default)]
5370    pub closed_reason: Option<String>,
5371    #[serde(default)]
5372    pub error: Option<String>,
5373    #[serde(default)]
5374    pub failure: Option<Value>,
5375    #[serde(default)]
5376    pub exception: Option<Value>,
5377    #[serde(default)]
5378    pub failures: Vec<Value>,
5379    #[serde(default)]
5380    pub output: Option<Value>,
5381    #[serde(default)]
5382    pub output_envelope: Option<Value>,
5383    #[serde(skip)]
5384    pub output_avro_value: Option<AvroValue>,
5385    #[serde(flatten)]
5386    pub raw: HashMap<String, Value>,
5387}
5388
5389/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5390#[derive(Clone, Debug, Deserialize)]
5391pub struct WorkflowStreamDescription {
5392    pub stream_name: String,
5393    pub status: String,
5394    pub last_offset: i64,
5395    pub total_items: u64,
5396    pub pending_items: u64,
5397    #[serde(default)]
5398    pub opened_at: Option<String>,
5399    #[serde(default)]
5400    pub last_appended_at: Option<String>,
5401    #[serde(default)]
5402    pub closed_at: Option<String>,
5403    #[serde(default)]
5404    pub error_reason: Option<String>,
5405    #[serde(default)]
5406    pub retention_seconds: Option<u64>,
5407    #[serde(flatten)]
5408    pub raw: HashMap<String, Value>,
5409}
5410
5411impl WorkflowStreamDescription {
5412    pub fn is_terminal(&self) -> bool {
5413        matches!(self.status.as_str(), "closed" | "errored")
5414    }
5415}
5416
5417/// One item for direct or replay-safe append.
5418#[derive(Clone, Debug, Default)]
5419pub struct WorkflowStreamAppendItem {
5420    pub payload_envelope: Option<Value>,
5421    pub payload_reference: Option<String>,
5422    pub item_type: Option<String>,
5423    pub content_type: Option<String>,
5424    pub idempotency_key: Option<String>,
5425}
5426
5427impl WorkflowStreamAppendItem {
5428    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5429    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5430        let value = AvroValue::from_serialize(&payload)?;
5431        Ok(Self {
5432            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5433            ..Self::default()
5434        })
5435    }
5436
5437    /// Preserve an external payload URI as an opaque service-contract reference.
5438    pub fn from_reference(reference: impl Into<String>) -> Self {
5439        Self {
5440            payload_reference: Some(reference.into()),
5441            ..Self::default()
5442        }
5443    }
5444
5445    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5446        self.item_type = Some(item_type.into());
5447        self
5448    }
5449
5450    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5451        self.content_type = Some(content_type.into());
5452        self
5453    }
5454
5455    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5456        self.idempotency_key = Some(idempotency_key.into());
5457        self
5458    }
5459
5460    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5461        let mut item = serde_json::Map::new();
5462        if let Some(payload) = &self.payload_envelope {
5463            item.insert("payload".to_string(), payload.clone());
5464            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5465        }
5466        if let Some(reference) = &self.payload_reference {
5467            item.insert("payload_reference".to_string(), json!(reference));
5468        }
5469        if let Some(item_type) = &self.item_type {
5470            item.insert("item_type".to_string(), json!(item_type));
5471        }
5472        if let Some(content_type) = &self.content_type {
5473            item.insert("content_type".to_string(), json!(content_type));
5474        }
5475        if let Some(key) = derived_idempotency_key
5476            .as_ref()
5477            .or(self.idempotency_key.as_ref())
5478        {
5479            item.insert("idempotency_key".to_string(), json!(key));
5480        }
5481        Value::Object(item)
5482    }
5483}
5484
5485/// One durable item at its stable zero-based offset.
5486#[derive(Clone, Debug)]
5487pub struct WorkflowStreamItem {
5488    pub offset: u64,
5489    pub payload: Option<Value>,
5490    pub payload_envelope: Option<Value>,
5491    pub payload_reference: Option<String>,
5492    pub payload_codec: Option<String>,
5493    pub idempotency_key: Option<String>,
5494    pub item_type: Option<String>,
5495    pub content_type: Option<String>,
5496    pub origin: Option<String>,
5497    pub origin_reference: Option<String>,
5498    pub emitted_at: Option<String>,
5499    pub raw: Value,
5500}
5501
5502/// One bounded at-least-once subscription page.
5503#[derive(Clone, Debug)]
5504pub struct WorkflowStreamPage {
5505    pub stream: WorkflowStreamDescription,
5506    pub items: Vec<WorkflowStreamItem>,
5507    pub next_offset: u64,
5508    pub terminal: bool,
5509}
5510
5511/// Durable acceptance and deduplication outcome for an append request.
5512#[derive(Clone, Debug)]
5513pub struct WorkflowStreamAppendResult {
5514    pub stream: WorkflowStreamDescription,
5515    pub accepted_offsets: Vec<u64>,
5516    pub accepted: u64,
5517    pub deduped: u64,
5518}
5519
5520#[derive(Deserialize)]
5521struct WorkflowStreamListResponse {
5522    #[serde(default)]
5523    streams: Vec<WorkflowStreamDescription>,
5524}
5525
5526#[derive(Deserialize)]
5527struct WorkflowStreamDescriptionResponse {
5528    stream: WorkflowStreamDescription,
5529}
5530
5531#[derive(Deserialize)]
5532struct WorkflowStreamPageResponse {
5533    stream: WorkflowStreamDescription,
5534    #[serde(default)]
5535    items: Vec<Value>,
5536    next_offset: u64,
5537    terminal: bool,
5538}
5539
5540#[derive(Deserialize)]
5541struct WorkflowStreamAppendResponse {
5542    stream: WorkflowStreamDescription,
5543    #[serde(default)]
5544    accepted_offsets: Vec<u64>,
5545    accepted: u64,
5546    deduped: u64,
5547}
5548
5549impl WorkflowDescription {
5550    pub fn is_completed(&self) -> bool {
5551        matches!(self.status.as_deref(), Some("completed" | "Completed"))
5552    }
5553
5554    pub fn is_terminal(&self) -> bool {
5555        matches!(
5556            self.status.as_deref(),
5557            Some(
5558                "completed"
5559                    | "Completed"
5560                    | "failed"
5561                    | "Failed"
5562                    | "cancelled"
5563                    | "Cancelled"
5564                    | "terminated"
5565                    | "Terminated"
5566                    | "timed_out"
5567                    | "TimedOut",
5568            )
5569        )
5570    }
5571
5572    fn decode_payloads(&mut self) -> Result<()> {
5573        if let Some(envelope) = &self.output_envelope {
5574            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
5575            self.output = Some(value.clone().into_json()?);
5576            self.output_avro_value = Some(value);
5577        }
5578
5579        Ok(())
5580    }
5581
5582    fn raw_value(&self) -> Value {
5583        let mut data = self.raw.clone();
5584        data.insert(
5585            "workflow_id".to_string(),
5586            self.workflow_id
5587                .clone()
5588                .map(Value::String)
5589                .unwrap_or(Value::Null),
5590        );
5591        data.insert(
5592            "run_id".to_string(),
5593            self.run_id
5594                .clone()
5595                .map(Value::String)
5596                .unwrap_or(Value::Null),
5597        );
5598        data.insert(
5599            "workflow_type".to_string(),
5600            self.workflow_type
5601                .clone()
5602                .map(Value::String)
5603                .unwrap_or(Value::Null),
5604        );
5605        data.insert(
5606            "status".to_string(),
5607            self.status
5608                .clone()
5609                .map(Value::String)
5610                .unwrap_or(Value::Null),
5611        );
5612        data.insert(
5613            "closed_reason".to_string(),
5614            self.closed_reason
5615                .clone()
5616                .map(Value::String)
5617                .unwrap_or(Value::Null),
5618        );
5619        if let Some(failure) = &self.failure {
5620            data.insert("failure".to_string(), failure.clone());
5621        }
5622        if let Some(exception) = &self.exception {
5623            data.insert("exception".to_string(), exception.clone());
5624        }
5625        Value::Object(data.into_iter().collect())
5626    }
5627}
5628
5629fn workflow_terminal_outcome(
5630    description: &WorkflowDescription,
5631    workflow_id: &str,
5632    run_id: Option<&str>,
5633) -> WorkflowTerminalOutcome {
5634    let terminal_kind = description
5635        .closed_reason
5636        .as_deref()
5637        .or(description.status.as_deref())
5638        .unwrap_or("failed")
5639        .to_ascii_lowercase();
5640    let kind = match terminal_kind.as_str() {
5641        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
5642        "terminated" => WorkflowTerminalKind::Terminated,
5643        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
5644        _ => WorkflowTerminalKind::Failed,
5645    };
5646    let default_reason = match kind {
5647        WorkflowTerminalKind::Failed => "workflow_failed",
5648        WorkflowTerminalKind::Cancelled => "cancelled",
5649        WorkflowTerminalKind::Terminated => "terminated",
5650        WorkflowTerminalKind::TimedOut => "timed_out",
5651    };
5652    let failure = description
5653        .failure
5654        .as_ref()
5655        .filter(|value| value.is_object());
5656    let nested_failure = failure
5657        .and_then(|value| value.get("failures"))
5658        .and_then(Value::as_array)
5659        .and_then(|failures| failures.last())
5660        .or_else(|| description.failures.last());
5661    let exception = description
5662        .exception
5663        .clone()
5664        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
5665        .or_else(|| {
5666            nested_failure
5667                .and_then(|value| value.get("exception_payload"))
5668                .cloned()
5669        });
5670    let string_field = |name: &str| {
5671        failure
5672            .and_then(|value| value.get(name))
5673            .and_then(Value::as_str)
5674            .or_else(|| {
5675                nested_failure
5676                    .and_then(|value| value.get(name))
5677                    .and_then(Value::as_str)
5678            })
5679            .map(str::to_string)
5680    };
5681    let exception_field = |name: &str| {
5682        exception
5683            .as_ref()
5684            .and_then(|value| value.get(name))
5685            .and_then(Value::as_str)
5686            .map(str::to_string)
5687    };
5688    let message = description
5689        .error
5690        .clone()
5691        .or_else(|| string_field("message"))
5692        .or_else(|| exception_field("message"));
5693    let reason = description
5694        .raw
5695        .get("reason")
5696        .and_then(Value::as_str)
5697        .map(str::to_string)
5698        .or_else(|| {
5699            failure
5700                .and_then(|value| value.get("reason"))
5701                .and_then(Value::as_str)
5702                .map(str::to_string)
5703        })
5704        .or_else(|| description.closed_reason.clone())
5705        .unwrap_or_else(|| default_reason.to_string());
5706    let failure_id = string_field("failure_id").or_else(|| {
5707        nested_failure
5708            .and_then(|value| value.get("id"))
5709            .and_then(Value::as_str)
5710            .map(str::to_string)
5711    });
5712
5713    WorkflowTerminalOutcome {
5714        kind,
5715        workflow_id: description
5716            .workflow_id
5717            .clone()
5718            .unwrap_or_else(|| workflow_id.to_string()),
5719        run_id: description
5720            .run_id
5721            .clone()
5722            .or_else(|| run_id.map(str::to_string)),
5723        reason,
5724        failure_category: string_field("failure_category")
5725            .or_else(|| Some(default_reason.to_string())),
5726        failure_id,
5727        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
5728        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
5729        non_retryable: failure
5730            .and_then(|value| value.get("non_retryable"))
5731            .and_then(Value::as_bool)
5732            .or_else(|| {
5733                nested_failure
5734                    .and_then(|value| value.get("non_retryable"))
5735                    .and_then(Value::as_bool)
5736            }),
5737        message,
5738        exception,
5739        raw: description.raw_value(),
5740    }
5741}
5742
5743#[derive(Clone, Debug, Deserialize)]
5744pub struct RegisterWorkerResponse {
5745    pub worker_id: String,
5746    pub registered: bool,
5747    #[serde(default)]
5748    pub heartbeat_interval_seconds: Option<u64>,
5749    #[serde(default)]
5750    pub protocol_version: Option<String>,
5751    #[serde(default)]
5752    pub server_capabilities: Option<Value>,
5753}
5754
5755/// Result of gracefully removing a worker-plane registration.
5756#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5757pub struct WorkerDeregistrationEnvelope {
5758    pub worker_id: String,
5759    pub outcome: String,
5760    pub recovered_workflow_task_count: u64,
5761}
5762
5763#[derive(Clone, Debug, Deserialize)]
5764pub struct PollWorkflowTaskResponse {
5765    #[serde(default)]
5766    pub task: Option<WorkflowTask>,
5767    #[serde(default)]
5768    pub poll_status: Option<String>,
5769    #[serde(default)]
5770    pub reason: Option<String>,
5771    #[serde(default)]
5772    pub protocol_version: Option<String>,
5773    #[serde(default)]
5774    pub server_capabilities: Option<Value>,
5775}
5776
5777impl PollWorkflowTaskResponse {
5778    /// Classify this response without parsing server display text.
5779    pub fn outcome(&self) -> WorkerPollOutcome {
5780        worker_poll_outcome(
5781            self.task.is_some(),
5782            self.poll_status.as_deref(),
5783            self.reason.as_deref(),
5784        )
5785    }
5786}
5787
5788fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
5789    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
5790        return false;
5791    };
5792    let supported = capabilities
5793        .get("workflow_memo_updates")
5794        .and_then(Value::as_object)
5795        .and_then(|memo| memo.get("supported"))
5796        .and_then(Value::as_bool)
5797        == Some(true);
5798    let command_advertised = capabilities
5799        .get("supported_workflow_task_commands")
5800        .and_then(Value::as_array)
5801        .is_some_and(|commands| {
5802            commands
5803                .iter()
5804                .any(|command| command.as_str() == Some("upsert_memo"))
5805        });
5806    supported && command_advertised
5807}
5808
5809fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
5810    commands
5811        .iter()
5812        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
5813}
5814
5815#[derive(Clone, Debug, Deserialize)]
5816pub struct PollActivityTaskResponse {
5817    #[serde(default)]
5818    pub task: Option<ActivityTask>,
5819    #[serde(default)]
5820    pub poll_status: Option<String>,
5821    #[serde(default)]
5822    pub reason: Option<String>,
5823}
5824
5825impl PollActivityTaskResponse {
5826    /// Classify this response without parsing server display text.
5827    pub fn outcome(&self) -> WorkerPollOutcome {
5828        worker_poll_outcome(
5829            self.task.is_some(),
5830            self.poll_status.as_deref(),
5831            self.reason.as_deref(),
5832        )
5833    }
5834}
5835
5836#[derive(Clone, Debug, Deserialize)]
5837pub struct PollQueryTaskResponse {
5838    #[serde(default)]
5839    pub task: Option<QueryTask>,
5840    #[serde(default)]
5841    pub poll_status: Option<String>,
5842    #[serde(default)]
5843    pub reason: Option<String>,
5844}
5845
5846impl PollQueryTaskResponse {
5847    /// Classify this response without parsing server display text.
5848    pub fn outcome(&self) -> WorkerPollOutcome {
5849        worker_poll_outcome(
5850            self.task.is_some(),
5851            self.poll_status.as_deref(),
5852            self.reason.as_deref(),
5853        )
5854    }
5855}
5856
5857/// Stable classification for worker poll responses.
5858#[derive(Clone, Debug, PartialEq, Eq)]
5859pub enum WorkerPollOutcome {
5860    /// A task was leased and is available on the response.
5861    Task,
5862    /// No task was leased, but the worker should continue polling.
5863    Idle {
5864        poll_status: Option<String>,
5865        reason: Option<String>,
5866    },
5867    /// The server asked this worker to stop claiming new work.
5868    Stop {
5869        poll_status: Option<String>,
5870        reason: Option<String>,
5871    },
5872}
5873
5874impl WorkerPollOutcome {
5875    pub fn should_stop(&self) -> bool {
5876        matches!(self, Self::Stop { .. })
5877    }
5878}
5879
5880fn worker_poll_outcome(
5881    has_task: bool,
5882    poll_status: Option<&str>,
5883    reason: Option<&str>,
5884) -> WorkerPollOutcome {
5885    if worker_poll_is_stop(poll_status, reason) {
5886        return WorkerPollOutcome::Stop {
5887            poll_status: poll_status.map(str::to_string),
5888            reason: reason.map(str::to_string),
5889        };
5890    }
5891
5892    if has_task {
5893        WorkerPollOutcome::Task
5894    } else {
5895        WorkerPollOutcome::Idle {
5896            poll_status: poll_status.map(str::to_string),
5897            reason: reason.map(str::to_string),
5898        }
5899    }
5900}
5901
5902/// An ephemeral server-routed query task.
5903#[derive(Clone, Debug, Deserialize)]
5904pub struct QueryTask {
5905    pub query_task_id: String,
5906    #[serde(default = "default_workflow_task_attempt")]
5907    pub query_task_attempt: u64,
5908    #[serde(default)]
5909    pub lease_owner: Option<String>,
5910    #[serde(default)]
5911    pub workflow_id: Option<String>,
5912    #[serde(default)]
5913    pub run_id: Option<String>,
5914    pub workflow_type: String,
5915    pub query_name: String,
5916    #[serde(
5917        default = "missing_task_payload_codec",
5918        deserialize_with = "deserialize_task_payload_codec"
5919    )]
5920    pub payload_codec: String,
5921    #[serde(default)]
5922    pub workflow_arguments: Option<Value>,
5923    #[serde(default)]
5924    pub query_arguments: Option<Value>,
5925    #[serde(default)]
5926    pub history_events: Vec<HistoryEvent>,
5927    #[serde(default)]
5928    pub history_export: Option<Value>,
5929    #[serde(default)]
5930    pub run_status: Option<String>,
5931}
5932
5933#[derive(Clone, Debug, Deserialize)]
5934pub struct WorkflowTask {
5935    pub task_id: String,
5936    #[serde(default)]
5937    pub workflow_command_id: Option<String>,
5938    #[serde(default)]
5939    pub workflow_id: Option<String>,
5940    #[serde(default)]
5941    pub run_id: Option<String>,
5942    pub workflow_type: String,
5943    #[serde(default)]
5944    pub cancel_requested: bool,
5945    #[serde(
5946        default = "missing_task_payload_codec",
5947        deserialize_with = "deserialize_task_payload_codec"
5948    )]
5949    pub payload_codec: String,
5950    #[serde(default)]
5951    pub arguments: Option<Value>,
5952    #[serde(default)]
5953    pub history_events: Vec<HistoryEvent>,
5954    #[serde(default)]
5955    pub total_history_events: Option<u64>,
5956    #[serde(default)]
5957    pub history_size_bytes: Option<u64>,
5958    #[serde(default)]
5959    pub continue_as_new_recommended: Option<bool>,
5960    #[serde(default)]
5961    pub history_budget_pressure: Option<String>,
5962    #[serde(default)]
5963    pub next_history_page_token: Option<String>,
5964    #[serde(default = "default_workflow_task_attempt")]
5965    pub workflow_task_attempt: u64,
5966    #[serde(default)]
5967    pub workflow_signal_id: Option<String>,
5968    #[serde(default)]
5969    pub signal_name: Option<String>,
5970    #[serde(default)]
5971    pub signal_arguments: Option<Value>,
5972    #[serde(default)]
5973    pub workflow_update_id: Option<String>,
5974    #[serde(default)]
5975    pub update_name: Option<String>,
5976    #[serde(default)]
5977    pub lease_owner: Option<String>,
5978}
5979
5980impl WorkflowTask {
5981    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
5982        self.history_events.extend(page.history_events);
5983
5984        if page.total_history_events.is_some() {
5985            self.total_history_events = page.total_history_events;
5986        }
5987
5988        self.next_history_page_token = page
5989            .next_history_page_token
5990            .filter(|token| !token.is_empty());
5991    }
5992}
5993
5994#[derive(Clone, Debug, Deserialize)]
5995struct WorkflowTaskHistoryPage {
5996    #[serde(default)]
5997    history_events: Vec<HistoryEvent>,
5998    #[serde(default)]
5999    total_history_events: Option<u64>,
6000    #[serde(default)]
6001    next_history_page_token: Option<String>,
6002}
6003
6004#[derive(Clone, Debug, Deserialize)]
6005pub struct ActivityTask {
6006    pub task_id: String,
6007    #[serde(default)]
6008    pub activity_attempt_id: Option<String>,
6009    #[serde(default)]
6010    pub attempt_id: Option<String>,
6011    pub activity_type: String,
6012    #[serde(
6013        default = "missing_task_payload_codec",
6014        deserialize_with = "deserialize_task_payload_codec"
6015    )]
6016    pub payload_codec: String,
6017    #[serde(default)]
6018    pub arguments: Option<Value>,
6019    #[serde(default = "default_attempt_number")]
6020    pub attempt_number: u64,
6021    #[serde(default)]
6022    pub lease_owner: Option<String>,
6023}
6024
6025#[derive(Clone, Debug, Deserialize)]
6026pub struct HistoryEvent {
6027    #[serde(alias = "type")]
6028    pub event_type: String,
6029    #[serde(default)]
6030    pub payload: Value,
6031    #[serde(flatten)]
6032    pub raw: HashMap<String, Value>,
6033}
6034
6035/// One decoded signal in the committed workflow-history snapshot.
6036#[derive(Clone, Debug, PartialEq)]
6037pub struct QuerySignal {
6038    pub id: Option<String>,
6039    pub name: String,
6040    pub arguments: Vec<Value>,
6041    avro_arguments: Vec<AvroValue>,
6042    pub workflow_sequence: Option<u64>,
6043}
6044
6045impl QuerySignal {
6046    /// Lossless fixed Avro Value arguments for this committed signal.
6047    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6048        &self.avro_arguments
6049    }
6050}
6051
6052/// Immutable state supplied to a registered query handler.
6053///
6054/// This context intentionally exposes no activity, signal-wait, or command
6055/// APIs. Query handlers inspect committed history and return a value; query
6056/// completion does not append an event or advance deterministic execution.
6057#[derive(Clone, Debug)]
6058pub struct QueryContext {
6059    pub workflow_id: Option<String>,
6060    pub run_id: Option<String>,
6061    pub workflow_type: String,
6062    pub run_status: Option<String>,
6063    workflow_input: Value,
6064    workflow_input_avro_value: AvroValue,
6065    history_events: Arc<Vec<HistoryEvent>>,
6066    signal_events: Arc<Vec<QuerySignal>>,
6067}
6068
6069impl QueryContext {
6070    /// The normalized argument list used to start the workflow.
6071    pub fn workflow_input(&self) -> &Value {
6072        &self.workflow_input
6073    }
6074
6075    /// The lossless fixed Avro Value argument list used to start the workflow.
6076    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6077        &self.workflow_input_avro_value
6078    }
6079
6080    /// The immutable committed history used for this query snapshot.
6081    pub fn history_events(&self) -> &[HistoryEvent] {
6082        self.history_events.as_slice()
6083    }
6084
6085    /// All decoded signals in committed workflow order.
6086    pub fn signal_events(&self) -> &[QuerySignal] {
6087        self.signal_events.as_slice()
6088    }
6089
6090    /// Decoded argument lists for each committed signal with `signal_name`.
6091    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6092        self.signal_events
6093            .iter()
6094            .filter(|signal| signal.name == signal_name)
6095            .map(|signal| signal.arguments.clone())
6096            .collect()
6097    }
6098
6099    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6100    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6101        self.signal_events
6102            .iter()
6103            .filter(|signal| signal.name == signal_name)
6104            .map(|signal| signal.avro_arguments.clone())
6105            .collect()
6106    }
6107}
6108
6109#[derive(Clone, Debug, Deserialize)]
6110pub struct ActivityHeartbeatResponse {
6111    #[serde(default)]
6112    pub cancel_requested: bool,
6113    #[serde(default)]
6114    pub heartbeat_recorded: bool,
6115    #[serde(default)]
6116    pub can_continue: Option<bool>,
6117    #[serde(default)]
6118    pub reason: Option<String>,
6119    #[serde(default)]
6120    pub run_closed_reason: Option<String>,
6121    #[serde(default)]
6122    pub run_closed_at: Option<String>,
6123    #[serde(default)]
6124    pub lease_expires_at: Option<String>,
6125    #[serde(default)]
6126    pub last_heartbeat_at: Option<String>,
6127}
6128
6129impl ActivityHeartbeatResponse {
6130    /// Whether the activity should stop instead of attempting completion.
6131    pub fn should_stop(&self) -> bool {
6132        self.cancel_requested || self.can_continue == Some(false)
6133    }
6134}
6135
6136fn missing_task_payload_codec() -> String {
6137    MISSING_TASK_PAYLOAD_CODEC.to_string()
6138}
6139
6140fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6141where
6142    D: Deserializer<'de>,
6143{
6144    Ok(match Value::deserialize(deserializer)? {
6145        Value::String(codec) => codec,
6146        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6147        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6148    })
6149}
6150
6151fn default_workflow_task_attempt() -> u64 {
6152    1
6153}
6154
6155fn default_attempt_number() -> u64 {
6156    1
6157}
6158
6159type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6160type WorkflowHandler = Arc<dyn Fn(WorkflowContext, AvroValue) -> WorkflowFuture + Send + Sync>;
6161type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6162type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6163type ReplayedWorkflowHandler =
6164    Arc<dyn Fn(WorkflowContext, AvroValue) -> ReplayedWorkflowInvocation + Send + Sync>;
6165type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6166type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6167type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6168type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6169type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6170type ReplayedQueryHandler = Arc<
6171    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6172        + Send
6173        + Sync,
6174>;
6175type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6176
6177struct ReplayedWorkflowInvocation {
6178    future: WorkflowFuture,
6179    snapshot: WorkflowStateSnapshot,
6180}
6181
6182#[derive(Clone)]
6183struct RegisteredWorkflow {
6184    execute: WorkflowHandler,
6185    replay: Option<ReplayedWorkflowHandler>,
6186    state_type: Option<TypeId>,
6187    definition_fingerprint: Option<String>,
6188}
6189
6190#[derive(Debug)]
6191struct WorkflowTaskDecision {
6192    commands: Vec<Value>,
6193    message_stream_cursors: Vec<Value>,
6194    message_stream_waits: Vec<Value>,
6195    cancellation_delivery: Option<CancellationDelivery>,
6196    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6197    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6198}
6199
6200impl WorkflowTaskDecision {
6201    fn without_message_streams(commands: Vec<Value>) -> Self {
6202        Self {
6203            commands,
6204            message_stream_cursors: Vec::new(),
6205            message_stream_waits: Vec::new(),
6206            cancellation_delivery: None,
6207            cancellation_scope_opening: None,
6208            cancellation_scope_delivery: None,
6209        }
6210    }
6211}
6212
6213#[derive(Clone)]
6214enum RegisteredQuery {
6215    Snapshot(QueryHandler),
6216    Replayed {
6217        state_type: TypeId,
6218        handler: ReplayedQueryHandler,
6219    },
6220}
6221
6222#[derive(Clone, Debug)]
6223pub struct WorkerHeartbeatObservation {
6224    pub worker_id: String,
6225    pub task_queue: String,
6226    pub acknowledged_at_unix_millis: u64,
6227    pub acknowledgement: Value,
6228}
6229
6230/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6231///
6232/// Expected empty long polls and explicit Server capacity backpressure are
6233/// normal worker states. Capacity backpressure honors the advertised retry
6234/// delay without consuming this retry budget. Other transport failures,
6235/// retryable HTTP 408/429 responses, and server errors are retried with capped
6236/// exponential backoff. Authentication, protocol, codec, and handler failures
6237/// are never retried by the worker.
6238/// Explicit storage admission pauses also preserve the already-serialized worker
6239/// request without consuming this budget or rerunning its handler. The delay is
6240/// capped by `max_backoff`, and shutdown interrupts storage waits.
6241#[derive(Clone, Copy, Debug)]
6242pub struct WorkerRetryPolicy {
6243    /// Number of retries after the initial request fails.
6244    pub max_retries: usize,
6245    /// Delay before the first retry.
6246    pub initial_backoff: Duration,
6247    /// Maximum delay between retries.
6248    pub max_backoff: Duration,
6249}
6250
6251impl Default for WorkerRetryPolicy {
6252    fn default() -> Self {
6253        Self {
6254            max_retries: 5,
6255            initial_backoff: Duration::from_millis(100),
6256            max_backoff: Duration::from_secs(5),
6257        }
6258    }
6259}
6260
6261#[derive(Clone, Debug)]
6262struct WorkerStorageAdmission {
6263    policy: WorkerRetryPolicy,
6264    stop: Arc<AtomicBool>,
6265}
6266
6267struct StopWorkerOnDrop(Arc<AtomicBool>);
6268
6269impl Drop for StopWorkerOnDrop {
6270    fn drop(&mut self) {
6271        self.0.store(true, Ordering::SeqCst);
6272    }
6273}
6274
6275async fn wait_for_worker_stop(stop: &AtomicBool) {
6276    while !stop.load(Ordering::SeqCst) {
6277        tokio::time::sleep(Duration::from_millis(100)).await;
6278    }
6279}
6280
6281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6282enum ManagedPollOutcome {
6283    Idle,
6284    Handled,
6285    Stop,
6286}
6287
6288#[derive(Clone)]
6289pub struct Worker {
6290    client: Client,
6291    worker_id: String,
6292    task_queue: String,
6293    workflows: HashMap<String, RegisteredWorkflow>,
6294    activities: HashMap<String, ActivityHandler>,
6295    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6296    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6297    max_concurrent_workflow_tasks: usize,
6298    max_concurrent_activity_tasks: usize,
6299    poll_timeout: Duration,
6300    heartbeat_interval: Duration,
6301    retry_policy: WorkerRetryPolicy,
6302    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6303    cooperative_cancellation_enabled: bool,
6304    allow_cancellation_scope_authoring: bool,
6305    allow_cancellation_scope_delivery: bool,
6306    cooperative_registration_confirmed: Arc<AtomicBool>,
6307}
6308
6309impl Worker {
6310    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6311        Self {
6312            client,
6313            worker_id: default_worker_id(),
6314            task_queue: task_queue.into(),
6315            workflows: HashMap::new(),
6316            activities: HashMap::new(),
6317            queries: HashMap::new(),
6318            updates: HashMap::new(),
6319            max_concurrent_workflow_tasks: 10,
6320            max_concurrent_activity_tasks: 10,
6321            poll_timeout: Duration::from_secs(30),
6322            heartbeat_interval: Duration::from_secs(60),
6323            retry_policy: WorkerRetryPolicy::default(),
6324            heartbeat_observer: None,
6325            cooperative_cancellation_enabled: false,
6326            allow_cancellation_scope_authoring: false,
6327            allow_cancellation_scope_delivery: false,
6328            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6329        }
6330    }
6331
6332    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6333        self.worker_id = worker_id.into();
6334        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6335        self
6336    }
6337
6338    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6339        self.poll_timeout = timeout;
6340        self
6341    }
6342
6343    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6344        self.heartbeat_interval = interval;
6345        self
6346    }
6347
6348    /// Opt in to separate cooperative workflow cancellation requests.
6349    ///
6350    /// Registration requires the Server to acknowledge this exact worker,
6351    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6352    /// processing uses canonical delivery and activity ownership fences.
6353    /// Existing terminal cancel and terminate operations remain terminal.
6354    /// The default is disabled, preserving ordinary protocol 1.19 workers.
6355    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6356    /// and [`Worker::run_until`] register automatically.
6357    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6358        self.cooperative_cancellation_enabled = enabled;
6359        self.client.cooperative_worker_protocol = enabled;
6360        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6361        self
6362    }
6363
6364    /// Enable candidate scope authoring without advertising scoped execution.
6365    #[doc(hidden)]
6366    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6367        self.allow_cancellation_scope_authoring = enabled;
6368        self
6369    }
6370
6371    /// Enable the candidate scoped call consumer with canonical authoring.
6372    #[doc(hidden)]
6373    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6374        self.allow_cancellation_scope_delivery = enabled;
6375        self
6376    }
6377
6378    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6379    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6380        self.retry_policy = policy;
6381        self
6382    }
6383
6384    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6385    where
6386        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6387    {
6388        self.heartbeat_observer = Some(Arc::new(observer));
6389        self
6390    }
6391
6392    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6393        self.max_concurrent_workflow_tasks = count.max(1);
6394        self
6395    }
6396
6397    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6398        self.max_concurrent_activity_tasks = count.max(1);
6399        self
6400    }
6401
6402    /// Register a workflow handler.
6403    ///
6404    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6405    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6406    /// while acquiring or decoding a worker task remain worker-operation
6407    /// failures and do not get converted into workflow outcomes.
6408    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6409    where
6410        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6411        Fut: Future<Output = Result<Value>> + Send + 'static,
6412    {
6413        let handler = Arc::new(handler);
6414        self.workflows.insert(
6415            workflow_type.into(),
6416            RegisteredWorkflow {
6417                execute: Arc::new(move |ctx, input| {
6418                    let handler = Arc::clone(&handler);
6419                    Box::pin(async move {
6420                        let result = handler(ctx, input.into_json()?).await?;
6421                        AvroValue::from_serialize(&result)
6422                    })
6423                }),
6424                replay: None,
6425                state_type: None,
6426                definition_fingerprint: None,
6427            },
6428        );
6429    }
6430
6431    /// Register a workflow with one Serde request value and a Serde result.
6432    ///
6433    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
6434    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
6435    /// workflow-specific schema. A task must contain zero arguments for a unit
6436    /// request or exactly one argument for every other request type.
6437    ///
6438    /// See the runnable
6439    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
6440    /// for typed workflow and activity contracts with retry and timeout policy.
6441    pub fn register_typed_workflow<I, O, F, Fut>(
6442        &mut self,
6443        workflow_type: impl Into<String>,
6444        handler: F,
6445    ) where
6446        I: DeserializeOwned + Send + 'static,
6447        O: Serialize + Send + 'static,
6448        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
6449        Fut: Future<Output = Result<O>> + Send + 'static,
6450    {
6451        let workflow_type = workflow_type.into();
6452        let handler_name = workflow_type.clone();
6453        let handler = Arc::new(handler);
6454        self.workflows.insert(
6455            workflow_type,
6456            RegisteredWorkflow {
6457                execute: Arc::new(move |ctx, input| {
6458                    let handler = Arc::clone(&handler);
6459                    let handler_name = handler_name.clone();
6460                    Box::pin(async move {
6461                        let input =
6462                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6463                        let result = handler(ctx, input).await?;
6464                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6465                    })
6466                }),
6467                replay: None,
6468                state_type: None,
6469                definition_fingerprint: None,
6470            },
6471        );
6472    }
6473
6474    /// Register a workflow on the lossless fixed Avro Value surface.
6475    pub fn register_workflow_avro_value<F, Fut>(
6476        &mut self,
6477        workflow_type: impl Into<String>,
6478        handler: F,
6479    ) where
6480        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
6481        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6482    {
6483        self.workflows.insert(
6484            workflow_type.into(),
6485            RegisteredWorkflow {
6486                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
6487                replay: None,
6488                state_type: None,
6489                definition_fingerprint: None,
6490            },
6491        );
6492    }
6493
6494    /// Register a workflow whose typed instance state can be reconstructed for queries.
6495    ///
6496    /// `state_factory` creates a fresh instance for every normal workflow task and
6497    /// query replay. The workflow handler is the single source of truth for state
6498    /// transitions: it updates [`WorkflowInstance`] after activities and signals
6499    /// resolve. Query replay runs this same handler over committed history and
6500    /// discards any commands it would emit.
6501    pub fn register_replayed_workflow<S, Factory, F, Fut>(
6502        &mut self,
6503        workflow_type: impl Into<String>,
6504        state_factory: Factory,
6505        handler: F,
6506    ) where
6507        S: Clone + Send + Sync + 'static,
6508        Factory: Fn() -> S + Send + Sync + 'static,
6509        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6510        Fut: Future<Output = Result<Value>> + Send + 'static,
6511    {
6512        let state_factory = Arc::new(state_factory);
6513        let handler = Arc::new(handler);
6514
6515        let execute_factory = Arc::clone(&state_factory);
6516        let execute_handler = Arc::clone(&handler);
6517        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6518            let state = WorkflowInstance::new(execute_factory());
6519            let handler = Arc::clone(&execute_handler);
6520            Box::pin(async move {
6521                let result = handler(ctx, input.into_json()?, state).await?;
6522                AvroValue::from_serialize(&result)
6523            }) as WorkflowFuture
6524        });
6525
6526        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6527            let state = WorkflowInstance::new(state_factory());
6528            let snapshot_state = state.clone();
6529            let snapshot: WorkflowStateSnapshot =
6530                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6531            let replay_handler = Arc::clone(&handler);
6532            let future = async move {
6533                let result = replay_handler(ctx, input.into_json()?, state).await?;
6534                AvroValue::from_serialize(&result)
6535            };
6536            ReplayedWorkflowInvocation {
6537                future: Box::pin(future),
6538                snapshot,
6539            }
6540        });
6541
6542        self.workflows.insert(
6543            workflow_type.into(),
6544            RegisteredWorkflow {
6545                execute,
6546                replay: Some(replay),
6547                state_type: Some(TypeId::of::<S>()),
6548                definition_fingerprint: None,
6549            },
6550        );
6551    }
6552
6553    /// Register a replayable workflow with one Serde request value and result.
6554    ///
6555    /// Normal task execution and instance-state query replay both decode and
6556    /// encode through the fixed Avro Value codec. The state factory and handler
6557    /// otherwise follow [`Worker::register_replayed_workflow`].
6558    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
6559        &mut self,
6560        workflow_type: impl Into<String>,
6561        state_factory: Factory,
6562        handler: F,
6563    ) where
6564        I: DeserializeOwned + Send + 'static,
6565        O: Serialize + Send + 'static,
6566        S: Clone + Send + Sync + 'static,
6567        Factory: Fn() -> S + Send + Sync + 'static,
6568        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6569        Fut: Future<Output = Result<O>> + Send + 'static,
6570    {
6571        let workflow_type = workflow_type.into();
6572        let state_factory = Arc::new(state_factory);
6573        let handler = Arc::new(handler);
6574
6575        let execute_name = workflow_type.clone();
6576        let execute_factory = Arc::clone(&state_factory);
6577        let execute_handler = Arc::clone(&handler);
6578        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6579            let state = WorkflowInstance::new(execute_factory());
6580            let handler = Arc::clone(&execute_handler);
6581            let handler_name = execute_name.clone();
6582            Box::pin(async move {
6583                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6584                let result = handler(ctx, input, state).await?;
6585                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6586            }) as WorkflowFuture
6587        });
6588
6589        let replay_name = workflow_type.clone();
6590        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6591            let state = WorkflowInstance::new(state_factory());
6592            let snapshot_state = state.clone();
6593            let snapshot: WorkflowStateSnapshot =
6594                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6595            let handler = Arc::clone(&handler);
6596            let handler_name = replay_name.clone();
6597            let future = async move {
6598                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6599                let result = handler(ctx, input, state).await?;
6600                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6601            };
6602            ReplayedWorkflowInvocation {
6603                future: Box::pin(future),
6604                snapshot,
6605            }
6606        });
6607
6608        self.workflows.insert(
6609            workflow_type,
6610            RegisteredWorkflow {
6611                execute,
6612                replay: Some(replay),
6613                state_type: Some(TypeId::of::<S>()),
6614                definition_fingerprint: None,
6615            },
6616        );
6617    }
6618
6619    /// Bind a registered workflow to compile-time embedded source for safe redrive.
6620    ///
6621    /// Supply `include_str!` values for the workflow body and every helper whose
6622    /// behavior can affect replay. A handler re-registration clears the local
6623    /// identity; call this after registering the final handler. The server
6624    /// rejects reusing a worker ID when its prior fingerprint disappears.
6625    /// Workflows without source identity remain runnable but cannot be safely redriven.
6626    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
6627    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
6628    pub fn set_workflow_definition_sources(
6629        &mut self,
6630        workflow_type: &str,
6631        sources: &[&str],
6632    ) -> Result<()> {
6633        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
6634            return Err(Error::Codec(
6635                "workflow definition sources must be non-empty".to_string(),
6636            ));
6637        }
6638        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
6639            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
6640        })?;
6641        let mut hasher = Sha256::new();
6642        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
6643        hasher.update((workflow_type.len() as u64).to_be_bytes());
6644        hasher.update(workflow_type.as_bytes());
6645        for source in sources {
6646            hasher.update((source.len() as u64).to_be_bytes());
6647            hasher.update(source.as_bytes());
6648        }
6649        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
6650        Ok(())
6651    }
6652
6653    /// Register a replayable workflow on the lossless fixed Avro Value surface.
6654    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
6655        &mut self,
6656        workflow_type: impl Into<String>,
6657        state_factory: Factory,
6658        handler: F,
6659    ) where
6660        S: Clone + Send + Sync + 'static,
6661        Factory: Fn() -> S + Send + Sync + 'static,
6662        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6663        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6664    {
6665        let state_factory = Arc::new(state_factory);
6666        let handler = Arc::new(handler);
6667
6668        let execute_factory = Arc::clone(&state_factory);
6669        let execute_handler = Arc::clone(&handler);
6670        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6671            let state = WorkflowInstance::new(execute_factory());
6672            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
6673        });
6674
6675        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6676            let state = WorkflowInstance::new(state_factory());
6677            let snapshot_state = state.clone();
6678            let snapshot: WorkflowStateSnapshot =
6679                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6680            ReplayedWorkflowInvocation {
6681                future: Box::pin(handler(ctx, input, state)),
6682                snapshot,
6683            }
6684        });
6685
6686        self.workflows.insert(
6687            workflow_type.into(),
6688            RegisteredWorkflow {
6689                execute,
6690                replay: Some(replay),
6691                state_type: Some(TypeId::of::<S>()),
6692                definition_fingerprint: None,
6693            },
6694        );
6695    }
6696
6697    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
6698    where
6699        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
6700        Fut: Future<Output = Result<Value>> + Send + 'static,
6701    {
6702        let handler = Arc::new(handler);
6703        self.activities.insert(
6704            activity_type.into(),
6705            Arc::new(move |ctx, args| {
6706                let handler = Arc::clone(&handler);
6707                Box::pin(async move {
6708                    let result = handler(ctx, args.into_json()?).await?;
6709                    AvroValue::from_serialize(&result)
6710                })
6711            }),
6712        );
6713    }
6714
6715    /// Register an activity with one Serde request value and a Serde result.
6716    ///
6717    /// Inputs and results use the platform's fixed Avro Value schema. Shape
6718    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
6719    /// with the activity name and Rust type.
6720    pub fn register_typed_activity<I, O, F, Fut>(
6721        &mut self,
6722        activity_type: impl Into<String>,
6723        handler: F,
6724    ) where
6725        I: DeserializeOwned + Send + 'static,
6726        O: Serialize + Send + 'static,
6727        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
6728        Fut: Future<Output = Result<O>> + Send + 'static,
6729    {
6730        let activity_type = activity_type.into();
6731        let handler_name = activity_type.clone();
6732        let handler = Arc::new(handler);
6733        self.activities.insert(
6734            activity_type,
6735            Arc::new(move |ctx, input| {
6736                let handler = Arc::clone(&handler);
6737                let handler_name = handler_name.clone();
6738                Box::pin(async move {
6739                    let input =
6740                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
6741                    let result = handler(ctx, input).await?;
6742                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
6743                })
6744            }),
6745        );
6746    }
6747
6748    /// Register an activity on the lossless fixed Avro Value surface.
6749    pub fn register_activity_avro_value<F, Fut>(
6750        &mut self,
6751        activity_type: impl Into<String>,
6752        handler: F,
6753    ) where
6754        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
6755        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6756    {
6757        self.activities.insert(
6758            activity_type.into(),
6759            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
6760        );
6761    }
6762
6763    /// Register a named, read-only query handler for a workflow type.
6764    ///
6765    /// The workflow type must also be registered with [`Worker::register_workflow`]
6766    /// before the worker runs. The handler receives only an immutable committed
6767    /// state snapshot and normalized query arguments.
6768    pub fn register_query<F, Fut>(
6769        &mut self,
6770        workflow_type: impl Into<String>,
6771        query_name: impl Into<String>,
6772        handler: F,
6773    ) where
6774        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
6775        Fut: Future<Output = Result<Value>> + Send + 'static,
6776    {
6777        let handler = Arc::new(handler);
6778        self.queries
6779            .entry(workflow_type.into())
6780            .or_default()
6781            .insert(
6782                query_name.into(),
6783                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
6784                    let handler = Arc::clone(&handler);
6785                    Box::pin(async move {
6786                        let result = handler(ctx, args.into_json()?).await?;
6787                        AvroValue::from_serialize(&result)
6788                    })
6789                })),
6790            );
6791    }
6792
6793    /// Register a query handler on the lossless fixed Avro Value surface.
6794    pub fn register_query_avro_value<F, Fut>(
6795        &mut self,
6796        workflow_type: impl Into<String>,
6797        query_name: impl Into<String>,
6798        handler: F,
6799    ) where
6800        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
6801        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6802    {
6803        self.queries
6804            .entry(workflow_type.into())
6805            .or_default()
6806            .insert(
6807                query_name.into(),
6808                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
6809            );
6810    }
6811
6812    /// Register a named query against deterministically replayed instance state.
6813    ///
6814    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
6815    /// same state type `S`. The handler receives an immutable, detached state
6816    /// clone, so successful and failed queries cannot affect workflow execution
6817    /// or the state reconstructed by a later query.
6818    pub fn register_replayed_query<S, F, Fut>(
6819        &mut self,
6820        workflow_type: impl Into<String>,
6821        query_name: impl Into<String>,
6822        handler: F,
6823    ) where
6824        S: Clone + Send + Sync + 'static,
6825        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
6826        Fut: Future<Output = Result<Value>> + Send + 'static,
6827    {
6828        let handler = Arc::new(handler);
6829        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
6830            let state = state.downcast::<S>().map_err(|_| {
6831                "registered query state type does not match the replayed workflow state".to_string()
6832            })?;
6833            let handler = Arc::clone(&handler);
6834            Ok(Box::pin(async move {
6835                let result = handler(ctx, state, args.into_json()?).await?;
6836                AvroValue::from_serialize(&result)
6837            }))
6838        });
6839
6840        self.queries
6841            .entry(workflow_type.into())
6842            .or_default()
6843            .insert(
6844                query_name.into(),
6845                RegisteredQuery::Replayed {
6846                    state_type: TypeId::of::<S>(),
6847                    handler: erased_handler,
6848                },
6849            );
6850    }
6851
6852    /// Register a replayed-state query on the lossless fixed Avro Value surface.
6853    pub fn register_replayed_query_avro_value<S, F, Fut>(
6854        &mut self,
6855        workflow_type: impl Into<String>,
6856        query_name: impl Into<String>,
6857        handler: F,
6858    ) where
6859        S: Clone + Send + Sync + 'static,
6860        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
6861        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6862    {
6863        let handler = Arc::new(handler);
6864        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
6865            let state = state.downcast::<S>().map_err(|_| {
6866                "registered query state type does not match the replayed workflow state".to_string()
6867            })?;
6868            Ok(Box::pin(handler(ctx, state, args)))
6869        });
6870
6871        self.queries
6872            .entry(workflow_type.into())
6873            .or_default()
6874            .insert(
6875                query_name.into(),
6876                RegisteredQuery::Replayed {
6877                    state_type: TypeId::of::<S>(),
6878                    handler: erased_handler,
6879                },
6880            );
6881    }
6882
6883    /// Register a synchronous workflow update handler.
6884    pub fn register_update<F, Fut>(
6885        &mut self,
6886        workflow_type: impl Into<String>,
6887        update_name: impl Into<String>,
6888        handler: F,
6889    ) where
6890        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
6891        Fut: Future<Output = Result<Value>> + Send + 'static,
6892    {
6893        let handler = Arc::new(handler);
6894        self.updates
6895            .entry(workflow_type.into())
6896            .or_default()
6897            .insert(
6898                update_name.into(),
6899                Arc::new(move |ctx, args| {
6900                    let handler = Arc::clone(&handler);
6901                    Box::pin(async move {
6902                        let result = handler(ctx, args.into_json()?).await?;
6903                        AvroValue::from_serialize(&result)
6904                    })
6905                }),
6906            );
6907    }
6908
6909    /// Register an update handler on the lossless fixed Avro Value surface.
6910    pub fn register_update_avro_value<F, Fut>(
6911        &mut self,
6912        workflow_type: impl Into<String>,
6913        update_name: impl Into<String>,
6914        handler: F,
6915    ) where
6916        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
6917        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6918    {
6919        self.updates
6920            .entry(workflow_type.into())
6921            .or_default()
6922            .insert(
6923                update_name.into(),
6924                Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
6925            );
6926    }
6927
6928    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
6929        let mut command_contracts = serde_json::Map::new();
6930        for workflow_type in self.workflows.keys() {
6931            let mut queries = self
6932                .queries
6933                .get(workflow_type)
6934                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
6935                .unwrap_or_default();
6936            queries.sort();
6937            let mut updates = self
6938                .updates
6939                .get(workflow_type)
6940                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
6941                .unwrap_or_default();
6942            updates.sort();
6943            command_contracts.insert(
6944                workflow_type.clone(),
6945                json!({
6946                    "queries": queries,
6947                    "query_contracts": [],
6948                    "signals": [],
6949                    "signal_contracts": [],
6950                    "updates": updates,
6951                    "update_contracts": [],
6952                    "update_validators": [],
6953                }),
6954            );
6955        }
6956
6957        self.cooperative_registration_confirmed
6958            .store(false, Ordering::SeqCst);
6959        let response = self
6960            .client
6961            .register_worker_with_definition_fingerprints(
6962                &self.worker_id,
6963                &self.task_queue,
6964                self.workflows.keys().cloned().collect(),
6965                self.activities.keys().cloned().collect(),
6966                self.max_concurrent_workflow_tasks,
6967                self.max_concurrent_activity_tasks,
6968                [
6969                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
6970                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
6971                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
6972                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
6973                    self.cooperative_cancellation_enabled
6974                        .then(|| "cooperative_cancellation".to_string()),
6975                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
6976                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
6977                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
6978                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
6979                ]
6980                .into_iter()
6981                .flatten()
6982                .collect(),
6983                Value::Object(command_contracts),
6984                Some(
6985                    self.workflows
6986                        .iter()
6987                        .filter_map(|(workflow_type, workflow)| {
6988                            workflow
6989                                .definition_fingerprint
6990                                .as_ref()
6991                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
6992                        })
6993                        .collect(),
6994                ),
6995            )
6996            .await?;
6997        if self.cooperative_cancellation_enabled && response.registered {
6998            self.cooperative_registration_confirmed
6999                .store(true, Ordering::SeqCst);
7000        }
7001        Ok(response)
7002    }
7003
7004    /// Run until shutdown or a terminal worker error occurs.
7005    ///
7006    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7007    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7008    /// authentication, protocol, and other non-retryable failures are returned.
7009    pub async fn run(&self) -> Result<()> {
7010        self.run_until(std::future::pending::<()>()).await
7011    }
7012
7013    /// Run until `shutdown` resolves or a terminal worker error occurs.
7014    ///
7015    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7016    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7017    where
7018        F: Future<Output = ()>,
7019    {
7020        let stop = Arc::new(AtomicBool::new(false));
7021        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7022        let worker = self.with_storage_admission(Arc::clone(&stop));
7023        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7024        tokio::pin!(run);
7025        tokio::pin!(shutdown);
7026        tokio::select! {
7027            result = &mut run => result,
7028            _ = &mut shutdown => {
7029                stop.store(true, Ordering::SeqCst);
7030                run.await
7031            }
7032        }
7033    }
7034
7035    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7036        let mut worker = self.clone();
7037        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7038            policy: self.retry_policy,
7039            stop,
7040        });
7041        worker
7042    }
7043
7044    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7045        let registration = self.register().await?;
7046        if !registration.registered {
7047            return Err(Error::WorkerLoop(format!(
7048                "worker registration for {:?} was not accepted",
7049                self.worker_id
7050            )));
7051        }
7052        let registered_worker_id = registration.worker_id.clone();
7053        let primary = self.run_registered_until(stop, registration).await;
7054        self.cooperative_registration_confirmed
7055            .store(false, Ordering::SeqCst);
7056        let deregistration = self
7057            .client
7058            .deregister_worker_registration(&registered_worker_id)
7059            .await;
7060
7061        match (primary, deregistration) {
7062            (Ok(()), Ok(_)) => Ok(()),
7063            (Ok(()), Err(deregistration)) => Err(deregistration),
7064            (Err(primary), Ok(_)) => Err(primary),
7065            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7066                primary: Box::new(primary),
7067                deregistration: Box::new(deregistration),
7068            }),
7069        }
7070    }
7071
7072    async fn run_registered_until(
7073        &self,
7074        stop: Arc<AtomicBool>,
7075        registration: RegisterWorkerResponse,
7076    ) -> Result<()> {
7077        let heartbeat_interval = Duration::from_secs(
7078            registration
7079                .heartbeat_interval_seconds
7080                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7081        );
7082        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7083        // from the completion of the preceding attempt, including its bounded
7084        // retries. A fixed-epoch interval can leave an already-due tick queued
7085        // while an acknowledgement is slow, producing a catch-up heartbeat as
7086        // soon as that request completes.
7087        let heartbeat = tokio::time::sleep(Duration::ZERO);
7088        tokio::pin!(heartbeat);
7089        // Poll responses may already have leased server-side work by the time
7090        // they become ready, so each poller owns its responses through
7091        // completion or failure instead of racing raw polls in this select.
7092        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7093            let worker = self.clone();
7094            let stop = Arc::clone(&stop);
7095            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7096        });
7097        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7098            let worker = self.clone();
7099            let stop = Arc::clone(&stop);
7100            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7101        });
7102        let mut query_poller = (!self.queries.is_empty()).then(|| {
7103            let worker = self.clone();
7104            let stop = Arc::clone(&stop);
7105            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7106        });
7107
7108        loop {
7109            tokio::select! {
7110                _ = wait_for_worker_stop(&stop) => {
7111                    stop.store(true, Ordering::SeqCst);
7112                    break;
7113                }
7114                _ = &mut heartbeat => {
7115                    let result = self.retry_worker_operation(|| {
7116                        self.client.heartbeat_worker(
7117                            &self.worker_id,
7118                            self.max_concurrent_workflow_tasks,
7119                            self.max_concurrent_activity_tasks,
7120                        )
7121                    }).await;
7122                    heartbeat
7123                        .as_mut()
7124                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7125                    match result {
7126                        Ok(acknowledgement) => {
7127                            if let Some(observer) = &self.heartbeat_observer {
7128                                observer(&WorkerHeartbeatObservation {
7129                                    worker_id: self.worker_id.clone(),
7130                                    task_queue: self.task_queue.clone(),
7131                                    acknowledged_at_unix_millis: SystemTime::now()
7132                                        .duration_since(UNIX_EPOCH)
7133                                        .unwrap_or_default()
7134                                        .as_millis()
7135                                        .min(u64::MAX as u128)
7136                                        as u64,
7137                                    acknowledgement,
7138                                });
7139                            }
7140                        }
7141                        Err(error) => {
7142                            stop.store(true, Ordering::SeqCst);
7143                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7144                            return Err(error);
7145                        }
7146                    }
7147                }
7148                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7149                    workflow_poller = None;
7150                    let stopped_by_server = stop.load(Ordering::SeqCst);
7151                    stop.store(true, Ordering::SeqCst);
7152                    let poller_result = optional_poller_result("workflow", result);
7153                    let join_result =
7154                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7155                    poller_result?;
7156                    join_result?;
7157                    if stopped_by_server {
7158                        return Ok(());
7159                    }
7160                    return Err(Error::WorkerLoop(
7161                        "workflow poller stopped unexpectedly".to_string(),
7162                    ));
7163                }
7164                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7165                    activity_poller = None;
7166                    let stopped_by_server = stop.load(Ordering::SeqCst);
7167                    stop.store(true, Ordering::SeqCst);
7168                    let poller_result = optional_poller_result("activity", result);
7169                    let join_result =
7170                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7171                    poller_result?;
7172                    join_result?;
7173                    if stopped_by_server {
7174                        return Ok(());
7175                    }
7176                    return Err(Error::WorkerLoop(
7177                        "activity poller stopped unexpectedly".to_string(),
7178                    ));
7179                }
7180                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7181                    query_poller = None;
7182                    let stopped_by_server = stop.load(Ordering::SeqCst);
7183                    stop.store(true, Ordering::SeqCst);
7184                    let poller_result = optional_poller_result("query", result);
7185                    let join_result =
7186                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7187                    poller_result?;
7188                    join_result?;
7189                    if stopped_by_server {
7190                        return Ok(());
7191                    }
7192                    return Err(Error::WorkerLoop(
7193                        "query poller stopped unexpectedly".to_string(),
7194                    ));
7195                }
7196            }
7197        }
7198
7199        join_pollers(
7200            workflow_poller.take(),
7201            activity_poller.take(),
7202            query_poller.take(),
7203        )
7204        .await
7205    }
7206
7207    /// Poll and settle at most one task from each enabled task family.
7208    ///
7209    /// A workflow may reach its server-enforced run deadline while this worker
7210    /// holds a task. When the completion endpoint authoritatively rejects that
7211    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
7212    /// terminal `run_status=failed`, the workflow tick is considered settled:
7213    /// the late command was not recorded and cannot replace the terminal run.
7214    /// Every other completion rejection remains an error. This worker-level
7215    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
7216    /// only bounds how long a client waits for a result.
7217    ///
7218    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
7219    /// the original [`Error::Http`] status and response body.
7220    pub async fn run_once(&self) -> Result<usize> {
7221        if self.cooperative_cancellation_enabled
7222            && !self
7223                .cooperative_registration_confirmed
7224                .load(Ordering::SeqCst)
7225        {
7226            return Err(Error::CooperativeCancellationUnavailable(
7227                "register this cooperative worker before polling tasks".into(),
7228            ));
7229        }
7230        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
7231        let mut handled = 0;
7232        match worker.poll_workflow_once().await? {
7233            ManagedPollOutcome::Handled => handled += 1,
7234            ManagedPollOutcome::Stop => return Ok(handled),
7235            ManagedPollOutcome::Idle => {}
7236        }
7237        match worker.poll_activity_once().await? {
7238            ManagedPollOutcome::Handled => handled += 1,
7239            ManagedPollOutcome::Stop => return Ok(handled),
7240            ManagedPollOutcome::Idle => {}
7241        }
7242        if !self.queries.is_empty() {
7243            match worker.poll_query_once().await? {
7244                ManagedPollOutcome::Handled => handled += 1,
7245                ManagedPollOutcome::Stop => return Ok(handled),
7246                ManagedPollOutcome::Idle => {}
7247            }
7248        }
7249        Ok(handled)
7250    }
7251
7252    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
7253        if self.cooperative_cancellation_enabled {
7254            return self.poll_cooperative_workflow_once().await;
7255        }
7256        let poll_request_id = unique_request_id("rust-workflow-poll");
7257        let response = self
7258            .retry_worker_operation(|| {
7259                self.client.poll_workflow_task_response_with_request_id(
7260                    &self.worker_id,
7261                    &self.task_queue,
7262                    self.poll_timeout,
7263                    &poll_request_id,
7264                    0,
7265                )
7266            })
7267            .await;
7268        let Some(response) = self.settle_worker_poll_response(response).await? else {
7269            return Ok(ManagedPollOutcome::Idle);
7270        };
7271        if response.outcome().should_stop() {
7272            return Ok(ManagedPollOutcome::Stop);
7273        }
7274        let memo_updates_supported =
7275            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
7276        let Some(task) = response.task else {
7277            return Ok(ManagedPollOutcome::Idle);
7278        };
7279
7280        let task_id = task.task_id.clone();
7281        let attempt = task.workflow_task_attempt;
7282        let run_id = task.run_id.clone();
7283        let lease_owner = task
7284            .lease_owner
7285            .clone()
7286            .unwrap_or_else(|| self.worker_id.clone());
7287
7288        self.settle_workflow_task_decision(
7289            &task_id,
7290            &lease_owner,
7291            attempt,
7292            run_id.as_deref(),
7293            self.execute_workflow_task_decision(task),
7294            memo_updates_supported,
7295        )
7296        .await
7297    }
7298
7299    async fn settle_workflow_task_decision(
7300        &self,
7301        task_id: &str,
7302        lease_owner: &str,
7303        attempt: u64,
7304        run_id: Option<&str>,
7305        decision: Result<WorkflowTaskDecision>,
7306        memo_updates_supported: bool,
7307    ) -> Result<ManagedPollOutcome> {
7308        match decision {
7309            Ok(decision)
7310                if decision.cancellation_delivery.is_some()
7311                    || decision.cancellation_scope_delivery.is_some()
7312                    || decision.cancellation_scope_opening.is_some() =>
7313            {
7314                return Err(Error::CooperativeCancellationUnavailable(
7315                    "worker cancellation delivery has not been negotiated".into(),
7316                ));
7317            }
7318            Ok(decision)
7319                if commands_use_workflow_memo_updates(&decision.commands)
7320                    && !memo_updates_supported =>
7321            {
7322                self.client
7323                    .fail_workflow_task(
7324                        task_id,
7325                        lease_owner,
7326                        attempt,
7327                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
7328                    )
7329                    .await?;
7330            }
7331            Ok(decision) if decision.commands.is_empty() => {
7332                // A replay can consume a recorded pending durable command
7333                // without producing a new command. The standalone protocol
7334                // acknowledges that state through the typed waiting outcome;
7335                // an empty completion is rejected by servers that require at
7336                // least one executable command.
7337                self.client
7338                    .fail_workflow_task_with_type(
7339                        task_id,
7340                        lease_owner,
7341                        attempt,
7342                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
7343                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
7344                    )
7345                    .await?;
7346            }
7347            Ok(decision) => {
7348                let completion = self
7349                    .client
7350                    .complete_workflow_task_with_message_streams(
7351                        task_id,
7352                        lease_owner,
7353                        attempt,
7354                        decision.commands,
7355                        decision.message_stream_cursors,
7356                        decision.message_stream_waits,
7357                    )
7358                    .await;
7359                if let Err(error) = completion {
7360                    if !workflow_task_completion_is_terminal_timeout(
7361                        &error, task_id, attempt, run_id,
7362                    ) {
7363                        return Err(error);
7364                    }
7365                }
7366            }
7367            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
7368            Err(error) => {
7369                self.client
7370                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
7371                    .await?;
7372            }
7373        }
7374
7375        Ok(ManagedPollOutcome::Handled)
7376    }
7377
7378    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7379        while !stop.load(Ordering::SeqCst) {
7380            if self.poll_workflow_once().await? == ManagedPollOutcome::Stop {
7381                stop.store(true, Ordering::SeqCst);
7382                break;
7383            }
7384        }
7385
7386        Ok(())
7387    }
7388
7389    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
7390        if self.cooperative_cancellation_enabled {
7391            return self.poll_cooperative_activity_once().await;
7392        }
7393        let poll_request_id = unique_request_id("rust-activity-poll");
7394        let response = self
7395            .retry_worker_operation(|| {
7396                self.client.poll_activity_task_response_with_request_id(
7397                    &self.worker_id,
7398                    &self.task_queue,
7399                    self.poll_timeout,
7400                    &poll_request_id,
7401                    0,
7402                )
7403            })
7404            .await;
7405        let Some(response) = self.settle_worker_poll_response(response).await? else {
7406            return Ok(ManagedPollOutcome::Idle);
7407        };
7408        if response.outcome().should_stop() {
7409            return Ok(ManagedPollOutcome::Stop);
7410        }
7411        let Some(task) = response.task else {
7412            return Ok(ManagedPollOutcome::Idle);
7413        };
7414
7415        let task_id = task.task_id.clone();
7416        let attempt_id = task
7417            .activity_attempt_id
7418            .clone()
7419            .or(task.attempt_id.clone())
7420            .unwrap_or_default();
7421        let lease_owner = task
7422            .lease_owner
7423            .clone()
7424            .unwrap_or_else(|| self.worker_id.clone());
7425        let codec = task.payload_codec.clone();
7426        let result = self.execute_activity_task(task).await;
7427        match result {
7428            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
7429            Ok(value) => {
7430                let completion = self
7431                    .client
7432                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
7433                    .await;
7434                if let Err(error) = completion {
7435                    if !activity_task_rejection_is_final(&error) {
7436                        return Err(error);
7437                    }
7438                }
7439            }
7440            Err(error) => {
7441                let failure = self
7442                    .client
7443                    .fail_activity_task(
7444                        &task_id,
7445                        &attempt_id,
7446                        &lease_owner,
7447                        error.to_string(),
7448                        false,
7449                    )
7450                    .await;
7451                if let Err(error) = failure {
7452                    if !activity_task_rejection_is_final(&error) {
7453                        return Err(error);
7454                    }
7455                }
7456            }
7457        }
7458
7459        Ok(ManagedPollOutcome::Handled)
7460    }
7461
7462    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7463        // Each lane retains its leased response through callback settlement.
7464        // A bounded independent activity must not occupy the cleanup lane too.
7465        // Preserve the existing serial loop for default protocol 1.19 workers.
7466        let lane_count = if self.cooperative_cancellation_enabled {
7467            self.max_concurrent_activity_tasks
7468        } else {
7469            1
7470        };
7471        let mut lanes = FuturesUnordered::new();
7472        for _ in 0..lane_count {
7473            let worker = self.clone();
7474            let stop = Arc::clone(&stop);
7475            lanes.push(async move {
7476                while !stop.load(Ordering::SeqCst) {
7477                    match worker.poll_activity_once().await {
7478                        Ok(ManagedPollOutcome::Stop) => {
7479                            stop.store(true, Ordering::SeqCst);
7480                            break;
7481                        }
7482                        Err(error) => {
7483                            stop.store(true, Ordering::SeqCst);
7484                            return Err(error);
7485                        }
7486                        _ => {}
7487                    }
7488                }
7489                Ok(())
7490            });
7491        }
7492        // Join every lane before deregistration, including after one fails.
7493        let mut first_error = None;
7494        while let Some(result) = lanes.next().await {
7495            if let Err(error) = result {
7496                first_error.get_or_insert(error);
7497            }
7498        }
7499        first_error.map_or(Ok(()), Err)
7500    }
7501
7502    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
7503        let poll_request_id = unique_request_id("rust-query-poll");
7504        let response = self
7505            .retry_worker_operation(|| {
7506                self.client.poll_query_task_response_with_request_id(
7507                    &self.worker_id,
7508                    &self.task_queue,
7509                    self.poll_timeout,
7510                    &poll_request_id,
7511                    0,
7512                )
7513            })
7514            .await;
7515        let Some(response) = self.settle_worker_poll_response(response).await? else {
7516            return Ok(ManagedPollOutcome::Idle);
7517        };
7518        if response.outcome().should_stop() {
7519            return Ok(ManagedPollOutcome::Stop);
7520        }
7521        let Some(task) = response.task else {
7522            return Ok(ManagedPollOutcome::Idle);
7523        };
7524
7525        let query_task_id = task.query_task_id.clone();
7526        let attempt = task.query_task_attempt;
7527        let lease_owner = task
7528            .lease_owner
7529            .clone()
7530            .unwrap_or_else(|| self.worker_id.clone());
7531        let codec = task.payload_codec.clone();
7532
7533        match self.execute_query_task(task).await {
7534            Ok(value) => {
7535                let result_envelope = match encode_typed_envelope(&value, &codec) {
7536                    Ok(result_envelope) => result_envelope,
7537                    Err(error) => {
7538                        let failure = self
7539                            .client
7540                            .fail_query_task(
7541                                &query_task_id,
7542                                &lease_owner,
7543                                attempt,
7544                                error.to_string(),
7545                                "query_result_encode_failed",
7546                                "QueryResultEncodeFailed",
7547                            )
7548                            .await;
7549                        if let Err(error) = failure {
7550                            if !query_task_rejection_is_final(&error) {
7551                                return Err(error);
7552                            }
7553                        }
7554                        return Ok(ManagedPollOutcome::Handled);
7555                    }
7556                };
7557
7558                if let Err(error) = self
7559                    .client
7560                    .complete_query_task_with_envelope(
7561                        &query_task_id,
7562                        &lease_owner,
7563                        attempt,
7564                        value.clone().into_json()?,
7565                        result_envelope,
7566                    )
7567                    .await
7568                {
7569                    if !query_task_rejection_is_final(&error) {
7570                        return Err(error);
7571                    }
7572                }
7573            }
7574            Err(failure) => {
7575                let result = self
7576                    .client
7577                    .fail_query_task(
7578                        &query_task_id,
7579                        &lease_owner,
7580                        attempt,
7581                        failure.message,
7582                        failure.reason,
7583                        failure.failure_type,
7584                    )
7585                    .await;
7586                if let Err(error) = result {
7587                    if !query_task_rejection_is_final(&error) {
7588                        return Err(error);
7589                    }
7590                }
7591            }
7592        }
7593
7594        Ok(ManagedPollOutcome::Handled)
7595    }
7596
7597    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7598        while !stop.load(Ordering::SeqCst) {
7599            if self.poll_query_once().await? == ManagedPollOutcome::Stop {
7600                stop.store(true, Ordering::SeqCst);
7601                break;
7602            }
7603        }
7604
7605        Ok(())
7606    }
7607
7608    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<T>
7609    where
7610        F: FnMut() -> Fut,
7611        Fut: Future<Output = Result<T>>,
7612    {
7613        let mut retries = 0;
7614
7615        loop {
7616            match operation().await {
7617                Err(error)
7618                    if worker_operation_is_retryable(&error)
7619                        && retries < self.retry_policy.max_retries =>
7620                {
7621                    retries += 1;
7622                    tokio::time::sleep(worker_retry_delay(self.retry_policy, retries)).await;
7623                }
7624                result => return result,
7625            }
7626        }
7627    }
7628
7629    async fn settle_worker_poll_response<T>(&self, response: Result<T>) -> Result<Option<T>> {
7630        match response {
7631            Ok(response) => Ok(Some(response)),
7632            Err(error) => {
7633                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
7634                    return Err(error);
7635                };
7636                let minimum_delay = self
7637                    .retry_policy
7638                    .initial_backoff
7639                    .max(Duration::from_millis(1));
7640                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
7641                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
7642                Ok(None)
7643            }
7644        }
7645    }
7646
7647    async fn execute_query_task(
7648        &self,
7649        mut task: QueryTask,
7650    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
7651        validate_query_task_payloads(&task).map_err(|error| {
7652            QueryTaskExecutionFailure::new(
7653                "query_payload_decode_failed",
7654                error.to_string(),
7655                "QueryPayloadDecodeFailed",
7656            )
7657        })?;
7658
7659        if !self.workflows.contains_key(&task.workflow_type) {
7660            return Err(QueryTaskExecutionFailure::new(
7661                "query_workflow_type_not_registered",
7662                format!("no workflow registered for type {:?}", task.workflow_type),
7663                "WorkflowTypeNotRegistered",
7664            ));
7665        }
7666
7667        let Some(handlers) = self.queries.get(&task.workflow_type) else {
7668            return Err(QueryTaskExecutionFailure::new(
7669                "query_handler_unavailable",
7670                format!(
7671                    "query handlers are unavailable for workflow type {:?}",
7672                    task.workflow_type
7673                ),
7674                "QueryHandlerUnavailable",
7675            ));
7676        };
7677        let Some(query) = handlers.get(&task.query_name) else {
7678            return Err(QueryTaskExecutionFailure::new(
7679                "rejected_unknown_query",
7680                format!("unknown query {:?}", task.query_name),
7681                "QueryFailed",
7682            ));
7683        };
7684
7685        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
7686            .map_err(|error| {
7687            QueryTaskExecutionFailure::new(
7688                "query_payload_decode_failed",
7689                format!("cannot decode query arguments: {error}"),
7690                "QueryPayloadDecodeFailed",
7691            )
7692        })?;
7693        let workflow_input_typed =
7694            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
7695                .map_err(|error| {
7696                    QueryTaskExecutionFailure::new(
7697                        "query_workflow_state_unavailable",
7698                        format!("cannot decode workflow start input: {error}"),
7699                        "QueryWorkflowStateUnavailable",
7700                    )
7701                })?;
7702        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
7703            QueryTaskExecutionFailure::new(
7704                "query_workflow_state_unavailable",
7705                format!("cannot project workflow start input: {error}"),
7706                "QueryWorkflowStateUnavailable",
7707            )
7708        })?;
7709        hydrate_query_history_from_export(&mut task).map_err(|error| {
7710            QueryTaskExecutionFailure::new(
7711                "query_workflow_state_unavailable",
7712                format!("cannot restore query history snapshot: {error}"),
7713                "QueryWorkflowStateUnavailable",
7714            )
7715        })?;
7716        enrich_query_history_from_export(&mut task).map_err(|error| {
7717            QueryTaskExecutionFailure::new(
7718                "query_workflow_state_unavailable",
7719                format!("cannot restore compact query history payloads: {error}"),
7720                "QueryWorkflowStateUnavailable",
7721            )
7722        })?;
7723        let signal_events = query_signal_events(&task).map_err(|error| {
7724            QueryTaskExecutionFailure::new(
7725                "query_workflow_state_unavailable",
7726                format!("cannot decode committed workflow signals: {error}"),
7727                "QueryWorkflowStateUnavailable",
7728            )
7729        })?;
7730        let history_events = Arc::new(std::mem::take(&mut task.history_events));
7731        let context = QueryContext {
7732            workflow_id: task.workflow_id,
7733            run_id: task.run_id,
7734            workflow_type: task.workflow_type.clone(),
7735            run_status: task.run_status,
7736            workflow_input,
7737            workflow_input_avro_value: workflow_input_typed.clone(),
7738            history_events: Arc::clone(&history_events),
7739            signal_events: Arc::new(signal_events),
7740        };
7741
7742        let future = match query {
7743            RegisteredQuery::Snapshot(handler) => handler(context, args),
7744            RegisteredQuery::Replayed {
7745                state_type,
7746                handler,
7747            } => {
7748                let workflow = self
7749                    .workflows
7750                    .get(&task.workflow_type)
7751                    .expect("workflow registration was checked above");
7752                if workflow.state_type != Some(*state_type) {
7753                    return Err(QueryTaskExecutionFailure::new(
7754                        "query_workflow_state_unavailable",
7755                        "replayed query state type does not match its workflow registration",
7756                        "QueryWorkflowStateUnavailable",
7757                    ));
7758                }
7759                let replay = workflow.replay.as_ref().ok_or_else(|| {
7760                    QueryTaskExecutionFailure::new(
7761                        "query_workflow_state_unavailable",
7762                        format!(
7763                            "workflow type {:?} is not registered for instance-state replay",
7764                            task.workflow_type
7765                        ),
7766                        "QueryWorkflowStateUnavailable",
7767                    )
7768                })?;
7769                let workflow_state = Arc::new(Mutex::new(
7770                    WorkflowState::new_with_identity(
7771                        history_events.as_ref().clone(),
7772                        context.workflow_id.clone(),
7773                        context.run_id.clone(),
7774                        self.task_queue.clone(),
7775                        task.payload_codec,
7776                        None,
7777                    )
7778                    .map_err(|error| {
7779                        QueryTaskExecutionFailure::new(
7780                            "query_workflow_state_unavailable",
7781                            format!("workflow replay failed before query: {error}"),
7782                            "QueryWorkflowStateUnavailable",
7783                        )
7784                    })?,
7785                ));
7786                let workflow_context = WorkflowContext {
7787                    state: workflow_state,
7788                    cancellation_scope_id: "root".into(),
7789                };
7790                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
7791                let mut cx = TaskContext::from_waker(noop_waker_ref());
7792                let outcome = {
7793                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
7794                        .map_err(|error| {
7795                            QueryTaskExecutionFailure::new(
7796                                "query_workflow_state_unavailable",
7797                                error.to_string(),
7798                                "QueryWorkflowStateUnavailable",
7799                            )
7800                        })?;
7801                    invocation.future.as_mut().poll(&mut cx)
7802                };
7803                match outcome {
7804                    Poll::Ready(Ok(_)) => {
7805                        workflow_context
7806                            .ensure_history_consumed()
7807                            .map_err(|error| {
7808                                QueryTaskExecutionFailure::new(
7809                                    "query_workflow_state_unavailable",
7810                                    format!("workflow replay failed before query: {error}"),
7811                                    "QueryWorkflowStateUnavailable",
7812                                )
7813                            })?;
7814                    }
7815                    Poll::Ready(Err(error)) => {
7816                        return Err(QueryTaskExecutionFailure::new(
7817                            "query_workflow_state_unavailable",
7818                            format!("workflow replay failed before query: {error}"),
7819                            "QueryWorkflowStateUnavailable",
7820                        ));
7821                    }
7822                    Poll::Pending => {
7823                        let commands = workflow_context.take_commands().map_err(|error| {
7824                            QueryTaskExecutionFailure::new(
7825                                "query_workflow_state_unavailable",
7826                                format!("workflow replay failed before query: {error}"),
7827                                "QueryWorkflowStateUnavailable",
7828                            )
7829                        })?;
7830                        if commands.is_empty()
7831                            && !workflow_context
7832                                .matched_recorded_pending()
7833                                .map_err(|error| {
7834                                    QueryTaskExecutionFailure::new(
7835                                        "query_workflow_state_unavailable",
7836                                        format!("workflow replay failed before query: {error}"),
7837                                        "QueryWorkflowStateUnavailable",
7838                                    )
7839                                })?
7840                        {
7841                            return Err(QueryTaskExecutionFailure::new(
7842                                "query_workflow_state_unavailable",
7843                                "workflow replay yielded without a durable command",
7844                                "QueryWorkflowStateUnavailable",
7845                            ));
7846                        }
7847                    }
7848                }
7849                let state = (invocation.snapshot)().map_err(|error| {
7850                    QueryTaskExecutionFailure::new(
7851                        "query_workflow_state_unavailable",
7852                        format!("cannot snapshot replayed workflow state: {error}"),
7853                        "QueryWorkflowStateUnavailable",
7854                    )
7855                })?;
7856                handler(context, state, args).map_err(|message| {
7857                    QueryTaskExecutionFailure::new(
7858                        "query_workflow_state_unavailable",
7859                        message,
7860                        "QueryWorkflowStateUnavailable",
7861                    )
7862                })?
7863            }
7864        };
7865
7866        future.await.map_err(|error| {
7867            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
7868        })
7869    }
7870
7871    #[cfg(test)]
7872    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
7873        Ok(self.execute_workflow_task_decision(task)?.commands)
7874    }
7875
7876    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
7877        self.execute_workflow_task_decision_with_cancellation(task, None)
7878    }
7879
7880    fn execute_workflow_task_decision_with_cancellation(
7881        &self,
7882        task: WorkflowTask,
7883        observation: Option<&CancellationRequest>,
7884    ) -> Result<WorkflowTaskDecision> {
7885        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
7886            && !self.cooperative_cancellation_enabled
7887        {
7888            return Err(Error::CancellationScopeExecutionUnavailable);
7889        }
7890        validate_workflow_task_payloads(&task)?;
7891        cooperative_cancellation::assert_cancellation_scope_replay_supported(
7892            &task.history_events,
7893            self.allow_cancellation_scope_authoring,
7894            self.allow_cancellation_scope_delivery,
7895        )?;
7896        let cancellation_history = if let Some(observation) = observation {
7897            observation.validate_observation()?;
7898            cooperative_cancellation::cancellation_claim(&task)?;
7899            let canonical = CancellationHistory::from_events(
7900                &task.history_events,
7901                task.run_id.as_deref().unwrap_or_default(),
7902                Some(observation),
7903            )?;
7904            if canonical.request_index >= task.history_events.len() {
7905                return Err(Error::InvalidCooperativeCancellation(
7906                    "workflow replay requires the observed canonical request".into(),
7907                ));
7908            }
7909            Some(canonical)
7910        } else {
7911            None
7912        };
7913        if let Some(update_id) = task
7914            .workflow_update_id
7915            .as_deref()
7916            .filter(|update_id| !update_id.is_empty())
7917        {
7918            if self.allow_cancellation_scope_delivery {
7919                return Err(Error::CancellationScopeExecutionUnavailable);
7920            }
7921            CancellationHistory::from_events(
7922                &task.history_events,
7923                task.run_id.as_deref().unwrap_or_default(),
7924                None,
7925            )?;
7926            return self
7927                .execute_update_task(&task, update_id)
7928                .map(WorkflowTaskDecision::without_message_streams);
7929        }
7930
7931        let workflow = self
7932            .workflows
7933            .get(&task.workflow_type)
7934            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
7935        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
7936        let resume_signal = decode_resume_signal(&task)?;
7937        let history_budget = WorkflowHistoryBudget {
7938            event_count: task
7939                .total_history_events
7940                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
7941            size_bytes: task.history_size_bytes,
7942            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
7943            pressure: task.history_budget_pressure.clone(),
7944        };
7945        let workflow_command_identity = task
7946            .workflow_command_id
7947            .clone()
7948            .filter(|identity| !identity.is_empty())
7949            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
7950            .unwrap_or_default();
7951        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
7952            task.history_events,
7953            task.workflow_id,
7954            task.run_id,
7955            self.task_queue.clone(),
7956            task.payload_codec.clone(),
7957            resume_signal,
7958            self.allow_cancellation_scope_authoring,
7959            self.allow_cancellation_scope_delivery,
7960        )?;
7961        workflow_state.history_budget = history_budget;
7962        workflow_state.workflow_command_identity = workflow_command_identity;
7963        if let Some(canonical) = cancellation_history {
7964            workflow_state.cancellation_history = canonical;
7965            workflow_state.cancellation_delivery_enabled = true;
7966        }
7967        if workflow_state.cancellation_history.request.is_none() {
7968            workflow_state.cancel_requested = task.cancel_requested;
7969        }
7970        let state = Arc::new(Mutex::new(workflow_state));
7971        let ctx = WorkflowContext {
7972            state,
7973            cancellation_scope_id: "root".into(),
7974        };
7975        let mut future = (workflow.execute)(ctx.clone(), input);
7976        let mut cx = TaskContext::from_waker(noop_waker_ref());
7977
7978        let outcome = {
7979            let _replay = cancellation_replay_clock::ReplayGuard::enter(&ctx)?;
7980            future.as_mut().poll(&mut cx)
7981        };
7982        let awaiting_canonical_boundary = {
7983            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
7984            state.cancellation_delivery_intent.is_some()
7985                || state.cancellation_scope_opening.is_some()
7986                || state
7987                    .scope_delivery
7988                    .as_ref()
7989                    .is_some_and(|replay| replay.intent.is_some())
7990        };
7991        if awaiting_canonical_boundary {
7992            // A private delivery intent never becomes an application error.
7993            // Even a custom future which ignores a pending durable call cannot
7994            // publish terminal commands before canonical delivery and replay.
7995            if let Poll::Ready(Err(error)) = outcome {
7996                if workflow_task_integrity_error(&error) {
7997                    return Err(error);
7998                }
7999            }
8000            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8001        }
8002
8003        match outcome {
8004            Poll::Ready(Ok(result)) => {
8005                ctx.ensure_history_consumed()?;
8006                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8007                let mut commands = ctx.take_commands()?;
8008                commands.push(json!({
8009                    "type": "complete_workflow",
8010                    "result": result
8011                }));
8012                self.message_stream_decision(&ctx, commands)
8013            }
8014            Poll::Ready(Err(error)) => {
8015                if let Error::ContinueAsNew(request) = error {
8016                    let mut commands = ctx.take_commands()?;
8017                    if let Some(command) = ctx.continue_as_new_command(request)? {
8018                        commands.push(command);
8019                    }
8020                    ctx.ensure_history_consumed()?;
8021                    return self.message_stream_decision(&ctx, commands);
8022                }
8023                if workflow_task_integrity_error(&error) {
8024                    // Replay and protocol failures describe the workflow-task
8025                    // decision itself. Preserve their specific failure reason
8026                    // instead of replacing it with the derivative fact that
8027                    // recorded commands remain unconsumed.
8028                    return Err(error);
8029                }
8030                // A handler error must not hide a committed durable command that
8031                // upgraded workflow code no longer consumes.
8032                ctx.ensure_history_consumed()?;
8033                let mut commands = ctx.take_commands()?;
8034                commands.push(workflow_failure_command(
8035                    &error,
8036                    recorded_activity_failure_boundary(&ctx, &error),
8037                ));
8038                self.message_stream_decision(&ctx, commands)
8039            }
8040            Poll::Pending => {
8041                let commands = ctx.take_commands()?;
8042                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8043                    Err(Error::WorkflowYieldedWithoutCommand)
8044                } else {
8045                    self.message_stream_decision(&ctx, commands)
8046                }
8047            }
8048        }
8049    }
8050
8051    fn message_stream_decision(
8052        &self,
8053        ctx: &WorkflowContext,
8054        commands: Vec<Value>,
8055    ) -> Result<WorkflowTaskDecision> {
8056        if !self.cooperative_cancellation_enabled
8057            && commands.iter().any(|command| {
8058                command["type"] == "schedule_activity"
8059                    && command.get("cancellation_policy").is_some()
8060            })
8061        {
8062            return Err(Error::CooperativeCancellationUnavailable(format!(
8063                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8064                self.worker_id,
8065            )));
8066        }
8067        if !self.cooperative_cancellation_enabled
8068            && commands.iter().any(|command| {
8069                command["type"] == "start_child_workflow"
8070                    && (command["parent_close_policy"] == "request_cancellation"
8071                        || matches!(
8072                            command["cancellation_policy"].as_str(),
8073                            Some("try_cancel" | "wait_cancellation_completed")
8074                        ))
8075            })
8076        {
8077            return Err(Error::CooperativeCancellationUnavailable(format!(
8078                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8079                self.worker_id,
8080            )));
8081        }
8082        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
8083        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8084        let scope_delivery = state
8085            .scope_delivery
8086            .as_ref()
8087            .and_then(|replay| replay.intent.clone());
8088        if scope_delivery
8089            .as_ref()
8090            .is_some_and(|intent| commands.len() != intent.command_count)
8091        {
8092            return Err(invalid_recorded_history(
8093                "cancellation_scope_pending_call_escaped",
8094                scope_delivery.as_ref().unwrap().boundary.sequence,
8095                "commands preceding the pending scoped call",
8096                "commands after suspension",
8097                "workflow cannot publish beyond an uncommitted scope delivery",
8098            ));
8099        }
8100        if let Some(opening) = &state.cancellation_scope_opening {
8101            if commands.len() != opening.command_count {
8102                return Err(invalid_recorded_history(
8103                    "cancellation_scope_pending_call_escaped",
8104                    opening.sequence,
8105                    "commands before original scope opening",
8106                    "commands after suspended opening",
8107                    "workflow cannot publish beyond an uncommitted scope opening",
8108                ));
8109            }
8110        }
8111        if state.cancellation_delivery_intent.is_some()
8112            && commands.len() != state.cancellation_delivery_command_count
8113        {
8114            return Err(invalid_recorded_history(
8115                "cooperative_cancellation_pending_call_escaped",
8116                state
8117                    .cancellation_delivery_intent
8118                    .as_ref()
8119                    .expect("pending delivery")
8120                    .sequence,
8121                "only commands preceding the pending cancellation call",
8122                "commands authored after a suspended call",
8123                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
8124            ));
8125        }
8126        Ok(WorkflowTaskDecision {
8127            commands,
8128            message_stream_cursors,
8129            message_stream_waits,
8130            cancellation_delivery: state.cancellation_delivery_intent.clone(),
8131            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
8132            cancellation_scope_delivery: scope_delivery,
8133        })
8134    }
8135
8136    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
8137        if !self.workflows.contains_key(&task.workflow_type) {
8138            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
8139        }
8140
8141        let accepted = task.history_events.iter().rev().find_map(|event| {
8142            (event.event_type == "UpdateAccepted"
8143                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
8144            .then_some(&event.payload)
8145        });
8146        let update_name = accepted
8147            .and_then(|payload| payload.get("update_name"))
8148            .and_then(Value::as_str)
8149            .or(task.update_name.as_deref())
8150            .unwrap_or_default();
8151        let Some(handler) = self
8152            .updates
8153            .get(&task.workflow_type)
8154            .and_then(|handlers| handlers.get(update_name))
8155        else {
8156            return Ok(vec![json!({
8157                "type": "fail_update",
8158                "update_id": update_id,
8159                "message": format!(
8160                    "no update handler is registered for {}.{update_name}",
8161                    task.workflow_type
8162                ),
8163                "exception_type": "UnknownUpdate",
8164                "non_retryable": true,
8165            })]);
8166        };
8167        let arguments = accepted
8168            .and_then(|payload| payload.get("arguments"))
8169            .or(task.arguments.as_ref());
8170        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
8171        let context = QueryContext {
8172            workflow_id: task.workflow_id.clone(),
8173            run_id: task.run_id.clone(),
8174            workflow_type: task.workflow_type.clone(),
8175            run_status: Some("running".to_string()),
8176            workflow_input: Value::Null,
8177            workflow_input_avro_value: AvroValue::Null,
8178            history_events: Arc::new(task.history_events.clone()),
8179            signal_events: Arc::new(Vec::new()),
8180        };
8181        let mut future = handler(context, arguments);
8182        let mut cx = TaskContext::from_waker(noop_waker_ref());
8183
8184        match future.as_mut().poll(&mut cx) {
8185            Poll::Ready(Ok(result)) => Ok(vec![json!({
8186                "type": "complete_update",
8187                "update_id": update_id,
8188                "result": encode_typed_envelope(&result, &task.payload_codec)?,
8189            })]),
8190            Poll::Ready(Err(error)) => Ok(vec![json!({
8191                "type": "fail_update",
8192                "update_id": update_id,
8193                "message": error.to_string(),
8194                "exception_type": "UpdateFailed",
8195                "non_retryable": true,
8196            })]),
8197            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
8198        }
8199    }
8200
8201    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
8202        validate_activity_task_payloads(&task)?;
8203
8204        let handler = self
8205            .activities
8206            .get(&task.activity_type)
8207            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
8208        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8209        let attempt_id = task
8210            .activity_attempt_id
8211            .clone()
8212            .or(task.attempt_id.clone())
8213            .unwrap_or_default();
8214        let lease_owner = task
8215            .lease_owner
8216            .clone()
8217            .unwrap_or_else(|| self.worker_id.clone());
8218        let ctx = ActivityContext {
8219            client: self.client.clone(),
8220            task_id: task.task_id,
8221            activity_attempt_id: attempt_id,
8222            lease_owner,
8223            activity_type: task.activity_type,
8224            attempt_number: task.attempt_number,
8225            task_queue: self.task_queue.clone(),
8226            worker_id: self.worker_id.clone(),
8227            claim_guard: None,
8228        };
8229
8230        handler(ctx, args).await
8231    }
8232}
8233
8234fn poller_result(
8235    kind: &str,
8236    result: std::result::Result<Result<()>, tokio::task::JoinError>,
8237) -> Result<()> {
8238    match result {
8239        Ok(result) => result,
8240        Err(error) => Err(Error::WorkerLoop(format!(
8241            "{kind} poller join error: {error}"
8242        ))),
8243    }
8244}
8245
8246fn optional_poller_result(
8247    kind: &str,
8248    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
8249) -> Result<()> {
8250    match result {
8251        Some(result) => poller_result(kind, result),
8252        None => Ok(()),
8253    }
8254}
8255
8256async fn join_pollers(
8257    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8258    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8259    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8260) -> Result<()> {
8261    let mut first_error = None;
8262
8263    if let Some(handle) = workflow_poller {
8264        if let Err(error) = poller_result("workflow", handle.await) {
8265            first_error.get_or_insert(error);
8266        }
8267    }
8268
8269    if let Some(handle) = activity_poller {
8270        if let Err(error) = poller_result("activity", handle.await) {
8271            first_error.get_or_insert(error);
8272        }
8273    }
8274
8275    if let Some(handle) = query_poller {
8276        if let Err(error) = poller_result("query", handle.await) {
8277            first_error.get_or_insert(error);
8278        }
8279    }
8280
8281    if let Some(error) = first_error {
8282        Err(error)
8283    } else {
8284        Ok(())
8285    }
8286}
8287
8288fn default_worker_id() -> String {
8289    let millis = SystemTime::now()
8290        .duration_since(UNIX_EPOCH)
8291        .unwrap_or_default()
8292        .as_millis();
8293    format!("rust-worker-{}-{millis}", std::process::id())
8294}
8295
8296fn percent_encode_path_segment(segment: &str) -> String {
8297    const HEX: &[u8; 16] = b"0123456789ABCDEF";
8298    let mut encoded = String::with_capacity(segment.len());
8299
8300    for byte in segment.bytes() {
8301        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
8302            encoded.push(char::from(byte));
8303        } else {
8304            encoded.push('%');
8305            encoded.push(char::from(HEX[(byte >> 4) as usize]));
8306            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
8307        }
8308    }
8309
8310    encoded
8311}
8312
8313fn unique_request_id(prefix: &str) -> String {
8314    let nanos = SystemTime::now()
8315        .duration_since(UNIX_EPOCH)
8316        .unwrap_or_default()
8317        .as_nanos();
8318    format!("{prefix}-{}-{nanos}", std::process::id())
8319}
8320
8321#[derive(Debug)]
8322struct QueryTaskExecutionFailure {
8323    reason: String,
8324    message: String,
8325    failure_type: String,
8326}
8327
8328impl QueryTaskExecutionFailure {
8329    fn new(
8330        reason: impl Into<String>,
8331        message: impl Into<String>,
8332        failure_type: impl Into<String>,
8333    ) -> Self {
8334        Self {
8335            reason: reason.into(),
8336            message: message.into(),
8337            failure_type: failure_type.into(),
8338        }
8339    }
8340}
8341
8342/// Typed local state owned by one deterministic workflow invocation.
8343///
8344/// Use [`WorkflowInstance::update`] for the same state transitions during
8345/// ordinary execution and replay. A replayed query receives a detached
8346/// immutable `Arc<S>` rather than this mutation-capable handle.
8347#[derive(Clone, Debug)]
8348pub struct WorkflowInstance<S> {
8349    state: Arc<Mutex<S>>,
8350}
8351
8352impl<S> WorkflowInstance<S> {
8353    fn new(state: S) -> Self {
8354        Self {
8355            state: Arc::new(Mutex::new(state)),
8356        }
8357    }
8358
8359    /// Read the current workflow-instance state without changing it.
8360    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
8361        let state = self
8362            .state
8363            .lock()
8364            .map_err(|_| Error::WorkflowStatePoisoned)?;
8365        Ok(reader(&state))
8366    }
8367
8368    /// Apply one deterministic workflow-instance state transition.
8369    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
8370        let mut state = self
8371            .state
8372            .lock()
8373            .map_err(|_| Error::WorkflowStatePoisoned)?;
8374        Ok(transition(&mut state))
8375    }
8376}
8377
8378impl<S: Clone> WorkflowInstance<S> {
8379    fn snapshot(&self) -> Result<S> {
8380        self.read(Clone::clone)
8381    }
8382}
8383
8384#[derive(Clone, Debug, PartialEq)]
8385pub struct MessageStreamMessage {
8386    pub stream_name: String,
8387    pub message_id: String,
8388    pub position: u64,
8389    pub arguments: Vec<AvroValue>,
8390}
8391
8392#[derive(Clone, Debug)]
8393pub struct MessageStream {
8394    ctx: WorkflowContext,
8395    name: String,
8396}
8397
8398impl MessageStream {
8399    /// Wait for one message, then return a bounded currently-available batch.
8400    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
8401        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
8402            return Err(Error::Codec(format!(
8403                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
8404            )));
8405        }
8406        loop {
8407            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
8408                return Ok(batch);
8409            }
8410
8411            self.ctx.record_message_stream_wait(&self.name)?;
8412            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
8413            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
8414            self.ctx.buffer_message_stream_delivery(arguments)?;
8415            if let Some(sequence) = replay_wait_sequence {
8416                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
8417            }
8418        }
8419    }
8420
8421    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
8422        self.receive(1)
8423            .await?
8424            .into_iter()
8425            .next()
8426            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
8427    }
8428}
8429
8430#[derive(Clone, Debug)]
8431pub struct WorkflowContext {
8432    state: Arc<Mutex<WorkflowState>>,
8433    cancellation_scope_id: String,
8434}
8435
8436fn valid_memo_key(key: &str) -> bool {
8437    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
8438
8439    !key.is_empty()
8440        && key.len() <= 64
8441        && (numeric_candidate.is_empty()
8442            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
8443        && key
8444            .bytes()
8445            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
8446}
8447
8448fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
8449    BASE64
8450        .decode(encode_avro_value(value)?.blob)
8451        .map(|bytes| bytes.len())
8452        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
8453}
8454
8455fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
8456    let AvroValue::Map(entries) = value else {
8457        return Err(Error::InvalidMemoUpdate(
8458            "entries must serialize to an Avro string-keyed map".to_string(),
8459        ));
8460    };
8461    if require_entries && entries.is_empty() {
8462        return Err(Error::InvalidMemoUpdate(
8463            "at least one entry is required".to_string(),
8464        ));
8465    }
8466    if entries.len() > MAX_MEMO_ENTRIES {
8467        return Err(Error::InvalidMemoUpdate(format!(
8468            "at most {MAX_MEMO_ENTRIES} entries are allowed"
8469        )));
8470    }
8471
8472    for (key, value) in &entries {
8473        if !valid_memo_key(&key) {
8474            return Err(Error::InvalidMemoUpdate(
8475                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
8476            ));
8477        }
8478        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
8479            return Err(Error::InvalidMemoUpdate(format!(
8480                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
8481            )));
8482        }
8483    }
8484
8485    let value = AvroValue::Map(entries);
8486    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
8487        return Err(Error::InvalidMemoUpdate(format!(
8488            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
8489        )));
8490    }
8491    Ok(value)
8492}
8493
8494fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
8495    let object = envelope.as_object().ok_or_else(|| {
8496        Error::InvalidMemoUpdate(
8497            "history field must use the public {codec, blob} payload envelope".to_string(),
8498        )
8499    })?;
8500    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
8501        return Err(Error::InvalidMemoUpdate(
8502            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
8503        ));
8504    }
8505
8506    canonical_memo_entries(
8507        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
8508        require_entries,
8509    )
8510}
8511
8512impl WorkflowContext {
8513    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
8514        let name = name.into();
8515        if name.is_empty()
8516            || name.len() > 128
8517            || !name.bytes().all(|byte| {
8518                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
8519            })
8520        {
8521            return Err(Error::Codec(
8522                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
8523                    .to_string(),
8524            ));
8525        }
8526        Ok(MessageStream {
8527            ctx: self.clone(),
8528            name,
8529        })
8530    }
8531
8532    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
8533        let mut state = self
8534            .state
8535            .lock()
8536            .map_err(|_| Error::WorkflowStatePoisoned)?;
8537        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
8538        state
8539            .message_stream_waits
8540            .insert(name.to_string(), position);
8541        Ok(())
8542    }
8543
8544    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
8545        let mut state = self
8546            .state
8547            .lock()
8548            .map_err(|_| Error::WorkflowStatePoisoned)?;
8549        let cursor = state
8550            .message_stream_cursors
8551            .get(&message.stream_name)
8552            .copied()
8553            .unwrap_or(0);
8554        if message.position <= cursor {
8555            return Ok(());
8556        }
8557        let pending = state
8558            .message_stream_messages
8559            .entry(message.stream_name.clone())
8560            .or_default();
8561        if pending.iter().any(|candidate| {
8562            candidate.position == message.position || candidate.message_id == message.message_id
8563        }) {
8564            return Ok(());
8565        }
8566        pending.push(message);
8567        pending.sort_by_key(|candidate| candidate.position);
8568        Ok(())
8569    }
8570
8571    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
8572        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
8573            match delivery {
8574                MessageStreamDelivery::Message(message) => {
8575                    let stream_name = message.stream_name.clone();
8576                    self.buffer_message_stream(message)?;
8577                    return Ok(Some(stream_name));
8578                }
8579                MessageStreamDelivery::Cursor {
8580                    stream_name,
8581                    through_position,
8582                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
8583            }
8584        }
8585        Ok(None)
8586    }
8587
8588    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
8589        let state = self
8590            .state
8591            .lock()
8592            .map_err(|_| Error::WorkflowStatePoisoned)?;
8593        Ok(match state.recorded_commands.get(state.command_cursor) {
8594            Some(RecordedCommand::SignalWait {
8595                sequence,
8596                signal_name,
8597                ..
8598            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
8599            _ => None,
8600        })
8601    }
8602
8603    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
8604        let (history, payload_codec) = {
8605            let state = self
8606                .state
8607                .lock()
8608                .map_err(|_| Error::WorkflowStatePoisoned)?;
8609            (
8610                Arc::clone(&state.history_events),
8611                state.payload_codec.clone(),
8612            )
8613        };
8614
8615        let Some(opened_index) = history.iter().position(|event| {
8616            event.event_type == "SignalWaitOpened"
8617                && durable_event_sequence(event) == Some(wait_sequence)
8618                && event.payload.get("signal_name").and_then(Value::as_str)
8619                    == Some(MESSAGE_STREAM_SIGNAL)
8620        }) else {
8621            return Ok(());
8622        };
8623        let boundary_index = history
8624            .iter()
8625            .enumerate()
8626            .skip(opened_index + 1)
8627            .find_map(|(index, event)| {
8628                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
8629                    && is_authored_command_open_event(event))
8630                .then_some(index)
8631            })
8632            .unwrap_or(history.len());
8633
8634        for event in history[opened_index + 1..boundary_index]
8635            .iter()
8636            .filter(|event| {
8637                event.event_type == "SignalReceived"
8638                    && event.payload.get("signal_name").and_then(Value::as_str)
8639                        == Some(MESSAGE_STREAM_SIGNAL)
8640            })
8641        {
8642            let arguments = decode_signal_event_arguments(event, &payload_codec)?
8643                .into_iter()
8644                .map(AvroValue::into_json)
8645                .collect::<Result<Vec<_>>>()?;
8646            self.buffer_message_stream_delivery(arguments)?;
8647        }
8648        Ok(())
8649    }
8650
8651    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
8652        let mut state = self
8653            .state
8654            .lock()
8655            .map_err(|_| Error::WorkflowStatePoisoned)?;
8656        let cursor = state
8657            .message_stream_cursors
8658            .entry(name.to_string())
8659            .or_default();
8660        *cursor = (*cursor).max(through_position);
8661        if let Some(pending) = state.message_stream_messages.get_mut(name) {
8662            pending.retain(|message| message.position > through_position);
8663        }
8664        Ok(())
8665    }
8666
8667    fn take_message_stream_batch(
8668        &self,
8669        name: &str,
8670        max_items: usize,
8671    ) -> Result<Option<Vec<MessageStreamMessage>>> {
8672        let mut state = self
8673            .state
8674            .lock()
8675            .map_err(|_| Error::WorkflowStatePoisoned)?;
8676        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
8677        let pending = state
8678            .message_stream_messages
8679            .entry(name.to_string())
8680            .or_default();
8681        let count = contiguous_message_stream_count(pending, cursor, max_items);
8682        if count == 0 {
8683            return Ok(None);
8684        }
8685        let batch = pending.drain(..count).collect::<Vec<_>>();
8686        let position = batch.last().map(|message| message.position).unwrap_or(0);
8687        state
8688            .message_stream_cursors
8689            .insert(name.to_string(), position);
8690        state.message_stream_waits.remove(name);
8691        Ok(Some(batch))
8692    }
8693
8694    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
8695        let state = self
8696            .state
8697            .lock()
8698            .map_err(|_| Error::WorkflowStatePoisoned)?;
8699        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
8700        cursors.sort_by_key(|(name, _)| *name);
8701        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
8702        waits.sort_by_key(|(name, _)| *name);
8703        Ok((
8704            cursors
8705                .into_iter()
8706                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
8707                .collect(),
8708            waits
8709                .into_iter()
8710                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
8711                .collect(),
8712        ))
8713    }
8714    /// Identity of the parent workflow currently being replayed.
8715    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
8716        let state = self
8717            .state
8718            .lock()
8719            .map_err(|_| Error::WorkflowStatePoisoned)?;
8720        Ok(WorkflowIdentity {
8721            workflow_id: state.workflow_id.clone(),
8722            run_id: state.run_id.clone(),
8723        })
8724    }
8725
8726    /// Return the server-published history budget for this workflow task.
8727    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
8728        let state = self
8729            .state
8730            .lock()
8731            .map_err(|_| Error::WorkflowStatePoisoned)?;
8732        Ok(state.history_budget.clone())
8733    }
8734
8735    /// Continue this workflow instance as a fresh run with replacement arguments.
8736    ///
8737    /// Return this value directly from the workflow handler. The worker converts
8738    /// it to the terminal protocol command only after replay has consumed every
8739    /// recorded durable command.
8740    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
8741        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
8742    }
8743
8744    /// Continue as new with optional workflow-type and task-queue overrides.
8745    pub fn continue_as_new_with_options<T: Serialize>(
8746        &self,
8747        options: ContinueAsNewOptions,
8748        args: T,
8749    ) -> Result<Value> {
8750        options.validate()?;
8751        Err(Error::ContinueAsNew(ContinueAsNewRequest {
8752            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
8753            options,
8754        }))
8755    }
8756
8757    pub fn activity<T: Serialize>(
8758        &self,
8759        activity_type: impl Into<String>,
8760        args: T,
8761    ) -> ActivityCall {
8762        self.activity_with_options(activity_type, ActivityOptions::new(), args)
8763    }
8764
8765    pub fn activity_on_queue<T, Q>(
8766        &self,
8767        activity_type: impl Into<String>,
8768        task_queue: Option<Q>,
8769        args: T,
8770    ) -> ActivityCall
8771    where
8772        T: Serialize,
8773        Q: Into<String>,
8774    {
8775        let mut options = ActivityOptions::new();
8776        options.task_queue = task_queue.map(Into::into);
8777        self.activity_with_options(activity_type, options, args)
8778    }
8779
8780    /// Schedule one durable activity with retry, routing, and timeout options.
8781    ///
8782    /// Options are validated before the command is emitted. Once the command is
8783    /// recorded, replay consumes the same activity lifecycle at this command
8784    /// position and never emits a duplicate schedule.
8785    ///
8786    /// ```no_run
8787    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
8788    /// # use std::time::Duration;
8789    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
8790    /// let result = ctx
8791    ///     .activity_with_options(
8792    ///         "charge-card",
8793    ///         ActivityOptions::new()
8794    ///             .task_queue("payments")
8795    ///             .retry_policy(
8796    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
8797    ///                     Duration::from_secs(1),
8798    ///                     2,
8799    ///                     Some(Duration::from_secs(30)),
8800    ///                 ),
8801    ///             )
8802    ///             .start_to_close_timeout(Duration::from_secs(60))
8803    ///             .schedule_to_close_timeout(Duration::from_secs(180))
8804    ///             .heartbeat_timeout(Duration::from_secs(15)),
8805    ///         json!([{"order_id": "order-42"}]),
8806    ///     )
8807    ///     .await;
8808    /// match result {
8809    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
8810    ///         "reason": failure.reason,
8811    ///         "timeout_kind": failure.timeout_kind,
8812    ///     })),
8813    ///     other => other,
8814    /// }
8815    /// # }
8816    /// ```
8817    pub fn activity_with_options<T: Serialize>(
8818        &self,
8819        activity_type: impl Into<String>,
8820        options: ActivityOptions,
8821        args: T,
8822    ) -> ActivityCall {
8823        ActivityCall {
8824            ctx: self.clone(),
8825            activity_type: activity_type.into(),
8826            options,
8827            args: Some(AvroValue::from_serialize(&args)),
8828            scheduled: false,
8829            parallel_group_path: Vec::new(),
8830        }
8831    }
8832
8833    pub async fn activity_avro_value<T: Serialize>(
8834        &self,
8835        activity_type: impl Into<String>,
8836        args: T,
8837    ) -> Result<AvroValue> {
8838        let mut call = self.activity(activity_type, args);
8839        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
8840    }
8841
8842    pub async fn activity_avro_value_with_options<T: Serialize>(
8843        &self,
8844        activity_type: impl Into<String>,
8845        options: ActivityOptions,
8846        args: T,
8847    ) -> Result<AvroValue> {
8848        let mut call = self.activity_with_options(activity_type, options, args);
8849        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
8850    }
8851
8852    /// Schedule an activity with a Serde request and decode its Serde result.
8853    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
8854    where
8855        I: Serialize,
8856        O: DeserializeOwned,
8857    {
8858        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
8859            .await
8860    }
8861
8862    /// Schedule an activity with options and decode its result into `O`.
8863    ///
8864    /// Both directions use the fixed Avro Value codec. In particular, this
8865    /// method does not deserialize the JSON-safe inspection projection returned
8866    /// by the dynamic [`ActivityCall`] future.
8867    pub async fn activity_typed_with_options<I, O>(
8868        &self,
8869        activity_type: impl Into<String>,
8870        options: ActivityOptions,
8871        args: I,
8872    ) -> Result<O>
8873    where
8874        I: Serialize,
8875        O: DeserializeOwned,
8876    {
8877        let activity_type = activity_type.into();
8878        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
8879            handler_type_error::<I>(
8880                HandlerKind::Activity,
8881                &activity_type,
8882                HandlerValueKind::Input,
8883                error.to_string(),
8884            )
8885        });
8886        let mut call = ActivityCall {
8887            ctx: self.clone(),
8888            activity_type: activity_type.clone(),
8889            options,
8890            args: Some(encoded),
8891            scheduled: false,
8892            parallel_group_path: Vec::new(),
8893        };
8894        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
8895        decode_handler_result(result, HandlerKind::Activity, &activity_type)
8896    }
8897
8898    /// Schedule and join a deterministic activity/child/timer group.
8899    ///
8900    /// Nested groups retain their input shape. Every durable leaf is scheduled
8901    /// before this future yields, results are assembled by declaration order,
8902    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
8903    /// declaration path, stable group metadata, and completed siblings.
8904    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
8905        ParallelCall::new(self.clone(), operations)
8906    }
8907
8908    /// Alias for [`WorkflowContext::parallel`].
8909    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
8910        self.parallel(operations)
8911    }
8912
8913    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
8914    pub async fn parallel_avro_value(
8915        &self,
8916        operations: Vec<ParallelOperation>,
8917    ) -> Result<Vec<ParallelAvroResult>> {
8918        let mut call = self.parallel(operations);
8919        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
8920    }
8921
8922    /// Start every durable operation and resume from the one winner persisted
8923    /// by Server. Non-winning operations continue and remain addressable.
8924    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
8925        let operations = operations
8926            .into_iter()
8927            .enumerate()
8928            .map(|(index, operation)| (SelectionKey::Index(index), operation))
8929            .collect();
8930        SelectCall::new(self.clone(), operations)
8931    }
8932
8933    /// Named-key variant of [`WorkflowContext::select`].
8934    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
8935    where
8936        K: Into<SelectionKey>,
8937    {
8938        SelectCall::new(
8939            self.clone(),
8940            operations
8941                .into_iter()
8942                .map(|(key, operation)| (key.into(), operation))
8943                .collect(),
8944        )
8945    }
8946
8947    /// Create a workflow-local deterministic compensation registry.
8948    pub fn saga(&self) -> Saga {
8949        Saga::new(self.clone())
8950    }
8951
8952    /// Whether cancellation has reached this replay's authored boundary.
8953    ///
8954    /// Server's current `/cancel` route is terminal and does not set this flag.
8955    /// A canonical service request remains pending until its committed delivery
8956    /// is consumed. Request observation alone does not authorize an exception.
8957    pub fn is_cancellation_requested(&self) -> Result<bool> {
8958        let state = self
8959            .state
8960            .lock()
8961            .map_err(|_| Error::WorkflowStatePoisoned)?;
8962        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
8963            return Ok(state
8964                .scope_delivery
8965                .as_ref()
8966                .unwrap()
8967                .contexts
8968                .contains_key(&self.cancellation_scope_id));
8969        }
8970        Ok(state.cancel_requested
8971            || state
8972                .scope_delivery
8973                .as_ref()
8974                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
8975    }
8976
8977    /// Raise a typed cooperative cancellation at an author-controlled point.
8978    ///
8979    /// Passing this result to [`Saga::finish`] compensates already registered
8980    /// forward steps before the cancellation remains the initiating outcome.
8981    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
8982        let mut state = self
8983            .state
8984            .lock()
8985            .map_err(|_| Error::WorkflowStatePoisoned)?;
8986        if state.cancellation_shield_depth == 0 {
8987            if let Some(replay) = &state.scope_delivery {
8988                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
8989                    let delivered = replay
8990                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
8991                        .ok_or_else(|| {
8992                            Error::InvalidCooperativeCancellation(
8993                                "scoped request lacks its consumed original delivery".into(),
8994                            )
8995                        })?;
8996                    return Err(Error::CancellationScopeRequested(
8997                        CancellationScopeRequested {
8998                            context: context
8999                                .clone()
9000                                .with_replay(Some(Arc::downgrade(&self.state))),
9001                            delivery: delivered.boundary.clone(),
9002                        },
9003                    ));
9004                }
9005            }
9006        }
9007        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9008            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9009                return Ok(());
9010            }
9011            return Err(state.cancellation_error());
9012        }
9013        Ok(())
9014    }
9015
9016    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9017        SignalCall {
9018            ctx: self.clone(),
9019            signal_name: signal_name.into(),
9020            runtime_reserved_allowed: false,
9021            opened_wait: false,
9022            matched_pending: false,
9023            parallel_group_path: Vec::new(),
9024        }
9025    }
9026
9027    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9028        SignalCall {
9029            ctx: self.clone(),
9030            signal_name: signal_name.into(),
9031            runtime_reserved_allowed: true,
9032            opened_wait: false,
9033            matched_pending: false,
9034            parallel_group_path: Vec::new(),
9035        }
9036    }
9037
9038    pub async fn wait_signal_avro_value(
9039        &self,
9040        signal_name: impl Into<String>,
9041    ) -> Result<Vec<AvroValue>> {
9042        let mut call = self.wait_signal(signal_name);
9043        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9044    }
9045
9046    /// Return every committed signal argument list with the given name.
9047    ///
9048    /// This history-backed view is deterministic and is intended for
9049    /// condition predicates that must be re-evaluated after a signal while the
9050    /// workflow is blocked on [`WorkflowContext::wait_condition`].
9051    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
9052        self.signals_avro_value(signal_name)?
9053            .into_iter()
9054            .map(|arguments| {
9055                arguments
9056                    .into_iter()
9057                    .map(AvroValue::into_json)
9058                    .collect::<Result<Vec<_>>>()
9059            })
9060            .collect()
9061    }
9062
9063    /// Lossless fixed Avro Value view of committed signals with the given name.
9064    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9065        let state = self
9066            .state
9067            .lock()
9068            .map_err(|_| Error::WorkflowStatePoisoned)?;
9069        state
9070            .history_events
9071            .iter()
9072            .filter(|event| {
9073                event.event_type == "SignalReceived"
9074                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
9075            })
9076            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
9077            .collect()
9078    }
9079
9080    /// Return every committed update argument list with the given name.
9081    ///
9082    /// Accepted and applied records for the same update ID are de-duplicated.
9083    /// A Server task created after an update therefore replays the workflow and
9084    /// re-evaluates an open condition without application polling.
9085    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
9086        self.updates_avro_value(update_name)?
9087            .into_iter()
9088            .map(|arguments| {
9089                arguments
9090                    .into_iter()
9091                    .map(AvroValue::into_json)
9092                    .collect::<Result<Vec<_>>>()
9093            })
9094            .collect()
9095    }
9096
9097    /// Lossless fixed Avro Value view of committed updates with the given name.
9098    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9099        let state = self
9100            .state
9101            .lock()
9102            .map_err(|_| Error::WorkflowStatePoisoned)?;
9103        let mut seen = Vec::new();
9104        let mut updates = Vec::new();
9105        for event in state.history_events.iter() {
9106            if !matches!(
9107                event.event_type.as_str(),
9108                "UpdateAccepted" | "UpdateApplied"
9109            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
9110                || event.payload.get("arguments").is_none()
9111            {
9112                continue;
9113            }
9114            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
9115                if seen.iter().any(|recorded| recorded == update_id) {
9116                    continue;
9117                }
9118                seen.push(update_id.to_string());
9119            }
9120            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
9121        }
9122        Ok(updates)
9123    }
9124
9125    /// Wait for a deterministic predicate to become true or for its durable
9126    /// timeout to elapse.
9127    ///
9128    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
9129    /// predicate tokens automatically change the recorded definition
9130    /// fingerprint. Direct callers must provide an equally stable identity in
9131    /// [`ConditionWaitOptions`].
9132    pub fn wait_condition<F>(
9133        &self,
9134        options: ConditionWaitOptions,
9135        predicate: F,
9136    ) -> ConditionWaitCall
9137    where
9138        F: Fn() -> Result<bool> + Send + 'static,
9139    {
9140        ConditionWaitCall {
9141            ctx: self.clone(),
9142            options,
9143            predicate: Box::new(predicate),
9144            occurrence_id: None,
9145            opened_wait: false,
9146            parallel_group_path: Vec::new(),
9147        }
9148    }
9149
9150    /// Wait for server-backed durable time without blocking the worker executor.
9151    ///
9152    /// Polling this future emits one `start_timer` command and yields. The
9153    /// server records the deadline, so neither worker nor server restarts reset
9154    /// the wait. Replay resolves the future only from a `TimerScheduled` and
9155    /// `TimerFired` pair at the same position in the shared durable-command
9156    /// stream, with matching sequence, timer identity, and delay. Sub-second
9157    /// durations round up because protocol deadlines use whole seconds.
9158    ///
9159    /// ```no_run
9160    /// # use durable_workflow::{json, Client, Worker};
9161    /// # use std::time::Duration;
9162    /// # fn configure(client: Client) {
9163    /// let mut worker = Worker::new(client, "rust-workers");
9164    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
9165    ///     ctx.sleep(Duration::from_secs(5)).await?;
9166    ///     Ok(json!({"status": "timer fired"}))
9167    /// });
9168    /// # }
9169    /// ```
9170    pub fn sleep(&self, duration: Duration) -> TimerCall {
9171        let delay_seconds = duration
9172            .as_secs()
9173            .checked_add(u64::from(duration.subsec_nanos() > 0));
9174        TimerCall {
9175            ctx: self.clone(),
9176            delay_seconds,
9177            scheduled: false,
9178            matched_pending: false,
9179            parallel_group_path: Vec::new(),
9180        }
9181    }
9182
9183    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
9184    pub fn start_timer(&self, duration: Duration) -> TimerCall {
9185        self.sleep(duration)
9186    }
9187
9188    /// Evaluate a non-deterministic callback once and durably record its typed value.
9189    ///
9190    /// On replay the callback is not invoked: the value is decoded from the
9191    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
9192    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
9193    /// small values that must remain fixed for the lifetime of a workflow run.
9194    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
9195    where
9196        T: Serialize + DeserializeOwned,
9197        F: FnOnce() -> T,
9198    {
9199        {
9200            let mut state = self
9201                .state
9202                .lock()
9203                .map_err(|_| Error::WorkflowStatePoisoned)?;
9204            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9205                return match recorded {
9206                    RecordedCommand::SideEffect { sequence, value } => {
9207                        state.command_cursor += 1;
9208                        value.deserialize().map_err(|error| {
9209                            Error::NonDeterministicReplay(ReplayFailure::new(
9210                                "side_effect_type_mismatch",
9211                                Some(sequence),
9212                                Some(std::any::type_name::<T>().to_string()),
9213                                Some(error.to_string()),
9214                                "recorded side-effect value is incompatible with the requested Rust type",
9215                            ))
9216                        })
9217                    }
9218                    other => Err(command_mismatch(&other, "side effect")),
9219                };
9220            }
9221        }
9222
9223        let value = callback();
9224        let avro_value = AvroValue::from_serialize(&value)?;
9225        let mut state = self
9226            .state
9227            .lock()
9228            .map_err(|_| Error::WorkflowStatePoisoned)?;
9229        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
9230        state.commands.push(json!({
9231            "type": "record_side_effect",
9232            "result": result,
9233        }));
9234        Ok(value)
9235    }
9236
9237    /// Record or replay a lossless fixed Avro Value side effect.
9238    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
9239    where
9240        F: FnOnce() -> AvroValue,
9241    {
9242        {
9243            let mut state = self
9244                .state
9245                .lock()
9246                .map_err(|_| Error::WorkflowStatePoisoned)?;
9247            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9248                return match recorded {
9249                    RecordedCommand::SideEffect { value, .. } => {
9250                        state.command_cursor += 1;
9251                        Ok(value)
9252                    }
9253                    other => Err(command_mismatch(&other, "side effect")),
9254                };
9255            }
9256        }
9257
9258        let value = callback();
9259        let mut state = self
9260            .state
9261            .lock()
9262            .map_err(|_| Error::WorkflowStatePoisoned)?;
9263        let result = encode_typed_envelope(&value, &state.payload_codec)?;
9264        state.commands.push(json!({
9265            "type": "record_side_effect",
9266            "result": result,
9267        }));
9268        Ok(value)
9269    }
9270
9271    /// Append output items at a deterministic workflow command boundary.
9272    ///
9273    /// Stable idempotency keys are derived from the server-provided durable
9274    /// workflow command identity, command ordinal, and item index. Replay
9275    /// consumes the recorded side effect and never emits another append.
9276    pub fn append_workflow_stream(
9277        &self,
9278        stream_name: impl Into<String>,
9279        items: &[WorkflowStreamAppendItem],
9280        max_pending_items: Option<u64>,
9281    ) -> Result<()> {
9282        if items.is_empty() {
9283            return Err(Error::Codec(
9284                "workflow_stream_items_empty: append requires at least one item".to_string(),
9285            ));
9286        }
9287        if max_pending_items == Some(0) {
9288            return Err(Error::Codec(
9289                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
9290                    .to_string(),
9291            ));
9292        }
9293        let stream_name = stream_name.into();
9294        if stream_name.is_empty() {
9295            return Err(Error::Codec(
9296                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9297            ));
9298        }
9299
9300        let mut state = self
9301            .state
9302            .lock()
9303            .map_err(|_| Error::WorkflowStatePoisoned)?;
9304        let command_ordinal = state.workflow_stream_command_counter;
9305        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9306            state.workflow_stream_command_counter += 1;
9307            return match recorded {
9308                RecordedCommand::SideEffect { .. } => {
9309                    state.command_cursor += 1;
9310                    Ok(())
9311                }
9312                other => Err(command_mismatch(&other, "workflow stream append")),
9313            };
9314        }
9315
9316        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9317        state.workflow_stream_command_counter += 1;
9318        let wire_items = items
9319            .iter()
9320            .enumerate()
9321            .map(|(item_index, item)| {
9322                item.wire_value(Some(format!(
9323                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
9324                )))
9325            })
9326            .collect::<Vec<_>>();
9327        let mut directive = json!({
9328            "operation": "append",
9329            "stream_name": stream_name,
9330            "command_identity": identity,
9331            "command_ordinal": command_ordinal,
9332            "items": wire_items,
9333        });
9334        if let Some(max_pending_items) = max_pending_items {
9335            directive["max_pending_items"] = json!(max_pending_items);
9336        }
9337        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9338        state.commands.push(json!({
9339            "type": "record_side_effect",
9340            "result": result,
9341            "workflow_stream": directive,
9342        }));
9343        Ok(())
9344    }
9345
9346    /// Close a run-scoped output stream at a deterministic command boundary.
9347    pub fn close_workflow_stream(
9348        &self,
9349        stream_name: impl Into<String>,
9350        retention_seconds: Option<u64>,
9351    ) -> Result<()> {
9352        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
9353    }
9354
9355    /// Mark a run-scoped output stream errored at a deterministic command boundary.
9356    pub fn error_workflow_stream(
9357        &self,
9358        stream_name: impl Into<String>,
9359        error_reason: impl Into<String>,
9360        retention_seconds: Option<u64>,
9361    ) -> Result<()> {
9362        let error_reason = error_reason.into();
9363        if error_reason.is_empty() {
9364            return Err(Error::Codec(
9365                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
9366            ));
9367        }
9368        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
9369    }
9370
9371    fn finish_workflow_stream(
9372        &self,
9373        stream_name: String,
9374        error_reason: Option<String>,
9375        retention_seconds: Option<u64>,
9376    ) -> Result<()> {
9377        if stream_name.is_empty() {
9378            return Err(Error::Codec(
9379                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9380            ));
9381        }
9382        if retention_seconds == Some(0) {
9383            return Err(Error::Codec(
9384                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
9385            ));
9386        }
9387        let mut state = self
9388            .state
9389            .lock()
9390            .map_err(|_| Error::WorkflowStatePoisoned)?;
9391        let command_ordinal = state.workflow_stream_command_counter;
9392        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9393            state.workflow_stream_command_counter += 1;
9394            return match recorded {
9395                RecordedCommand::SideEffect { .. } => {
9396                    state.command_cursor += 1;
9397                    Ok(())
9398                }
9399                other => Err(command_mismatch(&other, "workflow stream close")),
9400            };
9401        }
9402        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9403        state.workflow_stream_command_counter += 1;
9404        let mut directive = json!({
9405            "operation": if error_reason.is_some() { "error" } else { "close" },
9406            "stream_name": stream_name,
9407            "command_identity": identity,
9408            "command_ordinal": command_ordinal,
9409        });
9410        if let Some(error_reason) = error_reason {
9411            directive["error_reason"] = json!(error_reason);
9412        }
9413        if let Some(retention_seconds) = retention_seconds {
9414            directive["retention_seconds"] = json!(retention_seconds);
9415        }
9416        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9417        state.commands.push(json!({
9418            "type": "record_side_effect",
9419            "result": result,
9420            "workflow_stream": directive,
9421        }));
9422        Ok(())
9423    }
9424
9425    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
9426        let identity = state.workflow_command_identity.as_str();
9427        if identity.is_empty() {
9428            return Err(Error::MissingWorkflowCommandIdentity);
9429        }
9430        Ok(identity)
9431    }
9432
9433    /// Validate, emit, or replay a typed workflow search-attribute update.
9434    ///
9435    /// The command is non-blocking within a workflow decision, but its
9436    /// `SearchAttributesUpserted` event occupies the same deterministic command
9437    /// stream as activities, timers, conditions, and other durable operations.
9438    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
9439        update.validate()?;
9440        let (attributes, attribute_types) = update.into_wire_parts();
9441        let mut state = self
9442            .state
9443            .lock()
9444            .map_err(|_| Error::WorkflowStatePoisoned)?;
9445
9446        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9447            return match recorded {
9448                RecordedCommand::SearchAttributes {
9449                    sequence,
9450                    attributes: recorded_attributes,
9451                    attribute_types: recorded_attribute_types,
9452                } => {
9453                    if recorded_attributes != attributes {
9454                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9455                            "search_attribute_value_mismatch",
9456                            Some(sequence),
9457                            Some(recorded_attributes.to_string()),
9458                            Some(attributes.to_string()),
9459                            "search-attribute values differ from the recorded durable command",
9460                        )));
9461                    }
9462                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
9463                        if recorded_types != attribute_types {
9464                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9465                                "search_attribute_type_mismatch",
9466                                Some(sequence),
9467                                Some(json!(recorded_types).to_string()),
9468                                Some(json!(attribute_types).to_string()),
9469                                "search-attribute declared types differ from the recorded durable command",
9470                            )));
9471                        }
9472                    }
9473                    state.command_cursor += 1;
9474                    Ok(())
9475                }
9476                other => Err(command_mismatch(&other, "search-attribute update")),
9477            };
9478        }
9479
9480        let mut command = serde_json::Map::from_iter([
9481            ("type".to_string(), json!("upsert_search_attributes")),
9482            ("attributes".to_string(), attributes),
9483        ]);
9484        if !attribute_types.is_empty() {
9485            command.insert("attribute_types".to_string(), json!(attribute_types));
9486        }
9487        state.commands.push(Value::Object(command));
9488        Ok(())
9489    }
9490
9491    /// Record a UUIDv4 once and return the same UUID on every replay.
9492    pub fn uuid_v4(&self) -> Result<Uuid> {
9493        self.side_effect(Uuid::new_v4)
9494    }
9495
9496    /// Select the newest supported version for a change, or replay the version
9497    /// already committed for that stable change ID.
9498    pub fn get_version(
9499        &self,
9500        change_id: impl Into<String>,
9501        min_supported: i32,
9502        max_supported: i32,
9503    ) -> Result<i32> {
9504        let change_id = change_id.into();
9505        if change_id.trim().is_empty() {
9506            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9507                "version_change_id_invalid",
9508                None,
9509                Some("non-empty change ID".to_string()),
9510                Some(change_id),
9511                "version markers require a stable non-empty change ID",
9512            )));
9513        }
9514        if min_supported > max_supported {
9515            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9516                "version_range_invalid",
9517                None,
9518                Some("min_supported <= max_supported".to_string()),
9519                Some(format!("{min_supported}..={max_supported}")),
9520                "version marker supported range is invalid",
9521            )));
9522        }
9523
9524        let mut state = self
9525            .state
9526            .lock()
9527            .map_err(|_| Error::WorkflowStatePoisoned)?;
9528        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
9529            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
9530            return Ok(version);
9531        }
9532
9533        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9534            return match recorded {
9535                RecordedCommand::VersionMarker {
9536                    sequence,
9537                    change_id: recorded_change_id,
9538                    version,
9539                    ..
9540                } => {
9541                    if recorded_change_id != change_id {
9542                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9543                            "version_change_id_mismatch",
9544                            Some(sequence),
9545                            Some(recorded_change_id),
9546                            Some(change_id),
9547                            "recorded version marker change ID differs from current workflow code",
9548                        )));
9549                    }
9550                    ensure_version_supported(
9551                        &change_id,
9552                        version,
9553                        min_supported,
9554                        max_supported,
9555                        sequence,
9556                    )?;
9557                    state.command_cursor += 1;
9558                    state.version_markers.insert(change_id, (version, sequence));
9559                    Ok(version)
9560                }
9561                other => Err(command_mismatch(
9562                    &other,
9563                    format!("version marker:{change_id}"),
9564                )),
9565            };
9566        }
9567
9568        let version = max_supported;
9569        state.commands.push(json!({
9570            "type": "record_version_marker",
9571            "change_id": change_id,
9572            "version": version,
9573            "min_supported": min_supported,
9574            "max_supported": max_supported,
9575        }));
9576        // Sequence numbers are assigned by the server. Zero identifies a marker
9577        // selected in this uncommitted decision batch for duplicate-call checks.
9578        state.version_markers.insert(change_id, (version, 0));
9579        Ok(version)
9580    }
9581
9582    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
9583    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
9584        Ok(self.get_version(change_id, -1, 1)? == 1)
9585    }
9586
9587    /// Keep a patch marker in history after the legacy branch has been removed.
9588    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
9589        self.get_version(change_id, -1, 1).map(|_| ())
9590    }
9591
9592    /// Merge non-indexed workflow memo metadata through durable history.
9593    ///
9594    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
9595    /// public Avro payload envelope consumed by Server and Cloud runtimes.
9596    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
9597        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
9598        let mut state = self
9599            .state
9600            .lock()
9601            .map_err(|_| Error::WorkflowStatePoisoned)?;
9602
9603        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9604            return match recorded {
9605                RecordedCommand::Memo {
9606                    sequence,
9607                    entries: recorded_entries,
9608                } => {
9609                    if recorded_entries != entries {
9610                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9611                            "memo_update_mismatch",
9612                            Some(sequence),
9613                            Some(format!("{recorded_entries:?}")),
9614                            Some(format!("{entries:?}")),
9615                            "recorded memo entries differ from the current workflow update",
9616                        )));
9617                    }
9618                    state.command_cursor += 1;
9619                    Ok(())
9620                }
9621                other => Err(command_mismatch(&other, "memo upsert")),
9622            };
9623        }
9624
9625        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
9626        state.commands.push(json!({
9627            "type": "upsert_memo",
9628            "entries": entries_envelope,
9629        }));
9630        Ok(())
9631    }
9632
9633    /// Start a named durable child on an explicit queue and await its result.
9634    ///
9635    /// The command is recorded in the parent's sequence-ordered durable command
9636    /// stream. Replay keeps a scheduled child pending without emitting another
9637    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
9638    /// values preserve the history payload codec and include both sides of the
9639    /// durable relationship; failures are returned as
9640    /// [`Error::ChildWorkflowFailed`].
9641    ///
9642    /// ```no_run
9643    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
9644    /// # fn configure(client: Client) {
9645    /// let mut worker = Worker::new(client, "parent-workers");
9646    /// worker.register_workflow("order-parent", |ctx, _input| async move {
9647    ///     let child = ctx
9648    ///         .start_child_workflow(
9649    ///             "fulfil-order",
9650    ///             ChildWorkflowOptions::new("fulfilment-workers")
9651    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
9652    ///             json!([{"order_id": "order-42"}]),
9653    ///         )
9654    ///         .await?;
9655    ///     Ok(child.result)
9656    /// });
9657    /// # }
9658    /// ```
9659    pub fn start_child_workflow<T: Serialize>(
9660        &self,
9661        workflow_type: impl Into<String>,
9662        options: ChildWorkflowOptions,
9663        args: T,
9664    ) -> ChildWorkflowCall {
9665        ChildWorkflowCall {
9666            ctx: self.clone(),
9667            workflow_type: workflow_type.into(),
9668            options,
9669            args: Some(AvroValue::from_serialize(&args)),
9670            scheduled: false,
9671            matched_pending: false,
9672            parallel_group_path: Vec::new(),
9673        }
9674    }
9675
9676    pub async fn start_child_workflow_avro_value<T: Serialize>(
9677        &self,
9678        workflow_type: impl Into<String>,
9679        options: ChildWorkflowOptions,
9680        args: T,
9681    ) -> Result<ChildWorkflowAvroResult> {
9682        let mut call = self.start_child_workflow(workflow_type, options, args);
9683        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9684    }
9685
9686    fn take_commands(&self) -> Result<Vec<Value>> {
9687        let mut state = self
9688            .state
9689            .lock()
9690            .map_err(|_| Error::WorkflowStatePoisoned)?;
9691        Ok(std::mem::take(&mut state.commands))
9692    }
9693
9694    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
9695        let mut state = self
9696            .state
9697            .lock()
9698            .map_err(|_| Error::WorkflowStatePoisoned)?;
9699
9700        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9701            return Err(command_mismatch(&recorded, "continue as new"));
9702        }
9703        if state.recorded_continue_as_new_sequence.is_some() {
9704            state.continue_as_new_consumed = true;
9705            return Ok(None);
9706        }
9707
9708        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
9709        let mut command = serde_json::Map::from_iter([
9710            ("type".to_string(), json!("continue_as_new")),
9711            ("arguments".to_string(), arguments),
9712            ("queue".to_string(), json!(state.task_queue.clone())),
9713        ]);
9714        if let Some(workflow_type) = request.options.workflow_type {
9715            command.insert("workflow_type".to_string(), json!(workflow_type));
9716        }
9717        if let Some(task_queue) = request.options.task_queue {
9718            command.insert("queue".to_string(), json!(task_queue));
9719        }
9720        Ok(Some(Value::Object(command)))
9721    }
9722
9723    fn matched_recorded_pending(&self) -> Result<bool> {
9724        let state = self
9725            .state
9726            .lock()
9727            .map_err(|_| Error::WorkflowStatePoisoned)?;
9728        Ok(state.matched_recorded_pending)
9729    }
9730
9731    fn ensure_history_consumed(&self) -> Result<()> {
9732        let state = self
9733            .state
9734            .lock()
9735            .map_err(|_| Error::WorkflowStatePoisoned)?;
9736        if let Some(replay) = &state.scope_delivery {
9737            if let Some((&sequence, _)) = replay
9738                .canonical
9739                .deliveries
9740                .iter()
9741                .find(|(sequence, _)| !replay.consumed.contains(sequence))
9742            {
9743                return Err(invalid_recorded_history(
9744                    "cancellation_scope_delivery_unconsumed",
9745                    sequence,
9746                    "original scoped delivery",
9747                    "workflow completion",
9748                    "workflow completed without consuming its committed scope delivery",
9749                ));
9750            }
9751        }
9752        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
9753            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9754                "recorded_commands_unconsumed",
9755                Some(command.sequence()),
9756                Some(command.shape().to_string()),
9757                Some("workflow completion".to_string()),
9758                "workflow completed before consuming all recorded durable commands",
9759            )));
9760        }
9761        if let Some(delivery) = state
9762            .cancellation_history
9763            .delivery
9764            .as_ref()
9765            .filter(|_| !state.cancellation_consumed)
9766        {
9767            return Err(invalid_recorded_history(
9768                "cooperative_cancellation_unconsumed",
9769                delivery.sequence,
9770                "committed cancellation call",
9771                "workflow completion",
9772                "workflow completed without reaching its committed cancellation boundary",
9773            ));
9774        }
9775        if let Some(sequence) = state
9776            .recorded_continue_as_new_sequence
9777            .filter(|_| !state.continue_as_new_consumed)
9778        {
9779            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9780                "recorded_continue_as_new_unconsumed",
9781                Some(sequence),
9782                Some("continue as new".to_string()),
9783                Some("workflow completion".to_string()),
9784                "workflow completed without consuming its recorded continue-as-new transition",
9785            )));
9786        }
9787        Ok(())
9788    }
9789}
9790
9791fn contiguous_message_stream_count(
9792    pending: &[MessageStreamMessage],
9793    cursor: u64,
9794    max_items: usize,
9795) -> usize {
9796    pending
9797        .iter()
9798        .take(max_items)
9799        .enumerate()
9800        .take_while(|(offset, message)| {
9801            u64::try_from(*offset)
9802                .ok()
9803                .and_then(|offset| cursor.checked_add(offset + 1))
9804                == Some(message.position)
9805        })
9806        .count()
9807}
9808
9809fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
9810    matches!(
9811        event.event_type.as_str(),
9812        "ActivityScheduled"
9813            | "TimerScheduled"
9814            | "ChildWorkflowScheduled"
9815            | "SignalWaitOpened"
9816            | "ConditionWaitOpened"
9817            | "SearchAttributesUpserted"
9818            | "SideEffectRecorded"
9819            | "VersionMarkerRecorded"
9820            | "MemoUpserted"
9821            | "WorkflowContinuedAsNew"
9822    )
9823}
9824
9825#[derive(Debug)]
9826struct WorkflowState {
9827    workflow_id: Option<String>,
9828    run_id: Option<String>,
9829    task_queue: String,
9830    payload_codec: String,
9831    history_events: Arc<Vec<HistoryEvent>>,
9832    history_budget: WorkflowHistoryBudget,
9833    cancel_requested: bool,
9834    cancellation_history: CancellationHistory,
9835    cancellation_consumed: bool,
9836    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
9837    cancellation_shield_depth: u64,
9838    cancellation_delivery_enabled: bool,
9839    cancellation_delivery_intent: Option<CancellationDelivery>,
9840    cancellation_delivery_command_count: usize,
9841    allow_cancellation_scope_authoring: bool,
9842    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
9843    cancellation_scope_memberships: BTreeMap<u64, String>,
9844    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
9845    resume_signal: Option<ResumeSignal>,
9846    recorded_commands: Vec<RecordedCommand>,
9847    selection_markers: Vec<SelectionMarker>,
9848    selection_marker_cursor: usize,
9849    cancelled_selection_members: Vec<SelectionCancellation>,
9850    recorded_continue_as_new_sequence: Option<u64>,
9851    continue_as_new_consumed: bool,
9852    command_cursor: usize,
9853    condition_wait_occurrence_counter: u64,
9854    matched_recorded_pending: bool,
9855    version_markers: HashMap<String, (i32, u64)>,
9856    workflow_command_identity: String,
9857    workflow_stream_command_counter: u64,
9858    commands: Vec<Value>,
9859    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
9860    message_stream_cursors: HashMap<String, u64>,
9861    message_stream_waits: HashMap<String, u64>,
9862}
9863
9864impl WorkflowState {
9865    #[cfg(test)]
9866    fn new(
9867        history: Vec<HistoryEvent>,
9868        task_queue: String,
9869        payload_codec: String,
9870        resume_signal: Option<ResumeSignal>,
9871    ) -> Result<Self> {
9872        Self::new_with_identity(
9873            history,
9874            None,
9875            None,
9876            task_queue,
9877            payload_codec,
9878            resume_signal,
9879        )
9880    }
9881
9882    fn new_with_identity(
9883        history: Vec<HistoryEvent>,
9884        workflow_id: Option<String>,
9885        run_id: Option<String>,
9886        task_queue: String,
9887        payload_codec: String,
9888        resume_signal: Option<ResumeSignal>,
9889    ) -> Result<Self> {
9890        Self::new_with_identity_and_scopes(
9891            history,
9892            workflow_id,
9893            run_id,
9894            task_queue,
9895            payload_codec,
9896            resume_signal,
9897            false,
9898        )
9899    }
9900
9901    fn new_with_identity_and_scopes(
9902        history: Vec<HistoryEvent>,
9903        workflow_id: Option<String>,
9904        run_id: Option<String>,
9905        task_queue: String,
9906        payload_codec: String,
9907        resume_signal: Option<ResumeSignal>,
9908        allow_cancellation_scope_authoring: bool,
9909    ) -> Result<Self> {
9910        Self::new_with_identity_and_scope_delivery(
9911            history,
9912            workflow_id,
9913            run_id,
9914            task_queue,
9915            payload_codec,
9916            resume_signal,
9917            allow_cancellation_scope_authoring,
9918            false,
9919        )
9920    }
9921
9922    fn new_with_identity_and_scope_delivery(
9923        history: Vec<HistoryEvent>,
9924        workflow_id: Option<String>,
9925        run_id: Option<String>,
9926        task_queue: String,
9927        payload_codec: String,
9928        resume_signal: Option<ResumeSignal>,
9929        allow_cancellation_scope_authoring: bool,
9930        allow_cancellation_scope_delivery: bool,
9931    ) -> Result<Self> {
9932        cooperative_cancellation::assert_cancellation_scope_replay_supported(
9933            &history,
9934            allow_cancellation_scope_authoring,
9935            allow_cancellation_scope_delivery,
9936        )?;
9937        let scopes = if allow_cancellation_scope_authoring {
9938            cancellation_scope::CancellationScopeHistory::read(
9939                &history,
9940                run_id.as_deref().unwrap_or_default(),
9941            )?
9942        } else {
9943            cancellation_scope::CancellationScopeHistory::default()
9944        };
9945        let cancellation_history = CancellationHistory::from_events(
9946            &history,
9947            run_id.as_deref().unwrap_or_default(),
9948            None,
9949        )?;
9950        if allow_cancellation_scope_authoring
9951            && cancellation_history.request.is_some()
9952            && !allow_cancellation_scope_delivery
9953        {
9954            return Err(Error::CancellationScopeExecutionUnavailable);
9955        }
9956        let scope_delivery = if allow_cancellation_scope_delivery {
9957            Some(cancellation_scope_replay::ScopeReplay::read(
9958                &history,
9959                &scopes,
9960                run_id.as_deref().unwrap_or_default(),
9961                workflow_id.as_deref().unwrap_or_default(),
9962            )?)
9963        } else {
9964            None
9965        };
9966        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
9967            &history,
9968            &payload_codec,
9969            WorkflowIdentity {
9970                workflow_id: workflow_id.clone(),
9971                run_id: run_id.clone(),
9972            },
9973        )?)?;
9974        for (sequence, opening) in &scopes.openings {
9975            if recorded_commands
9976                .iter()
9977                .any(|command| command.sequence() == *sequence)
9978            {
9979                return Err(invalid_recorded_history(
9980                    "invalid_cancellation_scope_history",
9981                    *sequence,
9982                    "distinct authored scope opening",
9983                    "operation collision",
9984                    "scope opening collides with a command",
9985                ));
9986            }
9987            recorded_commands.push(RecordedCommand::CancellationScope {
9988                sequence: *sequence,
9989                scope_id: opening.scope_id.clone(),
9990                parent_scope_id: opening.parent_scope_id.clone(),
9991                shield_parent: opening.shield_parent,
9992            });
9993        }
9994        recorded_commands.sort_by_key(RecordedCommand::sequence);
9995        if let Some(replay) = &scope_delivery {
9996            replay.bind_commands(&mut recorded_commands)?;
9997        }
9998        let selection_markers = recorded_selection_markers(&history)?;
9999        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
10000        let recorded_continue_as_new = history
10001            .iter()
10002            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
10003            .collect::<Vec<_>>();
10004        if recorded_continue_as_new.len() > 1 {
10005            return Err(invalid_recorded_history(
10006                "duplicate_continue_as_new_transition",
10007                recorded_continue_as_new
10008                    .last()
10009                    .and_then(|event| durable_event_sequence(event))
10010                    .unwrap_or(0),
10011                "one WorkflowContinuedAsNew event",
10012                &format!(
10013                    "{} WorkflowContinuedAsNew events",
10014                    recorded_continue_as_new.len()
10015                ),
10016                "workflow history records one continue-as-new transition more than once",
10017            ));
10018        }
10019        let recorded_continue_as_new_sequence = recorded_continue_as_new
10020            .first()
10021            .map(|event| {
10022                durable_event_sequence(event).ok_or_else(|| {
10023                    Error::NonDeterministicReplay(ReplayFailure::new(
10024                        "continue_as_new_sequence_missing",
10025                        None,
10026                        Some("recorded transition sequence".to_string()),
10027                        Some("missing sequence".to_string()),
10028                        "WorkflowContinuedAsNew history is missing its recorded sequence",
10029                    ))
10030                })
10031            })
10032            .transpose()?;
10033        let mut message_stream_cursors = HashMap::new();
10034        for event in &history {
10035            if !matches!(
10036                event.event_type.as_str(),
10037                "SignalReceived" | "SignalApplied"
10038            ) || event.payload.get("signal_name").and_then(Value::as_str)
10039                != Some(MESSAGE_STREAM_SIGNAL)
10040            {
10041                continue;
10042            }
10043            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
10044            if arguments.len() != 1 {
10045                continue;
10046            }
10047            let envelope = arguments[0].clone().into_json()?;
10048            let Some(envelope) = envelope.as_object() else {
10049                continue;
10050            };
10051            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
10052            {
10053                continue;
10054            }
10055            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10056                continue;
10057            };
10058            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10059            else {
10060                continue;
10061            };
10062            let cursor = message_stream_cursors
10063                .entry(stream_name.to_string())
10064                .or_insert(0);
10065            *cursor = (*cursor).max(through_position);
10066        }
10067        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
10068        let cancel_requested = history.iter().any(|event| {
10069            matches!(
10070                event.event_type.as_str(),
10071                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
10072            )
10073        });
10074        let cancellation_clock = cancellation_history
10075            .request
10076            .as_ref()
10077            .and_then(|request| request.context.as_ref())
10078            .map(|_| {
10079                cancellation_replay_clock::ReplayClock::new(
10080                    &history,
10081                    &recorded_commands,
10082                    cancellation_history.delivery_index,
10083                )
10084            })
10085            .or_else(|| {
10086                scope_delivery.as_ref().map(|_| {
10087                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
10088                })
10089            });
10090        Ok(Self {
10091            workflow_command_identity: String::new(),
10092            workflow_stream_command_counter: 0,
10093            workflow_id,
10094            run_id,
10095            task_queue,
10096            payload_codec,
10097            history_events: Arc::new(history),
10098            history_budget: WorkflowHistoryBudget {
10099                event_count,
10100                ..WorkflowHistoryBudget::default()
10101            },
10102            cancel_requested,
10103            cancellation_history,
10104            cancellation_consumed: false,
10105            cancellation_clock,
10106            cancellation_shield_depth: 0,
10107            cancellation_delivery_enabled: false,
10108            cancellation_delivery_intent: None,
10109            cancellation_delivery_command_count: 0,
10110            allow_cancellation_scope_authoring,
10111            cancellation_scope_opening: None,
10112            cancellation_scope_memberships: scopes.memberships,
10113            scope_delivery,
10114            resume_signal,
10115            recorded_commands,
10116            selection_markers,
10117            selection_marker_cursor: 0,
10118            cancelled_selection_members,
10119            recorded_continue_as_new_sequence,
10120            continue_as_new_consumed: false,
10121            command_cursor: 0,
10122            condition_wait_occurrence_counter: 0,
10123            matched_recorded_pending: false,
10124            version_markers: HashMap::new(),
10125            commands: Vec::new(),
10126            message_stream_messages: HashMap::new(),
10127            message_stream_cursors,
10128            message_stream_waits: HashMap::new(),
10129        })
10130    }
10131}
10132
10133enum MessageStreamDelivery {
10134    Message(MessageStreamMessage),
10135    Cursor {
10136        stream_name: String,
10137        through_position: u64,
10138    },
10139}
10140
10141fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
10142    if arguments.len() != 1 {
10143        return Ok(None);
10144    }
10145    let envelope = arguments
10146        .into_iter()
10147        .next()
10148        .expect("one argument was checked");
10149    let Some(envelope) = envelope.as_object() else {
10150        return Ok(None);
10151    };
10152    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10153        return Ok(None);
10154    };
10155    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
10156        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10157        else {
10158            return Ok(None);
10159        };
10160        return Ok(Some(MessageStreamDelivery::Cursor {
10161            stream_name: stream_name.to_string(),
10162            through_position,
10163        }));
10164    }
10165    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
10166        return Ok(None);
10167    }
10168    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
10169        return Ok(None);
10170    };
10171    let Some(position) = envelope
10172        .get("position")
10173        .and_then(Value::as_u64)
10174        .filter(|value| *value > 0)
10175    else {
10176        return Ok(None);
10177    };
10178    let Some(payload_envelope) = envelope.get("payload_envelope") else {
10179        return Ok(None);
10180    };
10181    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
10182    else {
10183        return Ok(None);
10184    };
10185    let decoded = decode_avro_value(&payload_envelope)?;
10186    let AvroValue::Array(values) = decoded else {
10187        return Ok(None);
10188    };
10189    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
10190        stream_name: stream_name.to_string(),
10191        message_id: message_id.to_string(),
10192        position,
10193        arguments: values,
10194    })))
10195}
10196
10197#[derive(Clone, Debug)]
10198enum RecordedCommand {
10199    CancellationScope {
10200        sequence: u64,
10201        scope_id: String,
10202        parent_scope_id: String,
10203        shield_parent: bool,
10204    },
10205    CancellationGroup {
10206        sequence: u64,
10207        span: u64,
10208        original: Vec<RecordedCommand>,
10209    },
10210    CancellationBoundary {
10211        sequence: u64,
10212        call_kind: CancellationCallKind,
10213        original: Option<Box<RecordedCommand>>,
10214    },
10215    Activity {
10216        sequence: u64,
10217        activity_type: Option<String>,
10218        cancellation_policy: String,
10219        options: Option<RecordedActivityOptions>,
10220        outcome: Option<ActivityOutcome>,
10221        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10222    },
10223    Timer {
10224        sequence: u64,
10225        delay_seconds: u64,
10226        fired: bool,
10227        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10228    },
10229    ChildWorkflow {
10230        sequence: u64,
10231        workflow_type: Option<String>,
10232        policies: RecordedChildPolicies,
10233        outcome: Option<ChildWorkflowOutcome>,
10234        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10235    },
10236    SignalWait {
10237        sequence: u64,
10238        signal_name: String,
10239        value: Option<Vec<AvroValue>>,
10240        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10241    },
10242    ConditionWait {
10243        sequence: u64,
10244        occurrence_id: String,
10245        condition_key: Option<String>,
10246        predicate_identity: String,
10247        timeout_seconds: Option<u64>,
10248        result: Option<ConditionWaitResult>,
10249        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10250    },
10251    SearchAttributes {
10252        sequence: u64,
10253        attributes: Value,
10254        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
10255    },
10256    SideEffect {
10257        sequence: u64,
10258        value: AvroValue,
10259    },
10260    VersionMarker {
10261        sequence: u64,
10262        change_id: String,
10263        version: i32,
10264    },
10265    Memo {
10266        sequence: u64,
10267        entries: AvroValue,
10268    },
10269}
10270
10271#[derive(Clone, Debug, PartialEq, Eq)]
10272struct SelectionMarker {
10273    selection_group_id: String,
10274    selection_group_base_sequence: u64,
10275    selection_group_size: usize,
10276    member_key: SelectionKey,
10277    member_index: usize,
10278    member_base_sequence: u64,
10279    member_size: usize,
10280    operation_kind: String,
10281    operation_identity: String,
10282    outcome: String,
10283    resolution_event_id: String,
10284    resolution_event_type: String,
10285}
10286
10287#[derive(Clone, Debug, PartialEq, Eq)]
10288struct SelectionCancellation {
10289    selection_group_id: String,
10290    member_key: SelectionKey,
10291    member_index: usize,
10292    member_base_sequence: u64,
10293    member_size: usize,
10294    operation_kind: String,
10295    operation_identity: String,
10296}
10297
10298fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
10299    let mut markers: Vec<SelectionMarker> = Vec::new();
10300    for event in events
10301        .iter()
10302        .filter(|event| event.event_type == "SelectionResolved")
10303    {
10304        let payload = &event.payload;
10305        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
10306        let group_size = required_selection_usize(payload, "selection_group_size")?;
10307        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
10308        let member_size = required_selection_usize(payload, "member_size")?;
10309        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
10310        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
10311            invalid_recorded_history(
10312                "selection_marker_invalid",
10313                base_sequence,
10314                "non-empty selection_group_id",
10315                &payload.to_string(),
10316                "selection winner history is missing its durable group identity",
10317            )
10318        })?;
10319        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
10320        if group_id != expected_group_id {
10321            return Err(invalid_recorded_history(
10322                "selection_marker_invalid",
10323                base_sequence,
10324                &expected_group_id,
10325                &group_id,
10326                "selection winner history contains an incompatible group identity",
10327            ));
10328        }
10329        let group_end = base_sequence
10330            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
10331            .unwrap_or(u64::MAX);
10332        let member_end = member_base_sequence
10333            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
10334            .unwrap_or(u64::MAX);
10335        if member_index >= group_size
10336            || member_base_sequence < base_sequence
10337            || member_end > group_end
10338        {
10339            return Err(invalid_recorded_history(
10340                "selection_marker_invalid",
10341                base_sequence,
10342                "winner member within selection group bounds",
10343                &payload.to_string(),
10344                "selection winner history contains an invalid member range",
10345            ));
10346        }
10347        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
10348            invalid_recorded_history(
10349                "selection_marker_invalid",
10350                base_sequence,
10351                "selection operation kind",
10352                &payload.to_string(),
10353                "selection winner history is missing its operation kind",
10354            )
10355        })?;
10356        if !matches!(
10357            operation_kind.as_str(),
10358            "activity" | "child" | "timer" | "signal" | "condition" | "group"
10359        ) {
10360            return Err(invalid_recorded_history(
10361                "selection_marker_invalid",
10362                base_sequence,
10363                "activity, child, timer, signal, condition, or group",
10364                &operation_kind,
10365                "selection winner history contains an unsupported operation kind",
10366            ));
10367        }
10368        let operation_identity =
10369            payload_string(payload, "operation_identity").ok_or_else(|| {
10370                invalid_recorded_history(
10371                    "selection_marker_invalid",
10372                    base_sequence,
10373                    "non-empty operation identity",
10374                    &payload.to_string(),
10375                    "selection winner history is missing its durable operation identity",
10376                )
10377            })?;
10378        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
10379            invalid_recorded_history(
10380                "selection_marker_invalid",
10381                base_sequence,
10382                "completed or failed selection outcome",
10383                &payload.to_string(),
10384                "selection winner history is missing its outcome",
10385            )
10386        })?;
10387        if !matches!(outcome.as_str(), "completed" | "failed") {
10388            return Err(invalid_recorded_history(
10389                "selection_marker_invalid",
10390                base_sequence,
10391                "completed or failed selection outcome",
10392                &outcome,
10393                "selection winner history contains an unsupported outcome",
10394            ));
10395        }
10396        let marker = SelectionMarker {
10397            selection_group_id: group_id,
10398            selection_group_base_sequence: base_sequence,
10399            selection_group_size: group_size,
10400            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
10401            member_index,
10402            member_base_sequence,
10403            member_size,
10404            operation_kind,
10405            operation_identity,
10406            outcome,
10407            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
10408                || {
10409                    invalid_recorded_history(
10410                        "selection_marker_invalid",
10411                        base_sequence,
10412                        "durable resolution_event_id",
10413                        &payload.to_string(),
10414                        "selection winner history is missing its terminal event identity",
10415                    )
10416                },
10417            )?,
10418            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
10419                || {
10420                    invalid_recorded_history(
10421                        "selection_marker_invalid",
10422                        base_sequence,
10423                        "durable resolution_event_type",
10424                        &payload.to_string(),
10425                        "selection winner history is missing its terminal event type",
10426                    )
10427                },
10428            )?,
10429        };
10430        if let Some(existing) = markers
10431            .iter()
10432            .find(|existing| existing.selection_group_id == marker.selection_group_id)
10433        {
10434            if existing != &marker {
10435                return Err(invalid_recorded_history(
10436                    "selection_marker_conflict",
10437                    base_sequence,
10438                    &format!("one winner for {}", marker.selection_group_id),
10439                    &payload.to_string(),
10440                    "selection history records conflicting winners for one durable group",
10441                ));
10442            }
10443            continue;
10444        }
10445        markers.push(marker);
10446    }
10447    Ok(markers)
10448}
10449
10450fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
10451    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
10452    for event in events
10453        .iter()
10454        .filter(|event| event.event_type == "SelectionOperationCancelled")
10455    {
10456        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
10457            invalid_recorded_history(
10458                "selection_cancellation_invalid",
10459                0,
10460                "non-empty selection_group_id",
10461                &event.payload.to_string(),
10462                "selection cancellation history is missing its group identity",
10463            )
10464        })?;
10465        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
10466        let marker = SelectionCancellation {
10467            selection_group_id: group_id,
10468            member_key: selection_key_from_value(
10469                event.payload.get("member_key"),
10470                member_base_sequence,
10471            )?,
10472            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
10473            member_base_sequence,
10474            member_size: required_selection_usize(&event.payload, "member_size")?,
10475            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
10476                invalid_recorded_history(
10477                    "selection_cancellation_invalid",
10478                    member_base_sequence,
10479                    "selection operation kind",
10480                    &event.payload.to_string(),
10481                    "selection cancellation is missing its operation kind",
10482                )
10483            })?,
10484            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
10485                || {
10486                    invalid_recorded_history(
10487                        "selection_cancellation_invalid",
10488                        member_base_sequence,
10489                        "selection operation identity",
10490                        &event.payload.to_string(),
10491                        "selection cancellation is missing its operation identity",
10492                    )
10493                },
10494            )?,
10495        };
10496        if let Some(existing) = cancelled.iter().find(|recorded| {
10497            recorded.selection_group_id == marker.selection_group_id
10498                && recorded.member_base_sequence == marker.member_base_sequence
10499        }) {
10500            if existing != &marker {
10501                return Err(invalid_recorded_history(
10502                    "selection_cancellation_conflict",
10503                    member_base_sequence,
10504                    "one stable SelectionOperationCancelled marker",
10505                    &event.payload.to_string(),
10506                    "selection cancellation history contains conflicting member metadata",
10507                ));
10508            }
10509        } else {
10510            cancelled.push(marker);
10511        }
10512    }
10513    Ok(cancelled)
10514}
10515
10516fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
10517    payload
10518        .get(field)
10519        .and_then(value_as_u64)
10520        .filter(|value| *value > 0)
10521        .ok_or_else(|| {
10522            invalid_recorded_history(
10523                "selection_marker_invalid",
10524                0,
10525                &format!("positive integer {field}"),
10526                &payload.to_string(),
10527                "selection history contains invalid durable identity metadata",
10528            )
10529        })
10530}
10531
10532fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
10533    required_selection_usize_allow_zero(payload, field).and_then(|value| {
10534        if value > 0 {
10535            Ok(value)
10536        } else {
10537            Err(invalid_recorded_history(
10538                "selection_marker_invalid",
10539                0,
10540                &format!("positive integer {field}"),
10541                &payload.to_string(),
10542                "selection history contains invalid durable identity metadata",
10543            ))
10544        }
10545    })
10546}
10547
10548fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
10549    payload
10550        .get(field)
10551        .and_then(value_as_u64)
10552        .and_then(|value| usize::try_from(value).ok())
10553        .ok_or_else(|| {
10554            invalid_recorded_history(
10555                "selection_marker_invalid",
10556                0,
10557                &format!("non-negative integer {field}"),
10558                &payload.to_string(),
10559                "selection history contains invalid durable identity metadata",
10560            )
10561        })
10562}
10563
10564#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
10565struct RecordedActivityOptions {
10566    task_queue: RecordedSnapshotValue<Option<String>>,
10567    execution_mode: RecordedSnapshotValue<Option<String>>,
10568    retry_policy: ActivityRetrySnapshot,
10569}
10570
10571#[derive(Clone, Debug)]
10572struct RecordedChildPolicies {
10573    parent_close_policy: String,
10574    cancellation_policy: String,
10575}
10576
10577fn recorded_activity_cancellation_policy(
10578    events: &[&HistoryEvent],
10579    sequence: u64,
10580) -> Result<String> {
10581    let mut policy: Option<String> = None;
10582    for event in events.iter().filter(|event| {
10583        matches!(
10584            event.event_type.as_str(),
10585            "ActivityScheduled"
10586                | "ActivityStarted"
10587                | "ActivityCompleted"
10588                | "ActivityFailed"
10589                | "ActivityTimedOut"
10590                | "ActivityCancelled"
10591        )
10592    }) {
10593        for source in [Some(&event.payload), event.payload.get("activity")]
10594            .into_iter()
10595            .flatten()
10596        {
10597            let Some(value) = source.get("cancellation_policy") else {
10598                continue;
10599            };
10600            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
10601                value.as_str()
10602            else {
10603                return Err(invalid_recorded_history(
10604                    "invalid_activity_cancellation_policy_history",
10605                    sequence,
10606                    "supported Activity cancellation policy",
10607                    &value.to_string(),
10608                    "Activity history contains an invalid cancellation policy",
10609                ));
10610            };
10611            if let Some(previous) = policy.as_deref() {
10612                if previous != incoming {
10613                    return Err(invalid_recorded_history(
10614                        "activity_cancellation_policy_history_conflict",
10615                        sequence,
10616                        previous,
10617                        incoming,
10618                        "Activity cancellation policy changed between history events",
10619                    ));
10620                }
10621            }
10622            policy = Some(incoming.to_string());
10623        }
10624        policy.get_or_insert_with(|| "try_cancel".to_string());
10625    }
10626    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
10627}
10628
10629fn recorded_child_policy_value<'a>(
10630    payload: &'a Value,
10631    field: &str,
10632    sequence: u64,
10633) -> Result<Option<&'a str>> {
10634    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
10635        return Ok(None);
10636    };
10637    let valid = match (field, value.as_str()) {
10638        (
10639            "parent_close_policy",
10640            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
10641        ) => true,
10642        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
10643            true
10644        }
10645        _ => false,
10646    };
10647    if !valid {
10648        return Err(invalid_recorded_history(
10649            "invalid_child_workflow_policy_history",
10650            sequence,
10651            "supported child workflow policy",
10652            &value.to_string(),
10653            "child workflow history contains an invalid policy",
10654        ));
10655    }
10656    Ok(value.as_str())
10657}
10658
10659fn recorded_child_policies(
10660    events: &[&HistoryEvent],
10661    scheduled: &HistoryEvent,
10662    sequence: u64,
10663) -> Result<RecordedChildPolicies> {
10664    let parent_close_policy =
10665        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
10666            .unwrap_or("abandon")
10667            .to_string();
10668    let cancellation_policy =
10669        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
10670            .unwrap_or("abandon")
10671            .to_string();
10672    for event in events {
10673        for (field, expected) in [
10674            ("parent_close_policy", parent_close_policy.as_str()),
10675            ("cancellation_policy", cancellation_policy.as_str()),
10676        ] {
10677            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
10678                if actual != expected {
10679                    return Err(invalid_recorded_history(
10680                        "child_workflow_policy_history_conflict",
10681                        sequence,
10682                        expected,
10683                        actual,
10684                        "child workflow policy changed between history events",
10685                    ));
10686                }
10687            }
10688        }
10689    }
10690    Ok(RecordedChildPolicies {
10691        parent_close_policy,
10692        cancellation_policy,
10693    })
10694}
10695
10696fn ensure_child_policies_match(
10697    sequence: u64,
10698    recorded: &RecordedChildPolicies,
10699    current: &ChildWorkflowOptions,
10700) -> Result<()> {
10701    for (field, expected, actual) in [
10702        (
10703            "parent_close_policy",
10704            recorded.parent_close_policy.as_str(),
10705            current.parent_close_policy.as_str(),
10706        ),
10707        (
10708            "cancellation_policy",
10709            recorded.cancellation_policy.as_str(),
10710            current.cancellation_policy.as_str(),
10711        ),
10712    ] {
10713        if expected != actual {
10714            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10715                "child_workflow_policy_changed",
10716                Some(sequence),
10717                Some(expected.to_string()),
10718                Some(actual.to_string()),
10719                format!("child workflow {field} changed during replay"),
10720            )));
10721        }
10722    }
10723    Ok(())
10724}
10725
10726#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
10727enum RecordedSnapshotValue<T> {
10728    /// Older history did not persist this field, so it cannot constrain replay.
10729    Unknown,
10730    Known(T),
10731}
10732
10733impl<T: PartialEq> RecordedSnapshotValue<T> {
10734    fn matches_current(&self, current: &Self) -> bool {
10735        match self {
10736            Self::Unknown => true,
10737            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
10738        }
10739    }
10740}
10741
10742#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
10743struct ActivityRetrySnapshot {
10744    snapshot_version: RecordedSnapshotValue<Option<u64>>,
10745    max_attempts: RecordedSnapshotValue<Option<u64>>,
10746    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
10747    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
10748    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
10749    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
10750    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
10751    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
10752}
10753
10754impl ActivityRetrySnapshot {
10755    fn matches_current(&self, current: &Self) -> bool {
10756        self.snapshot_version
10757            .matches_current(&current.snapshot_version)
10758            && self.max_attempts.matches_current(&current.max_attempts)
10759            && self
10760                .backoff_seconds
10761                .matches_current(&current.backoff_seconds)
10762            && self
10763                .start_to_close_timeout
10764                .matches_current(&current.start_to_close_timeout)
10765            && self
10766                .schedule_to_start_timeout
10767                .matches_current(&current.schedule_to_start_timeout)
10768            && self
10769                .schedule_to_close_timeout
10770                .matches_current(&current.schedule_to_close_timeout)
10771            && self
10772                .heartbeat_timeout
10773                .matches_current(&current.heartbeat_timeout)
10774            && self
10775                .non_retryable_error_types
10776                .matches_current(&current.non_retryable_error_types)
10777    }
10778}
10779
10780fn recorded_optional_u64(
10781    object: Option<&serde_json::Map<String, Value>>,
10782    field: &str,
10783) -> RecordedSnapshotValue<Option<u64>> {
10784    match object.and_then(|object| object.get(field)) {
10785        None => RecordedSnapshotValue::Unknown,
10786        Some(Value::Null) => RecordedSnapshotValue::Known(None),
10787        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
10788    }
10789}
10790
10791fn recorded_optional_string(
10792    object: &serde_json::Map<String, Value>,
10793    field: &str,
10794) -> RecordedSnapshotValue<Option<String>> {
10795    match object.get(field) {
10796        None => RecordedSnapshotValue::Unknown,
10797        Some(Value::Null) => RecordedSnapshotValue::Known(None),
10798        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
10799    }
10800}
10801
10802fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
10803    let policy = policy.and_then(Value::as_object);
10804    let backoff_seconds = policy
10805        .and_then(|policy| policy.get("backoff_seconds"))
10806        .and_then(Value::as_array)
10807        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
10808        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
10809    let mut non_retryable_error_types = Vec::new();
10810    for error_type in policy
10811        .and_then(|policy| policy.get("non_retryable_error_types"))
10812        .and_then(Value::as_array)
10813        .into_iter()
10814        .flatten()
10815        .filter_map(Value::as_str)
10816        .map(str::trim)
10817        .filter(|error_type| !error_type.is_empty())
10818    {
10819        if !non_retryable_error_types
10820            .iter()
10821            .any(|recorded| recorded == error_type)
10822        {
10823            non_retryable_error_types.push(error_type.to_string());
10824        }
10825    }
10826
10827    ActivityRetrySnapshot {
10828        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
10829        max_attempts: recorded_optional_u64(policy, "max_attempts"),
10830        backoff_seconds,
10831        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
10832        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
10833        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
10834        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
10835        non_retryable_error_types: if policy
10836            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
10837        {
10838            RecordedSnapshotValue::Known(non_retryable_error_types)
10839        } else {
10840            RecordedSnapshotValue::Unknown
10841        },
10842    }
10843}
10844
10845fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
10846    let policy = options.retry_policy.as_ref();
10847    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
10848        Some(Value::Null) => None,
10849        Some(value) => value_as_u64(value),
10850        None => Some(1),
10851    };
10852    let backoff_seconds = policy
10853        .and_then(|policy| policy.get("backoff_seconds"))
10854        .and_then(Value::as_array)
10855        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
10856        .unwrap_or_default();
10857    let non_retryable_error_types = policy
10858        .and_then(|policy| policy.get("non_retryable_error_types"))
10859        .and_then(Value::as_array)
10860        .into_iter()
10861        .flatten()
10862        .filter_map(Value::as_str)
10863        .map(str::to_string)
10864        .collect();
10865
10866    ActivityRetrySnapshot {
10867        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
10868        max_attempts: RecordedSnapshotValue::Known(max_attempts),
10869        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
10870        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
10871        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
10872        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
10873        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
10874        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
10875    }
10876}
10877
10878fn activity_options_description(options: &RecordedActivityOptions) -> String {
10879    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
10880}
10881
10882impl RecordedCommand {
10883    fn sequence(&self) -> u64 {
10884        match self {
10885            Self::CancellationGroup { sequence, .. }
10886            | Self::CancellationScope { sequence, .. }
10887            | Self::CancellationBoundary { sequence, .. }
10888            | Self::Activity { sequence, .. }
10889            | Self::Timer { sequence, .. }
10890            | Self::ChildWorkflow { sequence, .. }
10891            | Self::SignalWait { sequence, .. }
10892            | Self::ConditionWait { sequence, .. }
10893            | Self::SearchAttributes { sequence, .. }
10894            | Self::SideEffect { sequence, .. }
10895            | Self::VersionMarker { sequence, .. }
10896            | Self::Memo { sequence, .. } => *sequence,
10897        }
10898    }
10899
10900    fn shape(&self) -> &'static str {
10901        match self {
10902            Self::CancellationScope { .. } => "cancellation scope",
10903            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
10904                "cooperative cancellation"
10905            }
10906            Self::Activity { .. } => "activity",
10907            Self::Timer { .. } => "timer",
10908            Self::ChildWorkflow { .. } => "child workflow",
10909            Self::SignalWait { .. } => "signal wait",
10910            Self::ConditionWait { .. } => "condition wait",
10911            Self::SearchAttributes { .. } => "search-attribute update",
10912            Self::SideEffect { .. } => "side effect",
10913            Self::VersionMarker { .. } => "version marker",
10914            Self::Memo { .. } => "memo upsert",
10915        }
10916    }
10917}
10918
10919fn ensure_version_supported(
10920    change_id: &str,
10921    version: i32,
10922    min_supported: i32,
10923    max_supported: i32,
10924    sequence: u64,
10925) -> Result<()> {
10926    if (min_supported..=max_supported).contains(&version) {
10927        return Ok(());
10928    }
10929    Err(Error::NonDeterministicReplay(ReplayFailure::new(
10930        "version_marker_incompatible_range",
10931        (sequence != 0).then_some(sequence),
10932        Some(format!("{min_supported}..={max_supported}")),
10933        Some(format!("{change_id}:{version}")),
10934        "recorded workflow version is outside the range supported by current code",
10935    )))
10936}
10937
10938#[derive(Clone, Debug)]
10939struct ResumeSignal {
10940    signal_name: String,
10941    arguments: Vec<AvroValue>,
10942}
10943
10944const MAX_PARALLEL_OPERATIONS: usize = 1000;
10945
10946fn parallel_group_prefix(kind: &str) -> &'static str {
10947    match kind {
10948        "activity" => "parallel-activities",
10949        "child" => "parallel-children",
10950        "timer" => "parallel-timers",
10951        _ => "parallel-calls",
10952    }
10953}
10954
10955fn parallel_group_entry(
10956    base_sequence: u64,
10957    size: usize,
10958    index: usize,
10959    kind: &str,
10960) -> ParallelGroupMetadata {
10961    ParallelGroupMetadata {
10962        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
10963        parallel_group_kind: kind.to_string(),
10964        parallel_group_base_sequence: base_sequence,
10965        parallel_group_size: size,
10966        parallel_group_index: index,
10967        parallel_group_mode: None,
10968        selection_member_key: None,
10969        selection_member_index: None,
10970        selection_member_base_sequence: None,
10971        selection_member_size: None,
10972        selection_member_kind: None,
10973    }
10974}
10975
10976struct SelectionMemberMetadata {
10977    key: SelectionKey,
10978    index: usize,
10979    base_sequence: u64,
10980    size: usize,
10981    kind: String,
10982}
10983
10984fn selection_group_entry(
10985    base_sequence: u64,
10986    size: usize,
10987    index: usize,
10988    kind: &str,
10989    member: &SelectionMemberMetadata,
10990) -> ParallelGroupMetadata {
10991    ParallelGroupMetadata {
10992        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
10993        parallel_group_kind: kind.to_string(),
10994        parallel_group_base_sequence: base_sequence,
10995        parallel_group_size: size,
10996        parallel_group_index: index,
10997        parallel_group_mode: Some("select".to_string()),
10998        selection_member_key: Some(member.key.clone()),
10999        selection_member_index: Some(member.index),
11000        selection_member_base_sequence: Some(member.base_sequence),
11001        selection_member_size: Some(member.size),
11002        selection_member_kind: Some(member.kind.clone()),
11003    }
11004}
11005
11006fn apply_parallel_group_path(
11007    command: &mut serde_json::Map<String, Value>,
11008    path: &[ParallelGroupMetadata],
11009) {
11010    let Some(inner) = path.last() else {
11011        return;
11012    };
11013    command.insert(
11014        "parallel_group_id".to_string(),
11015        json!(inner.parallel_group_id),
11016    );
11017    command.insert(
11018        "parallel_group_kind".to_string(),
11019        json!(inner.parallel_group_kind),
11020    );
11021    command.insert(
11022        "parallel_group_base_sequence".to_string(),
11023        json!(inner.parallel_group_base_sequence),
11024    );
11025    command.insert(
11026        "parallel_group_size".to_string(),
11027        json!(inner.parallel_group_size),
11028    );
11029    command.insert(
11030        "parallel_group_index".to_string(),
11031        json!(inner.parallel_group_index),
11032    );
11033    if let Some(mode) = &inner.parallel_group_mode {
11034        command.insert("parallel_group_mode".to_string(), json!(mode));
11035    }
11036    if let Some(key) = &inner.selection_member_key {
11037        command.insert("selection_member_key".to_string(), json!(key));
11038    }
11039    if let Some(index) = inner.selection_member_index {
11040        command.insert("selection_member_index".to_string(), json!(index));
11041    }
11042    if let Some(base_sequence) = inner.selection_member_base_sequence {
11043        command.insert(
11044            "selection_member_base_sequence".to_string(),
11045            json!(base_sequence),
11046        );
11047    }
11048    if let Some(size) = inner.selection_member_size {
11049        command.insert("selection_member_size".to_string(), json!(size));
11050    }
11051    if let Some(kind) = &inner.selection_member_kind {
11052        command.insert("selection_member_kind".to_string(), json!(kind));
11053    }
11054    command.insert("parallel_group_path".to_string(), json!(path));
11055}
11056
11057fn ensure_parallel_path_matches(
11058    sequence: u64,
11059    recorded: Option<&[ParallelGroupMetadata]>,
11060    expected: &[ParallelGroupMetadata],
11061) -> Result<()> {
11062    match (recorded, expected.is_empty()) {
11063        (None, true) => Ok(()),
11064        (Some(recorded), false) if recorded == expected => Ok(()),
11065        (None, false) => Err(invalid_recorded_history(
11066            "parallel_group_metadata_missing",
11067            sequence,
11068            &serde_json::to_string(expected).unwrap_or_default(),
11069            "<missing>",
11070            "recorded parallel member is missing its durable group path",
11071        )),
11072        (Some(recorded), true) => Err(invalid_recorded_history(
11073            "parallel_group_shape_mismatch",
11074            sequence,
11075            "sequential command",
11076            &serde_json::to_string(recorded).unwrap_or_default(),
11077            "recorded command belonged to a parallel group but current code schedules it sequentially",
11078        )),
11079        (Some(recorded), false) => Err(invalid_recorded_history(
11080            "parallel_group_shape_mismatch",
11081            sequence,
11082            &serde_json::to_string(recorded).unwrap_or_default(),
11083            &serde_json::to_string(expected).unwrap_or_default(),
11084            "recorded parallel-group identity or path changed during replay",
11085        )),
11086    }
11087}
11088
11089#[derive(Clone, Debug)]
11090enum ParallelShape {
11091    Leaf,
11092    Group(Vec<ParallelShape>),
11093}
11094
11095struct ParallelDescriptor {
11096    operation: ParallelOperation,
11097    offset: usize,
11098    member_path: Vec<usize>,
11099    group_path: Vec<ParallelGroupMetadata>,
11100}
11101
11102fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
11103    operations
11104        .iter()
11105        .map(|operation| match operation {
11106            ParallelOperation::Group(children) => parallel_leaf_count(children),
11107            _ => 1,
11108        })
11109        .sum()
11110}
11111
11112fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
11113    match operation {
11114        ParallelOperation::Activity { .. } => Some("activity"),
11115        ParallelOperation::ChildWorkflow { .. } => Some("child"),
11116        ParallelOperation::Timer(_) => Some("timer"),
11117        ParallelOperation::Signal(_) => Some("signal"),
11118        ParallelOperation::Condition { .. } => Some("condition"),
11119        ParallelOperation::Group(children) => parallel_group_kind(children),
11120    }
11121}
11122
11123fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
11124    let mut kind = None;
11125    for operation in operations {
11126        let Some(operation_kind) = parallel_operation_kind(operation) else {
11127            continue;
11128        };
11129        match kind {
11130            None => kind = Some(operation_kind),
11131            Some(current) if current == operation_kind => {}
11132            Some(_) => return Some("mixed"),
11133        }
11134    }
11135    kind
11136}
11137
11138fn validate_parallel_operations(
11139    operations: &[ParallelOperation],
11140    member_path: &mut Vec<usize>,
11141    root: bool,
11142) -> Result<()> {
11143    let leaves = parallel_leaf_count(operations);
11144    if leaves > MAX_PARALLEL_OPERATIONS {
11145        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11146            reason: "fan_out_limit_exceeded",
11147            member_path: member_path.clone(),
11148            message: format!(
11149                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
11150            ),
11151        }));
11152    }
11153    if !root && operations.is_empty() {
11154        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11155            reason: "nested_group_empty",
11156            member_path: member_path.clone(),
11157            message: "a nested group must contain at least one durable leaf".to_string(),
11158        }));
11159    }
11160
11161    for (index, operation) in operations.iter().enumerate() {
11162        member_path.push(index);
11163        match operation {
11164            ParallelOperation::Activity {
11165                options, arguments, ..
11166            } => {
11167                options
11168                    .validate()
11169                    .map_err(|error| Error::InvalidActivityOptions(error))?;
11170                if let Err(error) = arguments {
11171                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11172                        reason: "arguments_invalid",
11173                        member_path: member_path.clone(),
11174                        message: error.to_string(),
11175                    }));
11176                }
11177            }
11178            ParallelOperation::ChildWorkflow {
11179                options, arguments, ..
11180            } => {
11181                validate_parallel_child_options(options)?;
11182                if let Err(error) = arguments {
11183                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11184                        reason: "arguments_invalid",
11185                        member_path: member_path.clone(),
11186                        message: error.to_string(),
11187                    }));
11188                }
11189            }
11190            ParallelOperation::Timer(duration)
11191                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
11192            {
11193                return Err(Error::TimerDurationOverflow);
11194            }
11195            ParallelOperation::Timer(_) => {}
11196            ParallelOperation::Signal(signal_name) => {
11197                validate_user_signal_name(signal_name)?;
11198                if signal_name.trim().is_empty() {
11199                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11200                        reason: "signal_name_empty",
11201                        member_path: member_path.clone(),
11202                        message: "signal wait name must not be empty".to_string(),
11203                    }));
11204                }
11205            }
11206            ParallelOperation::Condition { options, .. } => {
11207                options.validate()?;
11208            }
11209            ParallelOperation::Group(children) => {
11210                validate_parallel_operations(children, member_path, false)?;
11211            }
11212        }
11213        member_path.pop();
11214    }
11215    Ok(())
11216}
11217
11218fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
11219    if options.task_queue.trim().is_empty() {
11220        return Err(Error::InvalidChildWorkflowOptions(
11221            "task_queue must not be empty".to_string(),
11222        ));
11223    }
11224    for (name, value) in [
11225        (
11226            "execution_timeout_seconds",
11227            options.execution_timeout_seconds,
11228        ),
11229        ("run_timeout_seconds", options.run_timeout_seconds),
11230    ] {
11231        if value == Some(0) {
11232            return Err(Error::InvalidChildWorkflowOptions(format!(
11233                "{name} must be at least 1"
11234            )));
11235        }
11236    }
11237    if options
11238        .retry_policy
11239        .as_ref()
11240        .is_some_and(|policy| policy.max_attempts == Some(0))
11241    {
11242        return Err(Error::InvalidChildWorkflowOptions(
11243            "retry_policy.max_attempts must be at least 1".to_string(),
11244        ));
11245    }
11246    Ok(())
11247}
11248
11249fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
11250    ParallelShape::Group(
11251        operations
11252            .iter()
11253            .map(|operation| match operation {
11254                ParallelOperation::Group(children) => parallel_shape(children),
11255                _ => ParallelShape::Leaf,
11256            })
11257            .collect(),
11258    )
11259}
11260
11261fn parallel_descriptors(
11262    operations: Vec<ParallelOperation>,
11263    base_sequence: u64,
11264) -> Result<Vec<ParallelDescriptor>> {
11265    let size = parallel_leaf_count(&operations);
11266    let kind = parallel_group_kind(&operations).unwrap_or("activity");
11267    let mut descriptors = Vec::with_capacity(size);
11268    let mut cursor = 0;
11269
11270    for (index, operation) in operations.into_iter().enumerate() {
11271        match operation {
11272            ParallelOperation::Group(children) => {
11273                let child_base = base_sequence
11274                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
11275                    .ok_or(Error::TimerDurationOverflow)?;
11276                for mut descriptor in parallel_descriptors(children, child_base)? {
11277                    let outer_index = cursor + descriptor.offset;
11278                    descriptor.group_path.insert(
11279                        0,
11280                        parallel_group_entry(base_sequence, size, outer_index, kind),
11281                    );
11282                    descriptor.member_path.insert(0, index);
11283                    descriptor.offset = outer_index;
11284                    descriptors.push(descriptor);
11285                }
11286                cursor = descriptors.len();
11287            }
11288            operation => {
11289                descriptors.push(ParallelDescriptor {
11290                    operation,
11291                    offset: cursor,
11292                    member_path: vec![index],
11293                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
11294                });
11295                cursor += 1;
11296            }
11297        }
11298    }
11299    Ok(descriptors)
11300}
11301
11302enum ParallelLeafCall {
11303    Activity(ActivityCall),
11304    ChildWorkflow(ChildWorkflowCall),
11305    Timer(TimerCall),
11306    Signal(SignalCall),
11307    Condition(ConditionWaitCall),
11308}
11309
11310fn parallel_leaf_call(
11311    ctx: &WorkflowContext,
11312    operation: ParallelOperation,
11313    parallel_group_path: Vec<ParallelGroupMetadata>,
11314) -> ParallelLeafCall {
11315    match operation {
11316        ParallelOperation::Activity {
11317            activity_type,
11318            options,
11319            arguments,
11320        } => ParallelLeafCall::Activity(ActivityCall {
11321            ctx: ctx.clone(),
11322            activity_type,
11323            options,
11324            args: Some(arguments),
11325            scheduled: false,
11326            parallel_group_path,
11327        }),
11328        ParallelOperation::ChildWorkflow {
11329            workflow_type,
11330            options,
11331            arguments,
11332        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
11333            ctx: ctx.clone(),
11334            workflow_type,
11335            options,
11336            args: Some(arguments),
11337            scheduled: false,
11338            matched_pending: false,
11339            parallel_group_path,
11340        }),
11341        ParallelOperation::Timer(duration) => {
11342            let delay_seconds = duration
11343                .as_secs()
11344                .checked_add(u64::from(duration.subsec_nanos() > 0));
11345            ParallelLeafCall::Timer(TimerCall {
11346                ctx: ctx.clone(),
11347                delay_seconds,
11348                scheduled: false,
11349                matched_pending: false,
11350                parallel_group_path,
11351            })
11352        }
11353        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
11354            ctx: ctx.clone(),
11355            signal_name,
11356            runtime_reserved_allowed: false,
11357            opened_wait: false,
11358            matched_pending: false,
11359            parallel_group_path,
11360        }),
11361        ParallelOperation::Condition { options, predicate } => {
11362            ParallelLeafCall::Condition(ConditionWaitCall {
11363                ctx: ctx.clone(),
11364                options,
11365                predicate,
11366                occurrence_id: None,
11367                opened_wait: false,
11368                parallel_group_path,
11369            })
11370        }
11371        ParallelOperation::Group(_) => {
11372            unreachable!("parallel descriptors contain only durable leaves")
11373        }
11374    }
11375}
11376
11377impl ParallelLeafCall {
11378    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
11379        match self {
11380            Self::Activity(call) => Pin::new(call)
11381                .poll_avro_value(cx)
11382                .map_ok(ParallelAvroResult::Activity),
11383            Self::ChildWorkflow(call) => Pin::new(call)
11384                .poll_avro_value(cx)
11385                .map_ok(ParallelAvroResult::ChildWorkflow),
11386            Self::Timer(call) => Pin::new(call)
11387                .poll(cx)
11388                .map_ok(|()| ParallelAvroResult::Timer),
11389            Self::Signal(call) => Pin::new(call)
11390                .poll_avro_value(cx)
11391                .map_ok(ParallelAvroResult::Signal),
11392            Self::Condition(call) => Pin::new(call)
11393                .poll(cx)
11394                .map_ok(ParallelAvroResult::Condition),
11395        }
11396    }
11397}
11398
11399struct ParallelLeaf {
11400    call: ParallelLeafCall,
11401    sequence: u64,
11402    member_path: Vec<usize>,
11403    group_path: Vec<ParallelGroupMetadata>,
11404    result: Option<ParallelAvroResult>,
11405}
11406
11407/// Future returned by [`WorkflowContext::parallel`].
11408pub struct ParallelCall {
11409    ctx: WorkflowContext,
11410    operations: Option<Vec<ParallelOperation>>,
11411    shape: Option<ParallelShape>,
11412    leaves: Vec<ParallelLeaf>,
11413    pending_scope_delivery: bool,
11414}
11415
11416impl ParallelCall {
11417    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
11418        Self {
11419            ctx,
11420            operations: Some(operations),
11421            shape: None,
11422            leaves: Vec::new(),
11423            pending_scope_delivery: false,
11424        }
11425    }
11426
11427    fn initialize(&mut self) -> Result<()> {
11428        let operations = self.operations.take().unwrap_or_default();
11429        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
11430        self.shape = Some(parallel_shape(&operations));
11431        if operations.is_empty() {
11432            return Ok(());
11433        }
11434
11435        let base_sequence = {
11436            let state = self
11437                .ctx
11438                .state
11439                .lock()
11440                .map_err(|_| Error::WorkflowStatePoisoned)?;
11441            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
11442                recorded.sequence()
11443            } else {
11444                let last = state
11445                    .recorded_commands
11446                    .last()
11447                    .map(RecordedCommand::sequence)
11448                    .unwrap_or(0);
11449                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
11450                    .and_then(|sequence| sequence.checked_add(1))
11451                    .ok_or_else(|| {
11452                        Error::InvalidParallelGroup(ParallelGroupError {
11453                            reason: "sequence_overflow",
11454                            member_path: Vec::new(),
11455                            message: "parallel group sequence identity overflowed u64".to_string(),
11456                        })
11457                    })?
11458            }
11459        };
11460
11461        let descriptors = parallel_descriptors(operations, base_sequence)?;
11462        {
11463            let mut state = self
11464                .ctx
11465                .state
11466                .lock()
11467                .map_err(|_| Error::WorkflowStatePoisoned)?;
11468            let cursor = state.command_cursor;
11469            self.ctx.validate_scope_membership(&mut state, cursor)?;
11470            if state.prepare_parallel_scope_cancellation(&descriptors)? {
11471                self.pending_scope_delivery = true;
11472                return Ok(());
11473            }
11474            state.expand_cancellation_group(&descriptors)?;
11475            state.prepare_group_cancellation(&descriptors)?;
11476        }
11477        self.leaves = descriptors
11478            .into_iter()
11479            .map(|descriptor| {
11480                let call = parallel_leaf_call(
11481                    &self.ctx,
11482                    descriptor.operation,
11483                    descriptor.group_path.clone(),
11484                );
11485                ParallelLeaf {
11486                    call,
11487                    sequence: base_sequence + descriptor.offset as u64,
11488                    member_path: descriptor.member_path,
11489                    group_path: descriptor.group_path,
11490                    result: None,
11491                }
11492            })
11493            .collect();
11494        Ok(())
11495    }
11496
11497    fn poll_avro_value(
11498        mut self: Pin<&mut Self>,
11499        cx: &mut TaskContext<'_>,
11500    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
11501        if self.operations.is_some() {
11502            if let Err(error) = self.initialize() {
11503                return Poll::Ready(Err(error));
11504            }
11505        }
11506        if self.pending_scope_delivery {
11507            return Poll::Pending;
11508        }
11509        if self.leaves.is_empty() {
11510            return Poll::Ready(Ok(Vec::new()));
11511        }
11512
11513        let mut failures = Vec::new();
11514        let mut pending = false;
11515        for (index, leaf) in self.leaves.iter_mut().enumerate() {
11516            if leaf.result.is_some() {
11517                continue;
11518            }
11519            match leaf.call.poll_avro_value(cx) {
11520                Poll::Ready(Ok(result)) => leaf.result = Some(result),
11521                Poll::Ready(Err(error)) => failures.push((index, error)),
11522                Poll::Pending => pending = true,
11523            }
11524        }
11525
11526        if !failures.is_empty() {
11527            if let Some(position) = failures
11528                .iter()
11529                .position(|(_, error)| workflow_task_integrity_error(error))
11530            {
11531                return Poll::Ready(Err(failures.remove(position).1));
11532            }
11533            if self
11534                .ctx
11535                .state
11536                .lock()
11537                .map_err(|_| Error::WorkflowStatePoisoned)?
11538                .cancellation_delivery_intent
11539                .is_some()
11540            {
11541                return Poll::Pending;
11542            }
11543            if let Some(position) = failures
11544                .iter()
11545                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
11546            {
11547                return Poll::Ready(Err(failures.remove(position).1));
11548            }
11549            failures.sort_by_key(|(index, _)| *index);
11550            let (failed_index, cause) = failures.remove(0);
11551            let failed = &self.leaves[failed_index];
11552            let completed = self
11553                .leaves
11554                .iter()
11555                .filter_map(|leaf| {
11556                    leaf.result
11557                        .clone()
11558                        .and_then(|result| result.into_json_result().ok())
11559                        .map(|result| ParallelCompletion {
11560                            member_path: leaf.member_path.clone(),
11561                            result,
11562                        })
11563                })
11564                .collect();
11565            let group_id = failed
11566                .group_path
11567                .first()
11568                .map(|entry| entry.parallel_group_id.clone())
11569                .unwrap_or_default();
11570            let sequences = self
11571                .leaves
11572                .iter()
11573                .map(|leaf| leaf.sequence)
11574                .collect::<Vec<_>>();
11575            self.ctx
11576                .state
11577                .lock()
11578                .map_err(|_| Error::WorkflowStatePoisoned)?
11579                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
11580            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
11581                group_id,
11582                member_path: failed.member_path.clone(),
11583                group_path: failed.group_path.clone(),
11584                completed,
11585                cause: Box::new(cause),
11586            })));
11587        }
11588        if pending
11589            || self
11590                .ctx
11591                .state
11592                .lock()
11593                .map_err(|_| Error::WorkflowStatePoisoned)?
11594                .cancellation_delivery_intent
11595                .is_some()
11596        {
11597            return Poll::Pending;
11598        }
11599
11600        let mut flat_results = self
11601            .leaves
11602            .iter_mut()
11603            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
11604            .collect::<Vec<_>>()
11605            .into_iter();
11606        let results = parallel_results_for_shape(
11607            self.shape.as_ref().expect("initialized parallel shape"),
11608            &mut flat_results,
11609        );
11610        let sequences = self
11611            .leaves
11612            .iter()
11613            .map(|leaf| leaf.sequence)
11614            .collect::<Vec<_>>();
11615        self.ctx
11616            .state
11617            .lock()
11618            .map_err(|_| Error::WorkflowStatePoisoned)?
11619            .advance_cancellation_sequences(&sequences, None);
11620        Poll::Ready(Ok(match results {
11621            ParallelAvroResult::Group(results) => results,
11622            ParallelAvroResult::Activity(_)
11623            | ParallelAvroResult::ChildWorkflow(_)
11624            | ParallelAvroResult::Timer
11625            | ParallelAvroResult::Signal(_)
11626            | ParallelAvroResult::Condition(_) => {
11627                unreachable!("root parallel shape is a group")
11628            }
11629        }))
11630    }
11631}
11632
11633fn parallel_results_for_shape(
11634    shape: &ParallelShape,
11635    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
11636) -> ParallelAvroResult {
11637    match shape {
11638        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
11639        ParallelShape::Group(children) => ParallelAvroResult::Group(
11640            children
11641                .iter()
11642                .map(|child| parallel_results_for_shape(child, flat_results))
11643                .collect(),
11644        ),
11645    }
11646}
11647
11648impl Future for ParallelCall {
11649    type Output = Result<Vec<ParallelResult>>;
11650
11651    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
11652        self.poll_avro_value(cx)
11653            .map_ok(|results| {
11654                results
11655                    .into_iter()
11656                    .map(ParallelAvroResult::into_json_result)
11657                    .collect::<Result<Vec<_>>>()
11658            })
11659            .map_ok(|result| result)
11660            .flatten_result()
11661    }
11662}
11663
11664#[derive(Clone, Debug)]
11665struct SelectionMemberPlan {
11666    key: SelectionKey,
11667    index: usize,
11668    base_sequence: u64,
11669    size: usize,
11670    kind: String,
11671    shape: ParallelShape,
11672    leaf_start: usize,
11673}
11674
11675fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
11676    match operation {
11677        ParallelOperation::Activity { .. } => "activity",
11678        ParallelOperation::ChildWorkflow { .. } => "child",
11679        ParallelOperation::Timer(_) => "timer",
11680        ParallelOperation::Signal(_) => "signal",
11681        ParallelOperation::Condition { .. } => "condition",
11682        ParallelOperation::Group(_) => "group",
11683    }
11684}
11685
11686fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
11687    match operation {
11688        ParallelOperation::Group(children) => parallel_shape(children),
11689        _ => ParallelShape::Leaf,
11690    }
11691}
11692
11693fn selection_descriptors(
11694    operations: Vec<(SelectionKey, ParallelOperation)>,
11695    base_sequence: u64,
11696) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
11697    if operations.is_empty() {
11698        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11699            reason: "selection_empty",
11700            member_path: Vec::new(),
11701            message: "durable selection requires at least one operation".to_string(),
11702        }));
11703    }
11704    let operation_refs = operations
11705        .iter()
11706        .map(|(_, operation)| operation)
11707        .collect::<Vec<_>>();
11708    let total_size = operation_refs
11709        .iter()
11710        .map(|operation| match operation {
11711            ParallelOperation::Group(children) => parallel_leaf_count(children),
11712            _ => 1,
11713        })
11714        .sum::<usize>();
11715    if total_size > MAX_PARALLEL_OPERATIONS {
11716        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11717            reason: "fan_out_limit_exceeded",
11718            member_path: Vec::new(),
11719            message: format!(
11720                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
11721            ),
11722        }));
11723    }
11724    let group_kind = {
11725        let mut kind = None;
11726        for operation in &operation_refs {
11727            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
11728            match kind {
11729                None => kind = Some(operation_kind),
11730                Some(current) if current == operation_kind => {}
11731                Some(_) => {
11732                    kind = Some("mixed");
11733                    break;
11734                }
11735            }
11736        }
11737        kind.unwrap_or("mixed")
11738    };
11739
11740    let mut descriptors = Vec::with_capacity(total_size);
11741    let mut members = Vec::with_capacity(operations.len());
11742    let mut cursor = 0usize;
11743    let mut seen_keys: Vec<SelectionKey> = Vec::new();
11744    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
11745        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
11746            return Err(Error::InvalidParallelGroup(ParallelGroupError {
11747                reason: "selection_key_invalid",
11748                member_path: vec![member_index],
11749                message: "selection member keys must be non-empty strings or non-negative integers"
11750                    .to_string(),
11751            }));
11752        }
11753        if seen_keys.contains(&key) {
11754            return Err(Error::InvalidParallelGroup(ParallelGroupError {
11755                reason: "selection_key_duplicate",
11756                member_path: vec![member_index],
11757                message: format!("selection member key {key:?} is duplicated"),
11758            }));
11759        }
11760        seen_keys.push(key.clone());
11761        let member_size = match &operation {
11762            ParallelOperation::Group(children) => parallel_leaf_count(children),
11763            _ => 1,
11764        };
11765        if member_size == 0 {
11766            return Err(Error::InvalidParallelGroup(ParallelGroupError {
11767                reason: "selection_member_empty",
11768                member_path: vec![member_index],
11769                message: "a selection member must contain at least one durable leaf".to_string(),
11770            }));
11771        }
11772        let member_base = base_sequence
11773            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
11774            .ok_or(Error::TimerDurationOverflow)?;
11775        let member_kind = selection_operation_kind(&operation).to_string();
11776        let member_shape = selection_operation_shape(&operation);
11777        let leaf_start = descriptors.len();
11778        match operation {
11779            ParallelOperation::Group(children) => {
11780                validate_parallel_operations(&children, &mut vec![member_index], false)?;
11781                for mut descriptor in parallel_descriptors(children, member_base)? {
11782                    let flat_index = cursor + descriptor.offset;
11783                    descriptor.group_path.insert(
11784                        0,
11785                        selection_group_entry(
11786                            base_sequence,
11787                            total_size,
11788                            flat_index,
11789                            group_kind,
11790                            &SelectionMemberMetadata {
11791                                key: key.clone(),
11792                                index: member_index,
11793                                base_sequence: member_base,
11794                                size: member_size,
11795                                kind: member_kind.clone(),
11796                            },
11797                        ),
11798                    );
11799                    descriptor.member_path.insert(0, member_index);
11800                    descriptor.offset = flat_index;
11801                    descriptors.push(descriptor);
11802                }
11803            }
11804            operation => {
11805                validate_parallel_operations(
11806                    std::slice::from_ref(&operation),
11807                    &mut Vec::new(),
11808                    true,
11809                )?;
11810                descriptors.push(ParallelDescriptor {
11811                    operation,
11812                    offset: cursor,
11813                    member_path: vec![member_index],
11814                    group_path: vec![selection_group_entry(
11815                        base_sequence,
11816                        total_size,
11817                        cursor,
11818                        group_kind,
11819                        &SelectionMemberMetadata {
11820                            key: key.clone(),
11821                            index: member_index,
11822                            base_sequence: member_base,
11823                            size: member_size,
11824                            kind: member_kind.clone(),
11825                        },
11826                    )],
11827                });
11828            }
11829        }
11830        members.push(SelectionMemberPlan {
11831            key,
11832            index: member_index,
11833            base_sequence: member_base,
11834            size: member_size,
11835            kind: member_kind,
11836            shape: member_shape,
11837            leaf_start,
11838        });
11839        cursor += member_size;
11840    }
11841    Ok((descriptors, members))
11842}
11843
11844struct SelectionLeaf {
11845    call: ParallelLeafCall,
11846    outcome: Option<Result<ParallelAvroResult>>,
11847}
11848
11849/// Stable reference to one member of a durable selection group.
11850#[derive(Clone)]
11851pub struct DurableOperationHandle {
11852    ctx: WorkflowContext,
11853    pub key: SelectionKey,
11854    pub index: usize,
11855    pub kind: String,
11856    pub identity: String,
11857    pub base_sequence: u64,
11858    pub size: usize,
11859    pub selection_group_id: String,
11860    shape: ParallelShape,
11861}
11862
11863impl std::fmt::Debug for DurableOperationHandle {
11864    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11865        formatter
11866            .debug_struct("DurableOperationHandle")
11867            .field("key", &self.key)
11868            .field("index", &self.index)
11869            .field("kind", &self.kind)
11870            .field("identity", &self.identity)
11871            .field("base_sequence", &self.base_sequence)
11872            .field("size", &self.size)
11873            .field("selection_group_id", &self.selection_group_id)
11874            .finish()
11875    }
11876}
11877
11878impl DurableOperationHandle {
11879    /// Await this member after another member has already won the selection.
11880    pub fn await_result(&self) -> DurableOperationAwaitCall {
11881        DurableOperationAwaitCall {
11882            handle: self.clone(),
11883        }
11884    }
11885
11886    /// Request cancellation without affecting siblings. The future resolves
11887    /// to unit; only `SelectionOperationCancelled` history proves cancellation
11888    /// beat a concurrently committed terminal result.
11889    pub fn cancel(&self) -> CancelDurableOperationCall {
11890        CancelDurableOperationCall {
11891            handle: self.clone(),
11892            emitted: false,
11893        }
11894    }
11895}
11896
11897/// The one winner committed for a durable selection group.
11898#[derive(Debug)]
11899pub struct SelectionResult {
11900    pub key: SelectionKey,
11901    pub index: usize,
11902    pub kind: String,
11903    pub identity: String,
11904    pub value: Option<ParallelResult>,
11905    pub failure: Option<Error>,
11906    pub winner: DurableOperationHandle,
11907    pub handles: Vec<DurableOperationHandle>,
11908}
11909
11910impl SelectionResult {
11911    pub fn succeeded(&self) -> bool {
11912        self.failure.is_none()
11913    }
11914
11915    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
11916        self.handles.iter().find(|handle| &handle.key == key)
11917    }
11918
11919    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
11920        self.handles
11921            .iter()
11922            .filter(|handle| handle.index != self.index)
11923            .collect()
11924    }
11925
11926    pub fn into_result(self) -> Result<ParallelResult> {
11927        match (self.value, self.failure) {
11928            (Some(value), None) => Ok(value),
11929            (_, Some(error)) => Err(error),
11930            _ => Err(Error::WorkerLoop(
11931                "selection result contained neither a value nor a failure".to_string(),
11932            )),
11933        }
11934    }
11935}
11936
11937/// Future returned by [`WorkflowContext::select`].
11938pub struct SelectCall {
11939    ctx: WorkflowContext,
11940    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
11941    members: Vec<SelectionMemberPlan>,
11942    leaves: Vec<SelectionLeaf>,
11943    group_id: Option<String>,
11944}
11945
11946impl SelectCall {
11947    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
11948        Self {
11949            ctx,
11950            operations: Some(operations),
11951            members: Vec::new(),
11952            leaves: Vec::new(),
11953            group_id: None,
11954        }
11955    }
11956
11957    fn initialize(&mut self) -> Result<()> {
11958        let operations = self.operations.take().unwrap_or_default();
11959        let base_sequence = {
11960            let state = self
11961                .ctx
11962                .state
11963                .lock()
11964                .map_err(|_| Error::WorkflowStatePoisoned)?;
11965            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
11966                state.recorded_commands.get(state.command_cursor)
11967            {
11968                *sequence
11969            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
11970            {
11971                marker.selection_group_base_sequence
11972            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
11973                recorded.sequence()
11974            } else {
11975                let last = state
11976                    .recorded_commands
11977                    .last()
11978                    .map(RecordedCommand::sequence)
11979                    .unwrap_or(0);
11980                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
11981                    .and_then(|sequence| sequence.checked_add(1))
11982                    .ok_or(Error::TimerDurationOverflow)?
11983            }
11984        };
11985        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
11986        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
11987        {
11988            let mut state = self
11989                .ctx
11990                .state
11991                .lock()
11992                .map_err(|_| Error::WorkflowStatePoisoned)?;
11993            state.expand_cancellation_group(&descriptors)?;
11994            state.prepare_group_cancellation(&descriptors)?;
11995        }
11996        self.leaves = descriptors
11997            .into_iter()
11998            .map(|descriptor| SelectionLeaf {
11999                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
12000                outcome: None,
12001            })
12002            .collect();
12003        self.members = members;
12004        self.group_id = Some(group_id);
12005        Ok(())
12006    }
12007}
12008
12009impl Future for SelectCall {
12010    type Output = Result<SelectionResult>;
12011
12012    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12013        if self.operations.is_some() {
12014            if let Err(error) = self.initialize() {
12015                return Poll::Ready(Err(error));
12016            }
12017        }
12018
12019        for leaf in &mut self.leaves {
12020            if leaf.outcome.is_some() {
12021                continue;
12022            }
12023            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
12024                if outcome
12025                    .as_ref()
12026                    .err()
12027                    .is_some_and(workflow_task_integrity_error)
12028                {
12029                    return Poll::Ready(outcome.map(|_| unreachable!()));
12030                }
12031                leaf.outcome = Some(outcome);
12032            }
12033        }
12034
12035        if self
12036            .ctx
12037            .state
12038            .lock()
12039            .map_err(|_| Error::WorkflowStatePoisoned)?
12040            .cancellation_delivery_intent
12041            .is_some()
12042        {
12043            return Poll::Pending;
12044        }
12045
12046        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
12047            matches!(
12048                leaf.outcome,
12049                Some(Err(Error::CooperativeCancellationRequested(_)))
12050            )
12051        }) {
12052            return Poll::Ready(
12053                leaf.outcome
12054                    .take()
12055                    .expect("matched cancellation")
12056                    .map(|_| unreachable!()),
12057            );
12058        }
12059
12060        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
12061        let selection_member_range = self
12062            .members
12063            .first()
12064            .map(|member| member.base_sequence)
12065            .zip(self.leaves.len().try_into().ok())
12066            .map(|(base_sequence, size): (u64, u64)| {
12067                base_sequence..base_sequence.saturating_add(size)
12068            });
12069        let marker = {
12070            let mut state = match self.ctx.state.lock() {
12071                Ok(state) => state,
12072                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12073            };
12074            let marker = state
12075                .selection_markers
12076                .get(state.selection_marker_cursor)
12077                .cloned();
12078            if marker.is_none()
12079                && all_members_terminal
12080                && selection_member_range.as_ref().is_some_and(|member_range| {
12081                    state
12082                        .recorded_commands
12083                        .iter()
12084                        .any(|command| member_range.contains(&command.sequence()))
12085                })
12086            {
12087                // Terminal member history can be committed before the server's
12088                // SelectionResolved marker becomes visible to this task. That
12089                // marker is the durable barrier the selection is still waiting
12090                // on, so an otherwise commandless replay remains legitimately
12091                // pending instead of failing as an untracked yield.
12092                state.matched_recorded_pending = true;
12093            }
12094            marker
12095        };
12096        let Some(marker) = marker else {
12097            return Poll::Pending;
12098        };
12099        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
12100            || marker.selection_group_size != self.leaves.len()
12101            || self.members.first().map(|member| member.base_sequence)
12102                != Some(marker.selection_group_base_sequence)
12103        {
12104            return Poll::Ready(Err(invalid_recorded_history(
12105                "selection_group_shape_mismatch",
12106                marker.selection_group_base_sequence,
12107                self.group_id
12108                    .as_deref()
12109                    .unwrap_or("initialized selection group"),
12110                &marker.selection_group_id,
12111                "recorded selection group differs from current workflow code",
12112            )));
12113        }
12114        let Some(member_position) = self.members.iter().position(|member| {
12115            member.key == marker.member_key
12116                && member.index == marker.member_index
12117                && member.base_sequence == marker.member_base_sequence
12118                && member.size == marker.member_size
12119                && member.kind == marker.operation_kind
12120        }) else {
12121            return Poll::Ready(Err(invalid_recorded_history(
12122                "selection_member_shape_mismatch",
12123                marker.member_base_sequence,
12124                "winner member matching current workflow code",
12125                &format!("{:?}", marker.member_key),
12126                "recorded selection winner differs from the authored member identity",
12127            )));
12128        };
12129        let member = self.members[member_position].clone();
12130        let (handles, resolution_sequence) = {
12131            let mut state = match self.ctx.state.lock() {
12132                Ok(state) => state,
12133                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12134            };
12135            let identities = self
12136                .members
12137                .iter()
12138                .map(|candidate| {
12139                    selection_operation_identity(
12140                        &state,
12141                        &candidate.kind,
12142                        candidate.base_sequence,
12143                        candidate.size,
12144                    )
12145                })
12146                .collect::<Vec<_>>();
12147            if let Some((position, missing)) = identities
12148                .iter()
12149                .enumerate()
12150                .find(|(_, identity)| identity.is_empty())
12151                .map(|(position, identity)| (position, identity.clone()))
12152            {
12153                let candidate = &self.members[position];
12154                return Poll::Ready(Err(invalid_recorded_history(
12155                    "selection_operation_identity_missing",
12156                    candidate.base_sequence,
12157                    &format!(
12158                        "durable {} resource identity from scheduled/open history",
12159                        candidate.kind
12160                    ),
12161                    &missing,
12162                    "selection member history is missing its canonical durable identity",
12163                )));
12164            }
12165            let expected_winner_identity = &identities[member_position];
12166            let resolution_sequence = match validated_selection_resolution_sequence(
12167                &state,
12168                &marker,
12169                &member,
12170                expected_winner_identity,
12171            ) {
12172                Ok(sequence) => sequence,
12173                Err(error) => return Poll::Ready(Err(error)),
12174            };
12175            let handles = self
12176                .members
12177                .iter()
12178                .zip(identities)
12179                .map(|(member, identity)| DurableOperationHandle {
12180                    ctx: self.ctx.clone(),
12181                    key: member.key.clone(),
12182                    index: member.index,
12183                    kind: member.kind.clone(),
12184                    identity,
12185                    base_sequence: member.base_sequence,
12186                    size: member.size,
12187                    selection_group_id: marker.selection_group_id.clone(),
12188                    shape: member.shape.clone(),
12189                })
12190                .collect::<Vec<_>>();
12191            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
12192                return Poll::Ready(Err(error));
12193            }
12194            state.selection_marker_cursor += 1;
12195            (handles, resolution_sequence)
12196        };
12197
12198        let mut winner_failure = None;
12199        let mut flat_results = Vec::with_capacity(member.size);
12200        if marker.outcome == "failed" {
12201            let resolution_offset = match resolution_sequence
12202                .checked_sub(member.base_sequence)
12203                .and_then(|offset| usize::try_from(offset).ok())
12204            {
12205                Some(offset) if offset < member.size => offset,
12206                _ => {
12207                    return Poll::Ready(Err(invalid_recorded_history(
12208                        "selection_resolution_event_mismatch",
12209                        member.base_sequence,
12210                        "failure event within selected member bounds",
12211                        &resolution_sequence.to_string(),
12212                        "selection failure event is outside the authored member",
12213                    )))
12214                }
12215            };
12216            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
12217            match leaf.outcome.take() {
12218                Some(Err(error)) => winner_failure = Some(error),
12219                _ => {
12220                    return Poll::Ready(Err(invalid_recorded_history(
12221                        "selection_winner_outcome_mismatch",
12222                        member.base_sequence,
12223                        "exact failed terminal history referenced by SelectionResolved",
12224                        "missing or successful resolution event",
12225                        "selection winner marker disagrees with terminal operation history",
12226                    )))
12227                }
12228            }
12229        } else {
12230            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
12231                match leaf.outcome.take() {
12232                    Some(Ok(result)) => flat_results.push(result),
12233                    Some(Err(_)) => {
12234                        return Poll::Ready(Err(invalid_recorded_history(
12235                            "selection_winner_outcome_mismatch",
12236                            member.base_sequence,
12237                            "fully completed nested selection member",
12238                            "failed durable leaf",
12239                            "completed selection winner contains a failed leaf",
12240                        )))
12241                    }
12242                    None => {
12243                        return Poll::Ready(Err(invalid_recorded_history(
12244                            "selection_winner_unresolved",
12245                            member.base_sequence,
12246                            "terminal history for every completed winner leaf",
12247                            "pending member history",
12248                            "completed SelectionResolved member has an unfinished durable barrier",
12249                        )))
12250                    }
12251                }
12252            }
12253        }
12254        let value = if winner_failure.is_none() {
12255            let mut flat_results = flat_results.into_iter();
12256            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
12257            match value.into_json_result() {
12258                Ok(value) => Some(value),
12259                Err(error) => return Poll::Ready(Err(error)),
12260            }
12261        } else {
12262            None
12263        };
12264        let winner = handles[member_position].clone();
12265        self.ctx
12266            .state
12267            .lock()
12268            .map_err(|_| Error::WorkflowStatePoisoned)?
12269            .advance_cancellation_selection(&marker.selection_group_id);
12270        Poll::Ready(Ok(SelectionResult {
12271            key: winner.key.clone(),
12272            index: winner.index,
12273            kind: winner.kind.clone(),
12274            identity: winner.identity.clone(),
12275            value,
12276            failure: winner_failure,
12277            winner,
12278            handles,
12279        }))
12280    }
12281}
12282
12283fn selection_operation_identity(
12284    state: &WorkflowState,
12285    kind: &str,
12286    base_sequence: u64,
12287    size: usize,
12288) -> String {
12289    if kind == "group" {
12290        return format!("group:{base_sequence}:{size}");
12291    }
12292    let fields: &[&str] = match kind {
12293        "activity" => &["activity_execution_id"],
12294        "child" => &["child_workflow_run_id"],
12295        "timer" => &["timer_id"],
12296        "signal" => &["signal_wait_id"],
12297        "condition" => &["condition_wait_id"],
12298        _ => &[],
12299    };
12300    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
12301        for event in state
12302            .history_events
12303            .iter()
12304            .filter(|event| durable_event_sequence(event) == Some(sequence))
12305        {
12306            for field in fields {
12307                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
12308                    if !identity.is_empty() {
12309                        return identity.to_string();
12310                    }
12311                }
12312            }
12313        }
12314    }
12315    String::new()
12316}
12317
12318fn validated_selection_resolution_sequence(
12319    state: &WorkflowState,
12320    marker: &SelectionMarker,
12321    member: &SelectionMemberPlan,
12322    expected_identity: &str,
12323) -> Result<u64> {
12324    if expected_identity.is_empty() {
12325        return Err(invalid_recorded_history(
12326            "selection_operation_identity_missing",
12327            member.base_sequence,
12328            &format!(
12329                "durable {} resource identity from scheduled/open history",
12330                member.kind
12331            ),
12332            "missing operation identity",
12333            "selection member history is missing its canonical durable identity",
12334        ));
12335    }
12336    if marker.operation_identity != expected_identity {
12337        return Err(invalid_recorded_history(
12338            "selection_operation_identity_mismatch",
12339            member.base_sequence,
12340            expected_identity,
12341            &marker.operation_identity,
12342            "selection winner identity does not match durable scheduled/open history",
12343        ));
12344    }
12345
12346    let failure_types = [
12347        "ActivityFailed",
12348        "ActivityCancelled",
12349        "ActivityTimedOut",
12350        "ChildRunFailed",
12351        "ChildRunCancelled",
12352        "ChildRunTerminated",
12353    ];
12354    let success_types = [
12355        "ActivityCompleted",
12356        "ChildRunCompleted",
12357        "TimerFired",
12358        "SignalApplied",
12359        "ConditionWaitSatisfied",
12360        "ConditionWaitTimedOut",
12361    ];
12362    let terminal_types: &[&str] = if marker.outcome == "failed" {
12363        &failure_types
12364    } else {
12365        &success_types
12366    };
12367    let mut candidates = Vec::new();
12368    let member_commands = (member.base_sequence
12369        ..member.base_sequence.saturating_add(member.size as u64))
12370        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
12371        .map(|command| (command.sequence(), command))
12372        .collect::<BTreeMap<_, _>>();
12373    let mut resolved_conditions = BTreeSet::new();
12374    for event in state.history_events.iter() {
12375        let Some(sequence) = durable_event_sequence(event) else {
12376            continue;
12377        };
12378        let Some(command) = member_commands.get(&sequence) else {
12379            continue;
12380        };
12381        if !terminal_types.contains(&event.event_type.as_str()) {
12382            continue;
12383        }
12384        if matches!(command, RecordedCommand::ConditionWait { .. }) {
12385            if !matches!(
12386                event.event_type.as_str(),
12387                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
12388            ) && !(event.event_type == "TimerFired"
12389                && event.payload.get("timer_kind").and_then(Value::as_str)
12390                    == Some("condition_timeout"))
12391            {
12392                continue;
12393            }
12394            if !resolved_conditions.insert(sequence) {
12395                continue;
12396            }
12397        }
12398        let event_id = event
12399            .raw
12400            .get("id")
12401            .or_else(|| event.raw.get("event_id"))
12402            .and_then(Value::as_str)
12403            .filter(|value| !value.is_empty())
12404            .ok_or_else(|| {
12405                invalid_recorded_history(
12406                    "selection_resolution_event_id_missing",
12407                    member.base_sequence,
12408                    "terminal selection history with a durable event id",
12409                    &event.payload.to_string(),
12410                    "selection terminal history cannot be bound to its winner marker",
12411                )
12412            })?;
12413        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
12414    }
12415    let resolution = if marker.outcome == "failed" {
12416        candidates.first()
12417    } else {
12418        candidates.last()
12419    };
12420    let Some((event_id, event_type, sequence)) = resolution else {
12421        return Err(invalid_recorded_history(
12422            "selection_resolution_event_missing",
12423            member.base_sequence,
12424            "terminal history for the selected member",
12425            &format!("{:?}", marker.member_key),
12426            "selection winner marker has no matching durable terminal event",
12427        ));
12428    };
12429    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
12430        return Err(invalid_recorded_history(
12431            "selection_resolution_event_mismatch",
12432            member.base_sequence,
12433            &format!("{event_type}:{event_id}"),
12434            &format!(
12435                "{}:{}",
12436                marker.resolution_event_type, marker.resolution_event_id
12437            ),
12438            "selection winner marker does not reference the event that made its member terminal",
12439        ));
12440    }
12441    Ok(*sequence)
12442}
12443
12444fn selection_member_recorded_command(
12445    state: &WorkflowState,
12446    authored_sequence: u64,
12447) -> Option<&RecordedCommand> {
12448    let original = state
12449        .recorded_commands
12450        .iter()
12451        .find(|command| command.sequence() == authored_sequence)?;
12452    let RecordedCommand::ConditionWait {
12453        occurrence_id,
12454        parallel_group_path: Some(_),
12455        ..
12456    } = original
12457    else {
12458        return Some(original);
12459    };
12460    // Decoding proves each physical reopen has the same authored identity and
12461    // group path after a satisfied predecessor. Only its latest wait can make
12462    // this logical member terminal.
12463    state
12464        .recorded_commands
12465        .iter()
12466        .filter(|command| {
12467            matches!(command, RecordedCommand::ConditionWait {
12468                occurrence_id: candidate, ..
12469            } if candidate == occurrence_id)
12470        })
12471        .max_by_key(|command| command.sequence())
12472}
12473
12474fn recorded_selection_member_outcome(
12475    state: &WorkflowState,
12476    handle: &DurableOperationHandle,
12477) -> Result<Option<ParallelResult>> {
12478    for event in state.history_events.iter() {
12479        let Some(sequence) = durable_event_sequence(event) else {
12480            continue;
12481        };
12482        if sequence < handle.base_sequence
12483            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
12484            || !matches!(
12485                event.event_type.as_str(),
12486                "ActivityFailed"
12487                    | "ActivityCancelled"
12488                    | "ActivityTimedOut"
12489                    | "ChildRunFailed"
12490                    | "ChildRunCancelled"
12491                    | "ChildRunTerminated"
12492            )
12493        {
12494            continue;
12495        }
12496        let Some(command) = state
12497            .recorded_commands
12498            .iter()
12499            .find(|command| command.sequence() == sequence)
12500        else {
12501            continue;
12502        };
12503        match command {
12504            RecordedCommand::Activity {
12505                outcome: Some(Err(failure)),
12506                ..
12507            } => return Err(Error::ActivityFailed(failure.clone())),
12508            RecordedCommand::ChildWorkflow {
12509                outcome: Some(Err(failure)),
12510                ..
12511            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
12512            _ => {}
12513        }
12514    }
12515
12516    let mut results = Vec::with_capacity(handle.size);
12517    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
12518        let Some(command) = selection_member_recorded_command(state, sequence) else {
12519            return Ok(None);
12520        };
12521        let result = match command {
12522            RecordedCommand::Activity { outcome, .. } => match outcome {
12523                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
12524                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
12525                None => return Ok(None),
12526            },
12527            RecordedCommand::Timer { fired, .. } => {
12528                if !fired {
12529                    return Ok(None);
12530                }
12531                ParallelAvroResult::Timer
12532            }
12533            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
12534                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
12535                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
12536                None => return Ok(None),
12537            },
12538            RecordedCommand::SignalWait { value, .. } => match value {
12539                Some(value) => ParallelAvroResult::Signal(value.clone()),
12540                None => return Ok(None),
12541            },
12542            RecordedCommand::ConditionWait { result, .. } => match result {
12543                Some(result) => ParallelAvroResult::Condition(*result),
12544                None => return Ok(None),
12545            },
12546            other => {
12547                return Err(command_mismatch(
12548                    other,
12549                    format!("selected {} member", handle.kind),
12550                ))
12551            }
12552        };
12553        results.push(result);
12554    }
12555    let mut results = results.into_iter();
12556    parallel_results_for_shape(&handle.shape, &mut results)
12557        .into_json_result()
12558        .map(Some)
12559}
12560
12561fn recorded_selection_member_is_terminal(
12562    state: &WorkflowState,
12563    handle: &DurableOperationHandle,
12564) -> bool {
12565    let mut completed = 0usize;
12566    let mut all_completed = true;
12567    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
12568        let Some(command) = selection_member_recorded_command(state, sequence) else {
12569            all_completed = false;
12570            continue;
12571        };
12572        let terminal = match command {
12573            RecordedCommand::Activity {
12574                outcome: Some(Err(_)),
12575                ..
12576            }
12577            | RecordedCommand::ChildWorkflow {
12578                outcome: Some(Err(_)),
12579                ..
12580            } => return true,
12581            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
12582            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
12583            RecordedCommand::Timer { fired, .. } => *fired,
12584            RecordedCommand::SignalWait { value, .. } => value.is_some(),
12585            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
12586            RecordedCommand::SearchAttributes { .. }
12587            | RecordedCommand::CancellationScope { .. }
12588            | RecordedCommand::SideEffect { .. }
12589            | RecordedCommand::VersionMarker { .. }
12590            | RecordedCommand::Memo { .. }
12591            | RecordedCommand::CancellationBoundary { .. }
12592            | RecordedCommand::CancellationGroup { .. } => false,
12593        };
12594        if !terminal {
12595            all_completed = false;
12596            continue;
12597        }
12598        completed += 1;
12599    }
12600    all_completed && completed == handle.size
12601}
12602
12603fn selection_cancellation_for_handle(
12604    state: &WorkflowState,
12605    handle: &DurableOperationHandle,
12606) -> Result<bool> {
12607    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
12608        recorded.selection_group_id == handle.selection_group_id
12609            && recorded.member_base_sequence == handle.base_sequence
12610    }) else {
12611        return Ok(false);
12612    };
12613    validate_selection_cancellation_marker(marker, handle)?;
12614    Ok(true)
12615}
12616
12617fn validate_selection_cancellations_for_handles(
12618    state: &WorkflowState,
12619    handles: &[DurableOperationHandle],
12620) -> Result<()> {
12621    let Some(group_id) = handles
12622        .first()
12623        .map(|handle| handle.selection_group_id.as_str())
12624    else {
12625        return Ok(());
12626    };
12627    for marker in state
12628        .cancelled_selection_members
12629        .iter()
12630        .filter(|marker| marker.selection_group_id == group_id)
12631    {
12632        let Some(handle) = handles
12633            .iter()
12634            .find(|handle| handle.base_sequence == marker.member_base_sequence)
12635        else {
12636            return Err(invalid_recorded_history(
12637                "selection_cancellation_member_mismatch",
12638                marker.member_base_sequence,
12639                "SelectionOperationCancelled matching an authored selection handle",
12640                &format!("{marker:?}"),
12641                "selection cancellation member base does not name an authored member",
12642            ));
12643        };
12644        validate_selection_cancellation_marker(marker, handle)?;
12645    }
12646    Ok(())
12647}
12648
12649fn validate_selection_cancellation_marker(
12650    marker: &SelectionCancellation,
12651    handle: &DurableOperationHandle,
12652) -> Result<()> {
12653    if marker.selection_group_id != handle.selection_group_id
12654        || marker.member_key != handle.key
12655        || marker.member_index != handle.index
12656        || marker.member_base_sequence != handle.base_sequence
12657        || marker.member_size != handle.size
12658        || marker.operation_kind != handle.kind
12659        || marker.operation_identity != handle.identity
12660    {
12661        return Err(invalid_recorded_history(
12662            "selection_cancellation_member_mismatch",
12663            handle.base_sequence,
12664            "SelectionOperationCancelled matching the authored selection handle",
12665            &format!("{marker:?}"),
12666            "selection cancellation history targets different authored member metadata",
12667        ));
12668    }
12669    Ok(())
12670}
12671
12672/// Future returned by [`DurableOperationHandle::await_result`].
12673pub struct DurableOperationAwaitCall {
12674    handle: DurableOperationHandle,
12675}
12676
12677impl Future for DurableOperationAwaitCall {
12678    type Output = Result<ParallelResult>;
12679
12680    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12681        let mut state = match self.handle.ctx.state.lock() {
12682            Ok(state) => state,
12683            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12684        };
12685        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
12686            return Poll::Ready(Err(error));
12687        }
12688        match state.prepare_selection_handle_cancellation(&self.handle) {
12689            Ok(true) => return Poll::Pending,
12690            Ok(false) => {}
12691            Err(error) => return Poll::Ready(Err(error)),
12692        }
12693        match selection_cancellation_for_handle(&state, &self.handle) {
12694            Err(error) => return Poll::Ready(Err(error)),
12695            Ok(false) => {}
12696            Ok(true) => {
12697                state.advance_cancellation_receipt(
12698                    &self.handle.selection_group_id,
12699                    self.handle.base_sequence,
12700                );
12701                return Poll::Ready(Err(Error::DurableOperationCancelled(
12702                    DurableOperationCancelled {
12703                        selection_group_id: self.handle.selection_group_id.clone(),
12704                        member_key: self.handle.key.clone(),
12705                        member_index: self.handle.index,
12706                        operation_kind: self.handle.kind.clone(),
12707                        operation_identity: self.handle.identity.clone(),
12708                    },
12709                )));
12710            }
12711        }
12712        match recorded_selection_member_outcome(&state, &self.handle) {
12713            Ok(Some(result)) => {
12714                state.advance_cancellation_handle(&self.handle, false);
12715                Poll::Ready(Ok(result))
12716            }
12717            Ok(None) => Poll::Pending,
12718            Err(error) => {
12719                if !workflow_task_integrity_error(&error) {
12720                    state.advance_cancellation_handle(&self.handle, true);
12721                }
12722                Poll::Ready(Err(error))
12723            }
12724        }
12725    }
12726}
12727
12728fn validate_selection_delivery_handle(
12729    state: &WorkflowState,
12730    handle: &DurableOperationHandle,
12731) -> Result<()> {
12732    let path = state
12733        .recorded_commands
12734        .iter()
12735        .find(|command| command.sequence() == handle.base_sequence)
12736        .and_then(|command| match command {
12737            RecordedCommand::Activity {
12738                parallel_group_path,
12739                ..
12740            }
12741            | RecordedCommand::ChildWorkflow {
12742                parallel_group_path,
12743                ..
12744            }
12745            | RecordedCommand::Timer {
12746                parallel_group_path,
12747                ..
12748            }
12749            | RecordedCommand::SignalWait {
12750                parallel_group_path,
12751                ..
12752            }
12753            | RecordedCommand::ConditionWait {
12754                parallel_group_path,
12755                ..
12756            } => parallel_group_path.as_ref(),
12757            _ => None,
12758        })
12759        .and_then(|path| path.first());
12760    let matches = path.is_some_and(|entry| {
12761        entry.parallel_group_mode.as_deref() == Some("select")
12762            && entry.parallel_group_id == handle.selection_group_id
12763            && entry.selection_member_key.as_ref() == Some(&handle.key)
12764            && entry.selection_member_index == Some(handle.index)
12765            && entry.selection_member_base_sequence == Some(handle.base_sequence)
12766            && entry.selection_member_size == Some(handle.size)
12767            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
12768    });
12769    if !matches
12770        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
12771            != handle.identity
12772    {
12773        return Err(invalid_recorded_history(
12774            "cooperative_cancellation_call_mismatch",
12775            handle.base_sequence,
12776            "selection handle matching its authored durable identity",
12777            &format!("{handle:?}"),
12778            "selection handle identity or member metadata changed before cancellation replay",
12779        ));
12780    }
12781    Ok(())
12782}
12783
12784/// Future returned by [`DurableOperationHandle::cancel`].
12785pub struct CancelDurableOperationCall {
12786    handle: DurableOperationHandle,
12787    emitted: bool,
12788}
12789
12790impl Future for CancelDurableOperationCall {
12791    type Output = Result<()>;
12792
12793    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12794        let ctx = self.handle.ctx.clone();
12795        let mut state = match ctx.state.lock() {
12796            Ok(state) => state,
12797            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12798        };
12799        match selection_cancellation_for_handle(&state, &self.handle) {
12800            Err(error) => return Poll::Ready(Err(error)),
12801            Ok(true) => {
12802                state.advance_cancellation_receipt(
12803                    &self.handle.selection_group_id,
12804                    self.handle.base_sequence,
12805                );
12806                return Poll::Ready(Ok(()));
12807            }
12808            Ok(false) => {}
12809        }
12810        if recorded_selection_member_is_terminal(&state, &self.handle) {
12811            return Poll::Ready(Ok(()));
12812        }
12813        if !self.emitted {
12814            state.commands.push(json!({
12815                "type": "cancel_selection_operation",
12816                "selection_group_id": self.handle.selection_group_id,
12817                "member_key": self.handle.key,
12818                "member_index": self.handle.index,
12819                "member_base_sequence": self.handle.base_sequence,
12820                "member_size": self.handle.size,
12821                "operation_kind": self.handle.kind,
12822                "operation_identity": self.handle.identity,
12823            }));
12824            self.emitted = true;
12825        }
12826        // The cancellation command is only a request. Do not expose workflow
12827        // state after cancel until committed SelectionOperationCancelled
12828        // history proves that the request won the race with member completion.
12829        Poll::Pending
12830    }
12831}
12832
12833trait PollNestedResultExt<T> {
12834    fn flatten_result(self) -> Poll<Result<T>>;
12835}
12836
12837impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
12838    fn flatten_result(self) -> Poll<Result<T>> {
12839        match self {
12840            Poll::Ready(Ok(result)) => Poll::Ready(result),
12841            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
12842            Poll::Pending => Poll::Pending,
12843        }
12844    }
12845}
12846
12847struct SagaCompensation {
12848    activity_type: String,
12849    options: ActivityOptions,
12850    arguments: AvroValue,
12851    registration_order: usize,
12852}
12853
12854/// Workflow-local deterministic saga compensation helper.
12855///
12856/// Register each compensation only after its forward step succeeds. Passing
12857/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
12858/// reverse registration order after any failure, including cooperative
12859/// cancellation. Each compensation is an ordinary durable activity, so replay,
12860/// duplicate delivery, and worker restart use existing history semantics.
12861pub struct Saga {
12862    ctx: WorkflowContext,
12863    compensations: Vec<SagaCompensation>,
12864}
12865
12866impl Saga {
12867    fn new(ctx: WorkflowContext) -> Self {
12868        Self {
12869            ctx,
12870            compensations: Vec::new(),
12871        }
12872    }
12873
12874    pub fn add_compensation<T: Serialize>(
12875        &mut self,
12876        activity_type: impl Into<String>,
12877        args: T,
12878    ) -> Result<&mut Self> {
12879        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
12880    }
12881
12882    pub fn add_compensation_with_options<T: Serialize>(
12883        &mut self,
12884        activity_type: impl Into<String>,
12885        options: ActivityOptions,
12886        args: T,
12887    ) -> Result<&mut Self> {
12888        let activity_type = activity_type.into();
12889        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
12890            return Err(Error::Codec(
12891                "saga compensation activity type must be non-empty without surrounding whitespace"
12892                    .to_string(),
12893            ));
12894        }
12895        options.validate().map_err(Error::InvalidActivityOptions)?;
12896        let arguments = AvroValue::from_serialize(&args)?;
12897        let registration_order = self.compensations.len() + 1;
12898        self.compensations.push(SagaCompensation {
12899            activity_type,
12900            options,
12901            arguments,
12902            registration_order,
12903        });
12904        Ok(self)
12905    }
12906
12907    /// Compensate `initiating_failure` and return the failure that must remain.
12908    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
12909        let _shield = match self.ctx.cancellation_shield() {
12910            Ok(shield) => shield,
12911            Err(error) => return error,
12912        };
12913        while let Some(compensation) = self.compensations.pop() {
12914            if let Err(compensation_failure) = self
12915                .ctx
12916                .activity_with_options(
12917                    compensation.activity_type.clone(),
12918                    compensation.options,
12919                    compensation.arguments,
12920                )
12921                .await
12922            {
12923                if workflow_task_integrity_error(&compensation_failure) {
12924                    return compensation_failure;
12925                }
12926                return Error::SagaCompensationFailed(SagaCompensationFailure {
12927                    initiating_failure: Box::new(initiating_failure),
12928                    compensation_failure: Box::new(compensation_failure),
12929                    compensation_activity_type: compensation.activity_type,
12930                    compensation_registration_order: compensation.registration_order,
12931                });
12932            }
12933        }
12934        initiating_failure
12935    }
12936
12937    /// Return a successful forward value or compensate and preserve its failure.
12938    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
12939        match outcome {
12940            Ok(value) => Ok(value),
12941            Err(error) => Err(self.compensate(error).await),
12942        }
12943    }
12944}
12945
12946pub struct ActivityCall {
12947    ctx: WorkflowContext,
12948    activity_type: String,
12949    options: ActivityOptions,
12950    args: Option<Result<AvroValue>>,
12951    scheduled: bool,
12952    parallel_group_path: Vec<ParallelGroupMetadata>,
12953}
12954
12955impl ActivityCall {
12956    fn poll_avro_value(
12957        mut self: Pin<&mut Self>,
12958        _cx: &mut TaskContext<'_>,
12959    ) -> Poll<Result<AvroValue>> {
12960        let ctx = self.ctx.clone();
12961        let mut state = match ctx.state.lock() {
12962            Ok(state) => state,
12963            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12964        };
12965
12966        if self.scheduled {
12967            return Poll::Pending;
12968        }
12969
12970        let options = match self.options.validate() {
12971            Ok(options) => options,
12972            Err(error) => {
12973                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
12974            }
12975        };
12976        let task_queue = options
12977            .task_queue
12978            .clone()
12979            .unwrap_or_else(|| state.task_queue.clone());
12980        let current_recorded_options = RecordedActivityOptions {
12981            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
12982            // Rust schedules ordinary durable activities. The server records a
12983            // non-null mode only for a specialized execution primitive.
12984            execution_mode: RecordedSnapshotValue::Known(None),
12985            retry_policy: current_activity_retry_snapshot(&options),
12986        };
12987
12988        let cursor = state.command_cursor;
12989        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
12990            return Poll::Ready(Err(error));
12991        }
12992        let recorded =
12993            match state.cancellation_replay_command(cursor, CancellationCallKind::Activity) {
12994                Ok(recorded) => recorded,
12995                Err(error) => return Poll::Ready(Err(error)),
12996            };
12997        if let Some(recorded) = recorded {
12998            let sequence = recorded.sequence();
12999            match recorded {
13000                RecordedCommand::Activity {
13001                    activity_type,
13002                    cancellation_policy,
13003                    options: recorded_options,
13004                    outcome,
13005                    parallel_group_path,
13006                    ..
13007                } => {
13008                    let current_policy = options
13009                        .cancellation_policy
13010                        .unwrap_or(CancellationPolicy::TryCancel)
13011                        .as_str();
13012                    if cancellation_policy != current_policy {
13013                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13014                            ReplayFailure::new(
13015                                "activity_cancellation_policy_changed",
13016                                Some(sequence),
13017                                Some(cancellation_policy),
13018                                Some(current_policy.to_string()),
13019                                "Activity cancellation policy changed during replay",
13020                            ),
13021                        )));
13022                    }
13023                    if let Err(error) = ensure_parallel_path_matches(
13024                        sequence,
13025                        parallel_group_path.as_deref(),
13026                        &self.parallel_group_path,
13027                    ) {
13028                        return Poll::Ready(Err(error));
13029                    }
13030                    if let Some(recorded_type) = activity_type {
13031                        if recorded_type != self.activity_type {
13032                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13033                                ReplayFailure::new(
13034                                    "recorded_command_detail_mismatch",
13035                                    Some(sequence),
13036                                    Some(format!("activity:{recorded_type}")),
13037                                    Some(format!("activity:{}", self.activity_type)),
13038                                    "recorded activity type differs from the current workflow command",
13039                                ),
13040                            )));
13041                        }
13042                    }
13043                    if let Some(recorded_options) = recorded_options {
13044                        if !recorded_options
13045                            .task_queue
13046                            .matches_current(&current_recorded_options.task_queue)
13047                        {
13048                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13049                                ReplayFailure::new(
13050                                    "activity_task_queue_mismatch",
13051                                    Some(sequence),
13052                                    Some(activity_options_description(&recorded_options)),
13053                                    Some(activity_options_description(&current_recorded_options)),
13054                                    "recorded activity task queue differs from the current workflow command",
13055                                ),
13056                            )));
13057                        }
13058                        if !recorded_options
13059                            .execution_mode
13060                            .matches_current(&current_recorded_options.execution_mode)
13061                        {
13062                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13063                                ReplayFailure::new(
13064                                    "activity_execution_mode_mismatch",
13065                                    Some(sequence),
13066                                    Some(activity_options_description(&recorded_options)),
13067                                    Some(activity_options_description(&current_recorded_options)),
13068                                    "recorded activity execution mode differs from the current workflow command",
13069                                ),
13070                            )));
13071                        }
13072                        if !recorded_options
13073                            .retry_policy
13074                            .matches_current(&current_recorded_options.retry_policy)
13075                        {
13076                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13077                                ReplayFailure::new(
13078                                    "activity_retry_policy_mismatch",
13079                                    Some(sequence),
13080                                    Some(activity_options_description(&recorded_options)),
13081                                    Some(activity_options_description(&current_recorded_options)),
13082                                    "recorded activity retry policy differs from the current workflow command",
13083                                ),
13084                            )));
13085                        }
13086                    }
13087                    if let Err(error) =
13088                        state.replay_cancellation_at(cursor, CancellationCallKind::Activity)
13089                    {
13090                        return Poll::Ready(Err(error));
13091                    }
13092                    match state.prepare_scalar_cancellation(
13093                        cursor,
13094                        CancellationCallKind::Activity,
13095                        &self.parallel_group_path,
13096                    ) {
13097                        Ok(true) => {
13098                            self.scheduled = true;
13099                            return Poll::Pending;
13100                        }
13101                        Ok(false) => {}
13102                        Err(error) => return Poll::Ready(Err(error)),
13103                    }
13104                    state.command_cursor += 1;
13105                    if let Some(outcome) = outcome {
13106                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13107                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
13108                    }
13109                    state.matched_recorded_pending = true;
13110                    self.scheduled = true;
13111                    return Poll::Pending;
13112                }
13113                other => {
13114                    return Poll::Ready(Err(command_mismatch(
13115                        &other,
13116                        format!("activity:{}", self.activity_type),
13117                    )));
13118                }
13119            }
13120        }
13121
13122        if !self.scheduled {
13123            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
13124                Ok(args) => args,
13125                Err(error) => return Poll::Ready(Err(error)),
13126            };
13127            let arguments = normalize_avro_arguments(args);
13128            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
13129                Ok(envelope) => envelope,
13130                Err(error) => return Poll::Ready(Err(error)),
13131            };
13132
13133            let mut command = serde_json::Map::from_iter([
13134                ("type".to_string(), json!("schedule_activity")),
13135                (
13136                    "activity_type".to_string(),
13137                    json!(self.activity_type.clone()),
13138                ),
13139                ("queue".to_string(), json!(task_queue)),
13140                ("arguments".to_string(), envelope),
13141            ]);
13142            for (field, value) in [
13143                ("start_to_close_timeout", options.start_to_close_timeout),
13144                (
13145                    "schedule_to_start_timeout",
13146                    options.schedule_to_start_timeout,
13147                ),
13148                (
13149                    "schedule_to_close_timeout",
13150                    options.schedule_to_close_timeout,
13151                ),
13152                ("heartbeat_timeout", options.heartbeat_timeout),
13153            ] {
13154                if let Some(value) = value {
13155                    command.insert(field.to_string(), json!(value));
13156                }
13157            }
13158            if let Some(retry_policy) = options.retry_policy {
13159                command.insert("retry_policy".to_string(), retry_policy);
13160            }
13161            if let Some(policy) = options.cancellation_policy {
13162                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
13163            }
13164            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13165            ctx.apply_scope_membership(&mut command);
13166            match state.prepare_scalar_cancellation(
13167                cursor,
13168                CancellationCallKind::Activity,
13169                &self.parallel_group_path,
13170            ) {
13171                Ok(true) => {
13172                    self.scheduled = true;
13173                    return Poll::Pending;
13174                }
13175                Ok(false) => {}
13176                Err(error) => return Poll::Ready(Err(error)),
13177            }
13178            state.commands.push(Value::Object(command));
13179            self.scheduled = true;
13180        }
13181
13182        Poll::Pending
13183    }
13184}
13185
13186impl Future for ActivityCall {
13187    type Output = Result<Value>;
13188
13189    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13190        match self.poll_avro_value(cx) {
13191            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
13192            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13193            Poll::Pending => Poll::Pending,
13194        }
13195    }
13196}
13197
13198/// Future returned by [`WorkflowContext::sleep`].
13199pub struct TimerCall {
13200    ctx: WorkflowContext,
13201    delay_seconds: Option<u64>,
13202    scheduled: bool,
13203    matched_pending: bool,
13204    parallel_group_path: Vec<ParallelGroupMetadata>,
13205}
13206
13207impl Future for TimerCall {
13208    type Output = Result<()>;
13209
13210    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13211        if self.matched_pending {
13212            return Poll::Pending;
13213        }
13214
13215        let ctx = self.ctx.clone();
13216        let Some(requested_delay) = self.delay_seconds else {
13217            return Poll::Ready(Err(Error::TimerDurationOverflow));
13218        };
13219        let mut state = match ctx.state.lock() {
13220            Ok(state) => state,
13221            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13222        };
13223
13224        let cursor = state.command_cursor;
13225        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13226            return Poll::Ready(Err(error));
13227        }
13228        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
13229        {
13230            Ok(recorded) => recorded,
13231            Err(error) => return Poll::Ready(Err(error)),
13232        };
13233        if let Some(recorded) = recorded {
13234            match recorded {
13235                RecordedCommand::Timer {
13236                    sequence,
13237                    delay_seconds,
13238                    fired,
13239                    parallel_group_path,
13240                    ..
13241                } => {
13242                    if let Err(error) =
13243                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
13244                    {
13245                        return Poll::Ready(Err(error));
13246                    }
13247                    if let Err(error) = ensure_parallel_path_matches(
13248                        sequence,
13249                        parallel_group_path.as_deref(),
13250                        &self.parallel_group_path,
13251                    ) {
13252                        return Poll::Ready(Err(error));
13253                    }
13254                    if delay_seconds != requested_delay {
13255                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13256                            ReplayFailure::new(
13257                                "timer_delay_mismatch",
13258                                Some(sequence),
13259                                Some(format!("timer:{delay_seconds}s")),
13260                                Some(format!("timer:{requested_delay}s")),
13261                                "recorded timer delay differs from the current workflow command",
13262                            ),
13263                        )));
13264                    }
13265                    if let Err(error) =
13266                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
13267                    {
13268                        return Poll::Ready(Err(error));
13269                    }
13270                    match state.prepare_scalar_cancellation(
13271                        cursor,
13272                        CancellationCallKind::Timer,
13273                        &self.parallel_group_path,
13274                    ) {
13275                        Ok(true) => {
13276                            self.scheduled = true;
13277                            self.matched_pending = true;
13278                            return Poll::Pending;
13279                        }
13280                        Ok(false) => {}
13281                        Err(error) => return Poll::Ready(Err(error)),
13282                    }
13283                    state.command_cursor += 1;
13284                    if fired {
13285                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13286                        return Poll::Ready(Ok(()));
13287                    }
13288                    state.matched_recorded_pending = true;
13289                    self.scheduled = true;
13290                    self.matched_pending = true;
13291                    return Poll::Pending;
13292                }
13293                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
13294            }
13295        }
13296
13297        if !self.scheduled {
13298            let mut command = serde_json::Map::from_iter([
13299                ("type".to_string(), json!("start_timer")),
13300                ("delay_seconds".to_string(), json!(requested_delay)),
13301            ]);
13302            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
13303                Ok(Some(proof)) => {
13304                    command.insert("cancellation_cleanup".into(), proof);
13305                }
13306                Ok(None) => {}
13307                Err(error) => return Poll::Ready(Err(error)),
13308            }
13309            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13310            ctx.apply_scope_membership(&mut command);
13311            match state.prepare_scalar_cancellation(
13312                cursor,
13313                CancellationCallKind::Timer,
13314                &self.parallel_group_path,
13315            ) {
13316                Ok(true) => {
13317                    self.scheduled = true;
13318                    self.matched_pending = true;
13319                    return Poll::Pending;
13320                }
13321                Ok(false) => {}
13322                Err(error) => return Poll::Ready(Err(error)),
13323            }
13324            state.commands.push(Value::Object(command));
13325            self.scheduled = true;
13326        }
13327
13328        Poll::Pending
13329    }
13330}
13331
13332/// Future returned by [`WorkflowContext::wait_condition`].
13333pub struct ConditionWaitCall {
13334    ctx: WorkflowContext,
13335    options: ConditionWaitOptions,
13336    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
13337    occurrence_id: Option<String>,
13338    opened_wait: bool,
13339    parallel_group_path: Vec<ParallelGroupMetadata>,
13340}
13341
13342impl Future for ConditionWaitCall {
13343    type Output = Result<ConditionWaitResult>;
13344
13345    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13346        if self.opened_wait {
13347            return Poll::Pending;
13348        }
13349
13350        let options = match self.options.validate() {
13351            Ok(options) => options,
13352            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
13353        };
13354        let ctx = self.ctx.clone();
13355        let occurrence_id = match self.occurrence_id.as_ref() {
13356            Some(occurrence_id) => occurrence_id.clone(),
13357            None => {
13358                let mut state = match ctx.state.lock() {
13359                    Ok(state) => state,
13360                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13361                };
13362                let ordinal = state.condition_wait_occurrence_counter;
13363                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
13364                    Some(next) => next,
13365                    None => {
13366                        return Poll::Ready(Err(Error::WorkerLoop(
13367                            "condition wait occurrence counter overflowed".to_string(),
13368                        )))
13369                    }
13370                };
13371                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
13372                drop(state);
13373                self.occurrence_id = Some(occurrence_id.clone());
13374                occurrence_id
13375            }
13376        };
13377
13378        let recorded_result = {
13379            let mut state = match ctx.state.lock() {
13380                Ok(state) => state,
13381                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13382            };
13383            let initial_cursor = state.command_cursor;
13384            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
13385                return Poll::Ready(Err(error));
13386            }
13387            let recorded = match state
13388                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
13389            {
13390                Ok(recorded) => recorded,
13391                Err(error) => return Poll::Ready(Err(error)),
13392            };
13393            let Some(recorded) = recorded else {
13394                drop(state);
13395                return self.poll_new_condition(options);
13396            };
13397            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
13398                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
13399            }
13400
13401            let mut cursor = state.command_cursor;
13402            let mut result = None;
13403            let mut pending_delivery = false;
13404            loop {
13405                if cursor > initial_cursor
13406                    && matches!(
13407                        state.recorded_commands.get(cursor),
13408                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
13409                    )
13410                {
13411                    break;
13412                }
13413                let recorded = match state
13414                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
13415                {
13416                    Ok(recorded) => recorded,
13417                    Err(error) => return Poll::Ready(Err(error)),
13418                };
13419                let Some(RecordedCommand::ConditionWait {
13420                    sequence,
13421                    occurrence_id: ref recorded_occurrence_id,
13422                    ref condition_key,
13423                    ref predicate_identity,
13424                    timeout_seconds,
13425                    result: recorded_result,
13426                    ref parallel_group_path,
13427                    ..
13428                }) = recorded
13429                else {
13430                    break;
13431                };
13432
13433                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
13434                    break;
13435                }
13436                if let Err(error) = ensure_parallel_path_matches(
13437                    sequence,
13438                    parallel_group_path.as_deref(),
13439                    &self.parallel_group_path,
13440                ) {
13441                    return Poll::Ready(Err(error));
13442                }
13443                if let Err(error) = validate_recorded_condition_wait(
13444                    sequence,
13445                    recorded_occurrence_id,
13446                    condition_key.as_deref(),
13447                    predicate_identity,
13448                    timeout_seconds,
13449                    &occurrence_id,
13450                    &options,
13451                ) {
13452                    return Poll::Ready(Err(error));
13453                }
13454                if result == Some(ConditionWaitResult::TimedOut) {
13455                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
13456                        "condition_wait_reopened_after_timeout",
13457                        Some(sequence),
13458                        Some("timed-out condition is terminal".to_string()),
13459                        Some("another physical wait-open".to_string()),
13460                        "condition history reopened one logical wait after its durable timeout",
13461                    ))));
13462                }
13463                if let Err(error) =
13464                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
13465                {
13466                    return Poll::Ready(Err(error));
13467                }
13468                match state.prepare_scalar_cancellation(
13469                    cursor,
13470                    CancellationCallKind::Condition,
13471                    &self.parallel_group_path,
13472                ) {
13473                    Ok(pending) => pending_delivery |= pending,
13474                    Err(error) => return Poll::Ready(Err(error)),
13475                }
13476                result = recorded_result;
13477                if result.is_some() {
13478                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13479                }
13480                cursor += 1;
13481            }
13482            state.command_cursor = cursor;
13483            if pending_delivery {
13484                self.opened_wait = true;
13485                return Poll::Pending;
13486            }
13487            result
13488        };
13489
13490        if let Some(result) = recorded_result {
13491            return Poll::Ready(Ok(result));
13492        }
13493
13494        self.poll_open_condition(options, true)
13495    }
13496}
13497
13498impl ConditionWaitCall {
13499    fn poll_new_condition(
13500        self: Pin<&mut Self>,
13501        options: ValidatedConditionWaitOptions,
13502    ) -> Poll<Result<ConditionWaitResult>> {
13503        self.poll_open_condition(options, false)
13504    }
13505
13506    fn poll_open_condition(
13507        mut self: Pin<&mut Self>,
13508        options: ValidatedConditionWaitOptions,
13509        recorded_wait: bool,
13510    ) -> Poll<Result<ConditionWaitResult>> {
13511        {
13512            let ctx = self.ctx.clone();
13513            let mut state = match ctx.state.lock() {
13514                Ok(state) => state,
13515                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13516            };
13517            let cursor = state.command_cursor;
13518            match state.prepare_scalar_cancellation(
13519                cursor,
13520                CancellationCallKind::Condition,
13521                &self.parallel_group_path,
13522            ) {
13523                Ok(true) => {
13524                    self.opened_wait = true;
13525                    return Poll::Pending;
13526                }
13527                Ok(false) => {}
13528                Err(error) => return Poll::Ready(Err(error)),
13529            }
13530        }
13531        let selection_member = self
13532            .parallel_group_path
13533            .first()
13534            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
13535        match (self.predicate)() {
13536            Ok(true) if !selection_member || recorded_wait => {
13537                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
13538            }
13539            Ok(_) => {}
13540            Err(error) => return Poll::Ready(Err(error)),
13541        }
13542        if options.timeout_seconds == Some(0) && !selection_member {
13543            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
13544        }
13545
13546        let ctx = self.ctx.clone();
13547        let mut state = match ctx.state.lock() {
13548            Ok(state) => state,
13549            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13550        };
13551        let mut command = serde_json::Map::from_iter([
13552            ("type".to_string(), json!("open_condition_wait")),
13553            (
13554                "condition_wait_occurrence_id".to_string(),
13555                json!(self.occurrence_id.as_deref().unwrap_or_default()),
13556            ),
13557            ("condition_key".to_string(), json!(options.condition_key)),
13558            (
13559                "condition_definition_fingerprint".to_string(),
13560                json!(options.predicate_identity),
13561            ),
13562        ]);
13563        if let Some(timeout_seconds) = options.timeout_seconds {
13564            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
13565        }
13566        apply_parallel_group_path(&mut command, &self.parallel_group_path);
13567        ctx.apply_scope_membership(&mut command);
13568        state.commands.push(Value::Object(command));
13569        drop(state);
13570        self.opened_wait = true;
13571        Poll::Pending
13572    }
13573}
13574
13575fn validate_recorded_condition_wait(
13576    sequence: u64,
13577    recorded_occurrence_id: &str,
13578    recorded_key: Option<&str>,
13579    recorded_predicate_identity: &str,
13580    recorded_timeout_seconds: Option<u64>,
13581    current_occurrence_id: &str,
13582    current: &ValidatedConditionWaitOptions,
13583) -> Result<()> {
13584    if recorded_occurrence_id != current_occurrence_id {
13585        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13586            "condition_wait_occurrence_mismatch",
13587            Some(sequence),
13588            Some(recorded_occurrence_id.to_string()),
13589            Some(current_occurrence_id.to_string()),
13590            "recorded condition occurrence differs from the current authored wait position",
13591        )));
13592    }
13593    if recorded_key != Some(current.condition_key.as_str()) {
13594        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13595            "condition_wait_key_mismatch",
13596            Some(sequence),
13597            recorded_key.map(str::to_string),
13598            Some(current.condition_key.clone()),
13599            "recorded condition identity differs from the current workflow wait",
13600        )));
13601    }
13602    if recorded_predicate_identity != current.predicate_identity {
13603        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13604            "condition_wait_predicate_mismatch",
13605            Some(sequence),
13606            Some(recorded_predicate_identity.to_string()),
13607            Some(current.predicate_identity.clone()),
13608            "recorded condition predicate behavior differs from current workflow code",
13609        )));
13610    }
13611    if recorded_timeout_seconds != current.timeout_seconds {
13612        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13613            "condition_wait_timeout_mismatch",
13614            Some(sequence),
13615            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
13616            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
13617            "recorded condition timeout differs from the current workflow wait",
13618        )));
13619    }
13620    Ok(())
13621}
13622
13623/// Future returned by [`WorkflowContext::start_child_workflow`].
13624pub struct ChildWorkflowCall {
13625    ctx: WorkflowContext,
13626    workflow_type: String,
13627    options: ChildWorkflowOptions,
13628    args: Option<Result<AvroValue>>,
13629    scheduled: bool,
13630    matched_pending: bool,
13631    parallel_group_path: Vec<ParallelGroupMetadata>,
13632}
13633
13634impl ChildWorkflowCall {
13635    fn poll_avro_value(
13636        mut self: Pin<&mut Self>,
13637        _cx: &mut TaskContext<'_>,
13638    ) -> Poll<Result<ChildWorkflowAvroResult>> {
13639        if self.matched_pending {
13640            return Poll::Pending;
13641        }
13642
13643        let ctx = self.ctx.clone();
13644        let mut state = match ctx.state.lock() {
13645            Ok(state) => state,
13646            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13647        };
13648
13649        let cursor = state.command_cursor;
13650        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13651            return Poll::Ready(Err(error));
13652        }
13653        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
13654        {
13655            Ok(recorded) => recorded,
13656            Err(error) => return Poll::Ready(Err(error)),
13657        };
13658        if let Some(recorded) = recorded {
13659            let sequence = recorded.sequence();
13660            match recorded {
13661                RecordedCommand::ChildWorkflow {
13662                    workflow_type,
13663                    policies,
13664                    outcome,
13665                    parallel_group_path,
13666                    ..
13667                } => {
13668                    if let Err(error) = ensure_parallel_path_matches(
13669                        sequence,
13670                        parallel_group_path.as_deref(),
13671                        &self.parallel_group_path,
13672                    ) {
13673                        return Poll::Ready(Err(error));
13674                    }
13675                    if let Some(recorded_type) = workflow_type {
13676                        if recorded_type != self.workflow_type {
13677                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13678                                ReplayFailure::new(
13679                                    "recorded_command_detail_mismatch",
13680                                    Some(sequence),
13681                                    Some(format!("child workflow:{recorded_type}")),
13682                                    Some(format!("child workflow:{}", self.workflow_type)),
13683                                    "recorded child workflow type differs from the current workflow command",
13684                                ),
13685                            )));
13686                        }
13687                    }
13688                    if let Err(error) =
13689                        ensure_child_policies_match(sequence, &policies, &self.options)
13690                    {
13691                        return Poll::Ready(Err(error));
13692                    }
13693                    if let Err(error) =
13694                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
13695                    {
13696                        return Poll::Ready(Err(error));
13697                    }
13698                    match state.prepare_scalar_cancellation(
13699                        cursor,
13700                        CancellationCallKind::Child,
13701                        &self.parallel_group_path,
13702                    ) {
13703                        Ok(true) => {
13704                            self.scheduled = true;
13705                            self.matched_pending = true;
13706                            return Poll::Pending;
13707                        }
13708                        Ok(false) => {}
13709                        Err(error) => return Poll::Ready(Err(error)),
13710                    }
13711                    state.command_cursor += 1;
13712                    if let Some(outcome) = outcome {
13713                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13714                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
13715                    }
13716                    state.matched_recorded_pending = true;
13717                    self.scheduled = true;
13718                    self.matched_pending = true;
13719                    return Poll::Pending;
13720                }
13721                other => {
13722                    return Poll::Ready(Err(command_mismatch(
13723                        &other,
13724                        format!("child workflow:{}", self.workflow_type),
13725                    )));
13726                }
13727            }
13728        }
13729
13730        if !self.scheduled {
13731            if self.options.task_queue.trim().is_empty() {
13732                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
13733                    "task_queue must not be empty".to_string(),
13734                )));
13735            }
13736            for (name, value) in [
13737                (
13738                    "execution_timeout_seconds",
13739                    self.options.execution_timeout_seconds,
13740                ),
13741                ("run_timeout_seconds", self.options.run_timeout_seconds),
13742            ] {
13743                if value == Some(0) {
13744                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
13745                        "{name} must be at least 1"
13746                    ))));
13747                }
13748            }
13749
13750            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
13751                Ok(args) => args,
13752                Err(error) => return Poll::Ready(Err(error)),
13753            };
13754            let arguments = match encode_typed_envelope(
13755                &normalize_avro_arguments(args),
13756                &state.payload_codec,
13757            ) {
13758                Ok(arguments) => arguments,
13759                Err(error) => return Poll::Ready(Err(error)),
13760            };
13761            let mut command = json!({
13762                "type": "start_child_workflow",
13763                "workflow_type": self.workflow_type,
13764                "queue": self.options.task_queue,
13765                "parent_close_policy": self.options.parent_close_policy.as_str(),
13766                "arguments": arguments,
13767            });
13768            let object = command
13769                .as_object_mut()
13770                .expect("child workflow command is always an object");
13771            if self.options.cancellation_policy != CancellationPolicy::Abandon {
13772                object.insert(
13773                    "cancellation_policy".to_string(),
13774                    json!(self.options.cancellation_policy.as_str()),
13775                );
13776            }
13777            if let Some(policy) = &self.options.retry_policy {
13778                let mut retry_policy = serde_json::Map::new();
13779                if let Some(max_attempts) = policy.max_attempts {
13780                    if max_attempts == 0 {
13781                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
13782                            "retry_policy.max_attempts must be at least 1".to_string(),
13783                        )));
13784                    }
13785                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
13786                }
13787                if !policy.backoff_seconds.is_empty() {
13788                    retry_policy
13789                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
13790                }
13791                if !policy.non_retryable_error_types.is_empty() {
13792                    retry_policy.insert(
13793                        "non_retryable_error_types".to_string(),
13794                        json!(policy.non_retryable_error_types),
13795                    );
13796                }
13797                if retry_policy.is_empty() {
13798                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
13799                        "retry_policy must configure at least one field".to_string(),
13800                    )));
13801                }
13802                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
13803            }
13804            if let Some(seconds) = self.options.execution_timeout_seconds {
13805                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
13806            }
13807            if let Some(seconds) = self.options.run_timeout_seconds {
13808                object.insert("run_timeout_seconds".to_string(), json!(seconds));
13809            }
13810            apply_parallel_group_path(object, &self.parallel_group_path);
13811            ctx.apply_scope_membership(object);
13812            match state.prepare_scalar_cancellation(
13813                cursor,
13814                CancellationCallKind::Child,
13815                &self.parallel_group_path,
13816            ) {
13817                Ok(true) => {
13818                    self.scheduled = true;
13819                    self.matched_pending = true;
13820                    return Poll::Pending;
13821                }
13822                Ok(false) => {}
13823                Err(error) => return Poll::Ready(Err(error)),
13824            }
13825            state.commands.push(command);
13826            self.scheduled = true;
13827        }
13828
13829        Poll::Pending
13830    }
13831}
13832
13833impl Future for ChildWorkflowCall {
13834    type Output = Result<ChildWorkflowResult>;
13835
13836    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13837        match self.poll_avro_value(cx) {
13838            Poll::Ready(Ok(result)) => match result.result.into_json() {
13839                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
13840                    parent: result.parent,
13841                    child: result.child,
13842                    child_workflow_type: result.child_workflow_type,
13843                    result: projected,
13844                })),
13845                Err(error) => Poll::Ready(Err(error)),
13846            },
13847            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13848            Poll::Pending => Poll::Pending,
13849        }
13850    }
13851}
13852
13853fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
13854    Error::NonDeterministicReplay(ReplayFailure::new(
13855        "recorded_command_mismatch",
13856        Some(recorded.sequence()),
13857        Some(recorded.shape().to_string()),
13858        Some(actual.into()),
13859        "current workflow command does not match the recorded durable command sequence",
13860    ))
13861}
13862
13863pub struct SignalCall {
13864    ctx: WorkflowContext,
13865    signal_name: String,
13866    runtime_reserved_allowed: bool,
13867    opened_wait: bool,
13868    matched_pending: bool,
13869    parallel_group_path: Vec<ParallelGroupMetadata>,
13870}
13871
13872impl SignalCall {
13873    fn poll_avro_value(
13874        mut self: Pin<&mut Self>,
13875        _cx: &mut TaskContext<'_>,
13876    ) -> Poll<Result<Vec<AvroValue>>> {
13877        if self.matched_pending {
13878            return Poll::Pending;
13879        }
13880        if !self.runtime_reserved_allowed {
13881            if let Err(error) = validate_user_signal_name(&self.signal_name) {
13882                return Poll::Ready(Err(error));
13883            }
13884        }
13885
13886        let ctx = self.ctx.clone();
13887        let mut state = match ctx.state.lock() {
13888            Ok(state) => state,
13889            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13890        };
13891
13892        let cursor = state.command_cursor;
13893        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13894            return Poll::Ready(Err(error));
13895        }
13896        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
13897        {
13898            Ok(recorded) => recorded,
13899            Err(error) => return Poll::Ready(Err(error)),
13900        };
13901        if let Some(recorded) = recorded {
13902            match recorded {
13903                RecordedCommand::SignalWait {
13904                    sequence,
13905                    signal_name,
13906                    value,
13907                    parallel_group_path,
13908                } => {
13909                    if let Err(error) = ensure_parallel_path_matches(
13910                        sequence,
13911                        parallel_group_path.as_deref(),
13912                        &self.parallel_group_path,
13913                    ) {
13914                        return Poll::Ready(Err(error));
13915                    }
13916                    if signal_name != self.signal_name {
13917                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13918                            ReplayFailure::new(
13919                                "recorded_command_detail_mismatch",
13920                                Some(sequence),
13921                                Some(format!("signal wait:{signal_name}")),
13922                                Some(format!("signal wait:{}", self.signal_name)),
13923                                "recorded signal name differs from the current workflow command",
13924                            ),
13925                        )));
13926                    }
13927
13928                    if let Err(error) =
13929                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
13930                    {
13931                        return Poll::Ready(Err(error));
13932                    }
13933                    match state.prepare_scalar_cancellation(
13934                        cursor,
13935                        CancellationCallKind::Signal,
13936                        &self.parallel_group_path,
13937                    ) {
13938                        Ok(true) => {
13939                            self.opened_wait = true;
13940                            self.matched_pending = true;
13941                            return Poll::Pending;
13942                        }
13943                        Ok(false) => {}
13944                        Err(error) => return Poll::Ready(Err(error)),
13945                    }
13946                    state.command_cursor += 1;
13947                    if let Some(value) = value {
13948                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13949                        return Poll::Ready(Ok(value));
13950                    }
13951                    if state
13952                        .resume_signal
13953                        .as_ref()
13954                        .is_some_and(|signal| signal.signal_name == self.signal_name)
13955                    {
13956                        let signal = state
13957                            .resume_signal
13958                            .take()
13959                            .expect("matching resume signal is present");
13960                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
13961                        return Poll::Ready(Ok(signal.arguments));
13962                    }
13963
13964                    state.matched_recorded_pending = true;
13965                    self.opened_wait = true;
13966                    self.matched_pending = true;
13967                    return Poll::Pending;
13968                }
13969                other => {
13970                    return Poll::Ready(Err(command_mismatch(
13971                        &other,
13972                        format!("signal wait:{}", self.signal_name),
13973                    )));
13974                }
13975            }
13976        }
13977
13978        match state.prepare_scalar_cancellation(
13979            cursor,
13980            CancellationCallKind::Signal,
13981            &self.parallel_group_path,
13982        ) {
13983            Ok(true) => {
13984                self.opened_wait = true;
13985                self.matched_pending = true;
13986                return Poll::Pending;
13987            }
13988            Ok(false) => {}
13989            Err(error) => return Poll::Ready(Err(error)),
13990        }
13991
13992        if state
13993            .resume_signal
13994            .as_ref()
13995            .is_some_and(|signal| signal.signal_name == self.signal_name)
13996        {
13997            let signal = state
13998                .resume_signal
13999                .take()
14000                .expect("matching resume signal is present");
14001            state.unavailable_cancellation_boundary(&self.parallel_group_path);
14002            return Poll::Ready(Ok(signal.arguments));
14003        }
14004
14005        if !self.opened_wait {
14006            let mut command = serde_json::Map::from_iter([
14007                ("type".to_string(), json!("open_signal_wait")),
14008                ("signal_name".to_string(), json!(self.signal_name)),
14009            ]);
14010            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14011            ctx.apply_scope_membership(&mut command);
14012            state.commands.push(Value::Object(command));
14013            self.opened_wait = true;
14014        }
14015
14016        Poll::Pending
14017    }
14018}
14019
14020impl Future for SignalCall {
14021    type Output = Result<Vec<Value>>;
14022
14023    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14024        match self.poll_avro_value(cx) {
14025            Poll::Ready(Ok(values)) => Poll::Ready(
14026                values
14027                    .into_iter()
14028                    .map(AvroValue::into_json)
14029                    .collect::<Result<Vec<_>>>(),
14030            ),
14031            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14032            Poll::Pending => Poll::Pending,
14033        }
14034    }
14035}
14036
14037#[derive(Clone, Debug)]
14038pub struct ActivityContext {
14039    client: Client,
14040    pub task_id: String,
14041    pub activity_attempt_id: String,
14042    pub lease_owner: String,
14043    pub activity_type: String,
14044    pub attempt_number: u64,
14045    pub task_queue: String,
14046    pub worker_id: String,
14047    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
14048}
14049
14050impl ActivityContext {
14051    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
14052        if let Some(guard) = &self.claim_guard {
14053            return guard.heartbeat(self, details).await;
14054        }
14055        self.client
14056            .heartbeat_activity_task(
14057                &self.task_id,
14058                &self.activity_attempt_id,
14059                &self.lease_owner,
14060                details,
14061            )
14062            .await
14063    }
14064}
14065
14066fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
14067    validate_payload_codec(codec)?;
14068    match value {
14069        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
14070            value, codec,
14071        )?)),
14072        None => Ok(AvroValue::Array(Vec::new())),
14073    }
14074}
14075
14076fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
14077    let Some(signal_name) = task
14078        .signal_name
14079        .as_deref()
14080        .filter(|value| !value.is_empty())
14081    else {
14082        return Ok(None);
14083    };
14084    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
14085    let AvroValue::Array(arguments) = decoded else {
14086        unreachable!("normalize_avro_arguments always returns an array");
14087    };
14088
14089    Ok(Some(ResumeSignal {
14090        signal_name: signal_name.to_string(),
14091        arguments,
14092    }))
14093}
14094
14095fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
14096    validate_payload_codec(&task.payload_codec)?;
14097    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
14098    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
14099    for event in &task.history_events {
14100        validate_history_event_payloads(event, &task.payload_codec)?;
14101    }
14102    Ok(())
14103}
14104
14105fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
14106    validate_payload_codec(&task.payload_codec)?;
14107    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
14108}
14109
14110fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
14111    validate_payload_codec(&task.payload_codec)?;
14112    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
14113    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
14114    for event in &task.history_events {
14115        validate_history_event_payloads(event, &task.payload_codec)?;
14116    }
14117
14118    let Some(export) = task.history_export.as_ref() else {
14119        return Ok(());
14120    };
14121    let export_codec = match export.get("payloads") {
14122        Some(payloads) => declared_payload_codec(payloads, "codec")?,
14123        None => None,
14124    }
14125    .unwrap_or(&task.payload_codec);
14126    validate_payload_codec(export_codec)?;
14127
14128    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
14129        for event in events {
14130            let event_type = event
14131                .get("event_type")
14132                .or_else(|| event.get("type"))
14133                .and_then(Value::as_str)
14134                .unwrap_or_default();
14135            if let Some(payload) = event.get("payload") {
14136                validate_history_payloads(event_type, payload, export_codec)?;
14137            }
14138        }
14139    }
14140    for signal in export
14141        .get("signals")
14142        .and_then(Value::as_array)
14143        .into_iter()
14144        .flatten()
14145    {
14146        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
14147        validate_payload_codec(codec)?;
14148        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
14149    }
14150    for activity in export
14151        .get("activities")
14152        .and_then(Value::as_array)
14153        .into_iter()
14154        .flatten()
14155    {
14156        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
14157        validate_payload_codec(codec)?;
14158        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
14159        validate_optional_inbound_payload(activity.get("result"), codec)?;
14160    }
14161    Ok(())
14162}
14163
14164fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
14165    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
14166}
14167
14168fn validate_history_payloads(
14169    event_type: &str,
14170    payload: &Value,
14171    fallback_codec: &str,
14172) -> Result<()> {
14173    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
14174    validate_payload_codec(codec)?;
14175    for field in history_payload_fields(event_type) {
14176        validate_optional_inbound_payload(payload.get(*field), codec)?;
14177    }
14178    Ok(())
14179}
14180
14181const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
14182
14183fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
14184    match event_type {
14185        "ActivityCompleted" => &["result"],
14186        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
14187        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
14188        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
14189        "ChildRunCompleted" => &["result", "output"],
14190        "WorkflowCompleted" => &["output"],
14191        "ServiceCallStarted"
14192        | "ServiceCallCompleted"
14193        | "ServiceCallFailed"
14194        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
14195        _ => &[],
14196    }
14197}
14198
14199fn signal_history_payload(payload: &Value) -> Option<&Value> {
14200    SIGNAL_HISTORY_PAYLOAD_FIELDS
14201        .iter()
14202        .find_map(|field| payload.get(*field))
14203}
14204
14205fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
14206    match value.get(field) {
14207        None => Ok(None),
14208        Some(Value::String(codec)) => Ok(Some(codec)),
14209        Some(_) => Err(invalid_payload_envelope()),
14210    }
14211}
14212
14213fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
14214    validate_payload_codec(codec)?;
14215    if let Some(value) = value.filter(|value| !value.is_null()) {
14216        decode_wire_avro_value(value, codec)?;
14217    }
14218    Ok(())
14219}
14220
14221fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
14222    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
14223        invalid_recorded_history(
14224            "parallel_group_metadata_invalid",
14225            sequence,
14226            "non-empty parallel_group_id",
14227            &payload.to_string(),
14228            "parallel-group history is missing its stable identity",
14229        )
14230    })?;
14231    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
14232        invalid_recorded_history(
14233            "parallel_group_metadata_invalid",
14234            sequence,
14235            "activity, child, timer, signal, condition, or mixed group kind",
14236            &payload.to_string(),
14237            "parallel-group history is missing its group kind",
14238        )
14239    })?;
14240    if !matches!(
14241        kind.as_str(),
14242        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
14243    ) {
14244        return Err(invalid_recorded_history(
14245            "parallel_group_metadata_invalid",
14246            sequence,
14247            "activity, child, timer, signal, condition, or mixed group kind",
14248            &kind,
14249            "parallel-group history contains an unsupported group kind",
14250        ));
14251    }
14252    let base_sequence = payload
14253        .get("parallel_group_base_sequence")
14254        .and_then(value_as_u64)
14255        .filter(|value| *value > 0)
14256        .ok_or_else(|| {
14257            invalid_recorded_history(
14258                "parallel_group_metadata_invalid",
14259                sequence,
14260                "positive parallel_group_base_sequence",
14261                &payload.to_string(),
14262                "parallel-group history contains an invalid base sequence",
14263            )
14264        })?;
14265    let size = payload
14266        .get("parallel_group_size")
14267        .and_then(value_as_u64)
14268        .and_then(|value| usize::try_from(value).ok())
14269        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
14270        .ok_or_else(|| {
14271            invalid_recorded_history(
14272                "parallel_group_metadata_invalid",
14273                sequence,
14274                "bounded positive parallel_group_size",
14275                &payload.to_string(),
14276                "parallel-group history contains an invalid group size",
14277            )
14278        })?;
14279    let index = payload
14280        .get("parallel_group_index")
14281        .and_then(value_as_u64)
14282        .and_then(|value| usize::try_from(value).ok())
14283        .filter(|value| *value < size)
14284        .ok_or_else(|| {
14285            invalid_recorded_history(
14286                "parallel_group_metadata_invalid",
14287                sequence,
14288                "parallel_group_index within group bounds",
14289                &payload.to_string(),
14290                "parallel-group history contains an invalid member index",
14291            )
14292        })?;
14293    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
14294        return Err(invalid_recorded_history(
14295            "parallel_group_metadata_invalid",
14296            sequence,
14297            "base sequence plus member index equals workflow sequence",
14298            &payload.to_string(),
14299            "parallel-group path does not preserve durable workflow position",
14300        ));
14301    }
14302    let mode = payload
14303        .get("parallel_group_mode")
14304        .and_then(Value::as_str)
14305        .unwrap_or("all");
14306    if !matches!(mode, "all" | "select") {
14307        return Err(invalid_recorded_history(
14308            "parallel_group_metadata_invalid",
14309            sequence,
14310            "parallel group mode all or select",
14311            mode,
14312            "parallel-group history contains an unsupported group mode",
14313        ));
14314    }
14315    let expected_id = if mode == "select" {
14316        format!("select-calls:{base_sequence}:{size}")
14317    } else {
14318        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
14319    };
14320    if group_id != expected_id {
14321        return Err(invalid_recorded_history(
14322            "parallel_group_metadata_invalid",
14323            sequence,
14324            &expected_id,
14325            &group_id,
14326            "parallel-group history contains an incompatible stable group ID",
14327        ));
14328    }
14329    let selection_member_key = if mode == "select" {
14330        Some(selection_key_from_value(
14331            payload.get("selection_member_key"),
14332            sequence,
14333        )?)
14334    } else {
14335        None
14336    };
14337    let selection_member_index = if mode == "select" {
14338        Some(required_parallel_usize(
14339            payload,
14340            "selection_member_index",
14341            sequence,
14342        )?)
14343    } else {
14344        None
14345    };
14346    let selection_member_base_sequence = if mode == "select" {
14347        Some(
14348            payload
14349                .get("selection_member_base_sequence")
14350                .and_then(value_as_u64)
14351                .filter(|value| *value >= base_sequence)
14352                .ok_or_else(|| {
14353                    invalid_recorded_history(
14354                        "parallel_group_metadata_invalid",
14355                        sequence,
14356                        "selection member base within its group",
14357                        &payload.to_string(),
14358                        "selection history contains an invalid member base sequence",
14359                    )
14360                })?,
14361        )
14362    } else {
14363        None
14364    };
14365    let selection_member_size = if mode == "select" {
14366        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
14367        if member_size == 0 {
14368            return Err(invalid_recorded_history(
14369                "parallel_group_metadata_invalid",
14370                sequence,
14371                "positive selection member size",
14372                &payload.to_string(),
14373                "selection history contains an invalid member size",
14374            ));
14375        }
14376        Some(member_size)
14377    } else {
14378        None
14379    };
14380    let selection_member_kind = if mode == "select" {
14381        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
14382            invalid_recorded_history(
14383                "parallel_group_metadata_invalid",
14384                sequence,
14385                "selection member operation kind",
14386                &payload.to_string(),
14387                "selection history is missing its authored member kind",
14388            )
14389        })?;
14390        if !matches!(
14391            kind.as_str(),
14392            "activity" | "child" | "timer" | "signal" | "condition" | "group"
14393        ) {
14394            return Err(invalid_recorded_history(
14395                "parallel_group_metadata_invalid",
14396                sequence,
14397                "activity, child, timer, signal, condition, or group selection member kind",
14398                &kind,
14399                "selection history contains an unsupported member kind",
14400            ));
14401        }
14402        Some(kind)
14403    } else {
14404        None
14405    };
14406    if let (Some(member_base), Some(member_size)) =
14407        (selection_member_base_sequence, selection_member_size)
14408    {
14409        let member_end = member_base
14410            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
14411            .ok_or_else(|| {
14412                invalid_recorded_history(
14413                    "parallel_group_metadata_invalid",
14414                    sequence,
14415                    "bounded selection member range",
14416                    &payload.to_string(),
14417                    "selection member range overflowed",
14418                )
14419            })?;
14420        let group_end = base_sequence
14421            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
14422            .unwrap_or(u64::MAX);
14423        if sequence < member_base || sequence >= member_end || member_end > group_end {
14424            return Err(invalid_recorded_history(
14425                "parallel_group_metadata_invalid",
14426                sequence,
14427                "workflow sequence within one bounded selection member",
14428                &payload.to_string(),
14429                "selection member range does not contain its durable leaf",
14430            ));
14431        }
14432    }
14433    Ok(ParallelGroupMetadata {
14434        parallel_group_id: group_id,
14435        parallel_group_kind: kind,
14436        parallel_group_base_sequence: base_sequence,
14437        parallel_group_size: size,
14438        parallel_group_index: index,
14439        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
14440        selection_member_key,
14441        selection_member_index,
14442        selection_member_base_sequence,
14443        selection_member_size,
14444        selection_member_kind,
14445    })
14446}
14447
14448fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
14449    payload
14450        .get(field)
14451        .and_then(value_as_u64)
14452        .and_then(|value| usize::try_from(value).ok())
14453        .ok_or_else(|| {
14454            invalid_recorded_history(
14455                "parallel_group_metadata_invalid",
14456                sequence,
14457                &format!("non-negative integer {field}"),
14458                &payload.to_string(),
14459                "selection history contains invalid member metadata",
14460            )
14461        })
14462}
14463
14464fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
14465    match value {
14466        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
14467        Some(value) => value_as_u64(value)
14468            .and_then(|value| usize::try_from(value).ok())
14469            .map(SelectionKey::Index)
14470            .ok_or_else(|| {
14471                invalid_recorded_history(
14472                    "selection_member_key_invalid",
14473                    sequence,
14474                    "non-empty string or non-negative integer member key",
14475                    &value.to_string(),
14476                    "selection history contains an invalid member key",
14477                )
14478            }),
14479        None => Err(invalid_recorded_history(
14480            "selection_member_key_missing",
14481            sequence,
14482            "selection_member_key",
14483            "<missing>",
14484            "selection history is missing its stable member key",
14485        )),
14486    }
14487}
14488
14489fn recorded_parallel_group_path(
14490    events: &[&HistoryEvent],
14491    sequence: u64,
14492) -> Result<Option<Vec<ParallelGroupMetadata>>> {
14493    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
14494    for event in events {
14495        let payload = &event.payload;
14496        let has_metadata = payload.get("parallel_group_path").is_some()
14497            || payload.get("parallel_group_id").is_some()
14498            || payload.get("parallel_group_kind").is_some()
14499            || payload.get("parallel_group_base_sequence").is_some()
14500            || payload.get("parallel_group_size").is_some()
14501            || payload.get("parallel_group_index").is_some()
14502            || payload.get("parallel_group_mode").is_some()
14503            || payload.get("selection_member_key").is_some();
14504        if !has_metadata {
14505            continue;
14506        }
14507
14508        let top_level = recorded_parallel_group_entry(payload, sequence)?;
14509        let path = match payload.get("parallel_group_path") {
14510            None => vec![top_level.clone()],
14511            Some(Value::Array(entries)) if !entries.is_empty() => entries
14512                .iter()
14513                .map(|entry| recorded_parallel_group_entry(entry, sequence))
14514                .collect::<Result<Vec<_>>>()?,
14515            Some(value) => {
14516                return Err(invalid_recorded_history(
14517                    "parallel_group_metadata_invalid",
14518                    sequence,
14519                    "non-empty parallel_group_path list",
14520                    &value.to_string(),
14521                    "parallel-group history contains an invalid group path",
14522                ));
14523            }
14524        };
14525        if path.last() != Some(&top_level) {
14526            return Err(invalid_recorded_history(
14527                "parallel_group_metadata_invalid",
14528                sequence,
14529                &serde_json::to_string(&path.last()).unwrap_or_default(),
14530                &serde_json::to_string(&top_level).unwrap_or_default(),
14531                "parallel-group top-level fields do not match the innermost path entry",
14532            ));
14533        }
14534        if recorded.as_ref().is_some_and(|existing| existing != &path) {
14535            return Err(invalid_recorded_history(
14536                "parallel_group_history_conflict",
14537                sequence,
14538                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
14539                &serde_json::to_string(&path).unwrap_or_default(),
14540                "parallel-group metadata changed between scheduling and resolution history",
14541            ));
14542        }
14543        recorded = Some(path);
14544    }
14545    Ok(recorded)
14546}
14547
14548fn recorded_commands(
14549    events: &[HistoryEvent],
14550    fallback_codec: &str,
14551    parent: WorkflowIdentity,
14552) -> Result<Vec<RecordedCommand>> {
14553    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
14554    let mut last_new_sequence = None;
14555
14556    for event in events {
14557        let is_activity = matches!(
14558            event.event_type.as_str(),
14559            "ActivityScheduled"
14560                | "ActivityStarted"
14561                | "ActivityHeartbeatRecorded"
14562                | "ActivityRetryScheduled"
14563                | "ActivityCompleted"
14564                | "ActivityFailed"
14565                | "ActivityCancelled"
14566                | "ActivityTimedOut"
14567        );
14568        let is_workflow_timer = matches!(
14569            event.event_type.as_str(),
14570            "TimerScheduled" | "TimerCancelled" | "TimerFired"
14571        ) && !is_internal_timer_event(event);
14572        let is_child_workflow = matches!(
14573            event.event_type.as_str(),
14574            "ChildWorkflowScheduled"
14575                | "ChildRunStarted"
14576                | "ChildRunCompleted"
14577                | "ChildRunFailed"
14578                | "ChildRunCancelled"
14579                | "ChildRunTerminated"
14580        );
14581        let is_signal_wait = is_recorded_signal_wait_event(event);
14582        let is_condition_wait = is_recorded_condition_wait_event(event);
14583        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
14584        let is_side_effect = event.event_type == "SideEffectRecorded";
14585        let is_version_marker = event.event_type == "VersionMarkerRecorded";
14586        let is_memo = event.event_type == "MemoUpserted";
14587        if !is_activity
14588            && !is_workflow_timer
14589            && !is_child_workflow
14590            && !is_signal_wait
14591            && !is_condition_wait
14592            && !is_search_attributes
14593            && !is_side_effect
14594            && !is_version_marker
14595            && !is_memo
14596        {
14597            continue;
14598        }
14599
14600        let sequence = durable_event_sequence(event).ok_or_else(|| {
14601            Error::NonDeterministicReplay(ReplayFailure::new(
14602                "durable_command_sequence_missing",
14603                None,
14604                Some("positive workflow sequence".to_string()),
14605                Some(event.event_type.clone()),
14606                "durable command history event has no workflow sequence",
14607            ))
14608        })?;
14609        if sequence == 0 {
14610            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14611                "durable_command_sequence_invalid",
14612                Some(sequence),
14613                Some("positive workflow sequence".to_string()),
14614                Some(sequence.to_string()),
14615                "durable command history uses an invalid workflow sequence",
14616            )));
14617        }
14618        if !events_by_sequence.contains_key(&sequence) {
14619            if let Some(previous) = last_new_sequence {
14620                if sequence < previous {
14621                    return Err(invalid_recorded_history(
14622                        "durable_command_sequence_mismatch",
14623                        sequence,
14624                        &format!("workflow sequence greater than {previous}"),
14625                        &sequence.to_string(),
14626                        "durable commands are not strictly ordered by their recorded workflow sequence",
14627                    ));
14628                }
14629            }
14630            last_new_sequence = Some(sequence);
14631        }
14632        events_by_sequence.entry(sequence).or_default().push(event);
14633    }
14634
14635    let commands: Vec<RecordedCommand> = events_by_sequence
14636        .into_iter()
14637        .map(|(sequence, sequence_events)| {
14638            let activity_events: Vec<_> = sequence_events
14639                .iter()
14640                .copied()
14641                .filter(|event| event.event_type.starts_with("Activity"))
14642                .collect();
14643            let timer_events: Vec<_> = sequence_events
14644                .iter()
14645                .copied()
14646                .filter(|event| event.event_type.starts_with("Timer"))
14647                .collect();
14648            let child_events: Vec<_> = sequence_events
14649                .iter()
14650                .copied()
14651                .filter(|event| {
14652                    event.event_type == "ChildWorkflowScheduled"
14653                        || event.event_type.starts_with("ChildRun")
14654                })
14655                .collect();
14656            let signal_wait_events: Vec<_> = sequence_events
14657                .iter()
14658                .copied()
14659                .filter(|event| is_recorded_signal_wait_event(event))
14660                .collect();
14661            let condition_wait_events: Vec<_> = sequence_events
14662                .iter()
14663                .copied()
14664                .filter(|event| is_recorded_condition_wait_event(event))
14665                .collect();
14666            let search_attribute_events: Vec<_> = sequence_events
14667                .iter()
14668                .copied()
14669                .filter(|event| event.event_type == "SearchAttributesUpserted")
14670                .collect();
14671            let side_effect_events: Vec<_> = sequence_events
14672                .iter()
14673                .copied()
14674                .filter(|event| event.event_type == "SideEffectRecorded")
14675                .collect();
14676            let version_marker_events: Vec<_> = sequence_events
14677                .iter()
14678                .copied()
14679                .filter(|event| event.event_type == "VersionMarkerRecorded")
14680                .collect();
14681            let memo_events: Vec<_> = sequence_events
14682                .iter()
14683                .copied()
14684                .filter(|event| event.event_type == "MemoUpserted")
14685                .collect();
14686
14687            let command_kind_count = usize::from(!activity_events.is_empty())
14688                + usize::from(!timer_events.is_empty())
14689                + usize::from(!child_events.is_empty())
14690                + usize::from(!signal_wait_events.is_empty())
14691                + usize::from(!condition_wait_events.is_empty())
14692                + usize::from(!search_attribute_events.is_empty())
14693                + usize::from(!side_effect_events.is_empty())
14694                + usize::from(!version_marker_events.is_empty())
14695                + usize::from(!memo_events.is_empty());
14696            if command_kind_count > 1 {
14697                let actual = [
14698                    (!activity_events.is_empty()).then_some("activity"),
14699                    (!timer_events.is_empty()).then_some("timer"),
14700                    (!child_events.is_empty()).then_some("child workflow"),
14701                    (!signal_wait_events.is_empty()).then_some("signal wait"),
14702                    (!condition_wait_events.is_empty()).then_some("condition wait"),
14703                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
14704                    (!side_effect_events.is_empty()).then_some("side effect"),
14705                    (!version_marker_events.is_empty()).then_some("version marker"),
14706                    (!memo_events.is_empty()).then_some("memo upsert"),
14707                ]
14708                .into_iter()
14709                .flatten()
14710                .collect::<Vec<_>>()
14711                .join(" and ");
14712                return Err(invalid_recorded_history(
14713                    "durable_command_sequence_collision",
14714                    sequence,
14715                    "one durable command kind",
14716                    &actual,
14717                    "one workflow sequence records more than one durable command kind",
14718                ));
14719            }
14720
14721            if !activity_events.is_empty() {
14722                let parallel_group_path =
14723                    recorded_parallel_group_path(&activity_events, sequence)?;
14724                let scheduled_count = activity_events
14725                    .iter()
14726                    .filter(|event| event.event_type == "ActivityScheduled")
14727                    .count();
14728                if scheduled_count > 1 {
14729                    return Err(invalid_recorded_history(
14730                        "duplicate_activity_schedule",
14731                        sequence,
14732                        "at most one ActivityScheduled event",
14733                        "multiple ActivityScheduled events",
14734                        "activity history schedules more than one command at one workflow sequence",
14735                    ));
14736                }
14737                let activity_type = activity_events.iter().find_map(|event| {
14738                    event
14739                        .payload
14740                        .get("activity_type")
14741                        .or_else(|| event.payload.get("activity_name"))
14742                        .and_then(Value::as_str)
14743                        .map(str::to_string)
14744                });
14745                if activity_events.iter().filter_map(|event| {
14746                    event
14747                        .payload
14748                        .get("activity_type")
14749                        .or_else(|| event.payload.get("activity_name"))
14750                        .and_then(Value::as_str)
14751                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
14752                    return Err(invalid_recorded_history(
14753                        "activity_identity_mismatch",
14754                        sequence,
14755                        activity_type.as_deref().unwrap_or("one activity identity"),
14756                        "conflicting activity identities",
14757                        "activity lifecycle events at one workflow sequence disagree on identity",
14758                    ));
14759                }
14760                let terminal: Vec<_> = activity_events
14761                    .iter()
14762                    .copied()
14763                    .filter(|event| {
14764                        matches!(
14765                            event.event_type.as_str(),
14766                            "ActivityCompleted"
14767                                | "ActivityFailed"
14768                                | "ActivityCancelled"
14769                                | "ActivityTimedOut"
14770                        )
14771                    })
14772                    .collect();
14773                let duplicate_delivery = terminal.first().is_some_and(|first| {
14774                    terminal.iter().all(|event| {
14775                        event.event_type == first.event_type && event.payload == first.payload
14776                    })
14777                });
14778                if terminal.len() > 1 && !duplicate_delivery {
14779                    return Err(invalid_recorded_history(
14780                        "duplicate_activity_terminal_event",
14781                        sequence,
14782                        "at most one terminal activity event",
14783                        "multiple terminal activity events",
14784                        "activity history settles one command more than once",
14785                    ));
14786                }
14787                let outcome = terminal
14788                    .first()
14789                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
14790                    .transpose()?;
14791                let options = activity_events
14792                    .iter()
14793                    .find(|event| event.event_type == "ActivityScheduled")
14794                    .and_then(|event| event.payload.get("activity"))
14795                    .and_then(Value::as_object)
14796                    .map(|activity| RecordedActivityOptions {
14797                        task_queue: recorded_optional_string(activity, "queue"),
14798                        execution_mode: recorded_optional_string(activity, "execution_mode"),
14799                        retry_policy: recorded_activity_retry_snapshot(
14800                            activity.get("retry_policy"),
14801                        ),
14802                    });
14803                return Ok(RecordedCommand::Activity {
14804                    sequence,
14805                    activity_type,
14806                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
14807                    options,
14808                    outcome,
14809                    parallel_group_path,
14810                });
14811            }
14812
14813            if !child_events.is_empty() {
14814                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
14815                let scheduled: Vec<_> = child_events
14816                    .iter()
14817                    .copied()
14818                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
14819                    .collect();
14820                if scheduled.len() != 1 {
14821                    return Err(invalid_recorded_history(
14822                        "child_workflow_schedule_missing_or_duplicate",
14823                        sequence,
14824                        "one ChildWorkflowScheduled event",
14825                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
14826                        "child workflow replay requires exactly one recorded schedule event",
14827                    ));
14828                }
14829                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
14830                let workflow_type = child_events.iter().find_map(|event| {
14831                    event
14832                        .payload
14833                        .get("child_workflow_type")
14834                        .or_else(|| event.payload.get("workflow_type"))
14835                        .and_then(Value::as_str)
14836                        .filter(|value| !value.is_empty())
14837                        .map(str::to_string)
14838                });
14839                if child_events
14840                    .iter()
14841                    .filter_map(|event| {
14842                        event
14843                            .payload
14844                            .get("child_workflow_type")
14845                            .or_else(|| event.payload.get("workflow_type"))
14846                            .and_then(Value::as_str)
14847                    })
14848                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
14849                {
14850                    return Err(invalid_recorded_history(
14851                        "child_workflow_identity_mismatch",
14852                        sequence,
14853                        workflow_type
14854                            .as_deref()
14855                            .unwrap_or("one child workflow type"),
14856                        "conflicting child workflow types",
14857                        "child workflow lifecycle events at one sequence disagree on type",
14858                    ));
14859                }
14860                let mut outcomes = child_workflow_outcomes(
14861                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
14862                    fallback_codec,
14863                    parent.clone(),
14864                )?;
14865                let terminal_events = child_events
14866                    .iter()
14867                    .copied()
14868                    .filter(|event| event.event_type.starts_with("ChildRun"))
14869                    .collect::<Vec<_>>();
14870                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
14871                    terminal_events.iter().all(|event| {
14872                        event.event_type == first.event_type && event.payload == first.payload
14873                    })
14874                });
14875                if outcomes.len() > 1 && !duplicate_delivery {
14876                    return Err(invalid_recorded_history(
14877                        "duplicate_child_workflow_terminal_event",
14878                        sequence,
14879                        "at most one terminal child event",
14880                        "multiple terminal child events",
14881                        "child workflow history settles one command more than once",
14882                    ));
14883                }
14884                return Ok(RecordedCommand::ChildWorkflow {
14885                    sequence,
14886                    workflow_type,
14887                    policies,
14888                    outcome: outcomes.pop(),
14889                    parallel_group_path,
14890                });
14891            }
14892
14893            if !signal_wait_events.is_empty() {
14894                let opened: Vec<_> = signal_wait_events
14895                    .iter()
14896                    .copied()
14897                    .filter(|event| event.event_type == "SignalWaitOpened")
14898                    .collect();
14899                if opened.len() != 1 {
14900                    return Err(invalid_recorded_history(
14901                        "signal_wait_open_missing_or_duplicate",
14902                        sequence,
14903                        "one SignalWaitOpened event",
14904                        &format!("{} SignalWaitOpened events", opened.len()),
14905                        "signal replay requires exactly one canonical wait-open event",
14906                    ));
14907                }
14908
14909                let applied: Vec<_> = signal_wait_events
14910                    .iter()
14911                    .copied()
14912                    .filter(|event| event.event_type == "SignalApplied")
14913                    .collect();
14914                if applied.len() > 1 {
14915                    return Err(invalid_recorded_history(
14916                        "duplicate_signal_wait_apply",
14917                        sequence,
14918                        "at most one SignalApplied event",
14919                        "multiple SignalApplied events",
14920                        "signal history applies one durable wait more than once",
14921                    ));
14922                }
14923
14924                let signal_names = signal_wait_events
14925                    .iter()
14926                    .map(|event| required_signal_wait_name(event, sequence))
14927                    .collect::<Result<Vec<_>>>()?;
14928                let signal_name = signal_names
14929                    .first()
14930                    .expect("signal wait events are not empty")
14931                    .clone();
14932                if signal_names.iter().any(|candidate| candidate != &signal_name) {
14933                    return Err(invalid_recorded_history(
14934                        "signal_wait_identity_mismatch",
14935                        sequence,
14936                        &signal_name,
14937                        "conflicting signal names",
14938                        "signal wait lifecycle events at one workflow sequence disagree on identity",
14939                    ));
14940                }
14941                let value = applied
14942                    .first()
14943                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
14944                    .transpose()?;
14945                return Ok(RecordedCommand::SignalWait {
14946                    sequence,
14947                    signal_name,
14948                    value,
14949                    parallel_group_path: recorded_parallel_group_path(
14950                        &signal_wait_events,
14951                        sequence,
14952                    )?,
14953                });
14954            }
14955
14956            if !condition_wait_events.is_empty() {
14957                return recorded_condition_wait(
14958                    sequence,
14959                    &condition_wait_events,
14960                    events,
14961                );
14962            }
14963
14964            if !search_attribute_events.is_empty() {
14965                if search_attribute_events.len() != 1 {
14966                    return Err(invalid_recorded_history(
14967                        "duplicate_search_attribute_update",
14968                        sequence,
14969                        "one SearchAttributesUpserted event",
14970                        &format!(
14971                            "{} SearchAttributesUpserted events",
14972                            search_attribute_events.len()
14973                        ),
14974                        "search-attribute history records one workflow command more than once",
14975                    ));
14976                }
14977                let payload = &search_attribute_events[0].payload;
14978                let attributes = payload
14979                    .get("attributes")
14980                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
14981                    .cloned()
14982                    .ok_or_else(|| {
14983                        invalid_recorded_history(
14984                            "search_attribute_update_missing",
14985                            sequence,
14986                            "non-empty attributes object",
14987                            "missing or invalid attributes",
14988                            "search-attribute history is missing its recorded mutation",
14989                        )
14990                    })?;
14991                let attribute_types =
14992                    recorded_search_attribute_types(payload, &attributes, sequence)?;
14993                return Ok(RecordedCommand::SearchAttributes {
14994                    sequence,
14995                    attributes,
14996                    attribute_types,
14997                });
14998            }
14999
15000            if !side_effect_events.is_empty() {
15001                if side_effect_events.len() != 1 {
15002                    return Err(invalid_recorded_history(
15003                        "duplicate_side_effect_record",
15004                        sequence,
15005                        "one SideEffectRecorded event",
15006                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
15007                        "side-effect history records one workflow command more than once",
15008                    ));
15009                }
15010                let event = side_effect_events[0];
15011                let result = event.payload.get("result").ok_or_else(|| {
15012                    invalid_recorded_history(
15013                        "side_effect_result_missing",
15014                        sequence,
15015                        "recorded result payload",
15016                        "missing result",
15017                        "side-effect history is missing its recorded value",
15018                    )
15019                })?;
15020                let has_published_envelope = result.as_str().is_some()
15021                    || result.as_object().is_some_and(|envelope| {
15022                        envelope.get("codec").and_then(Value::as_str).is_some()
15023                            && envelope.get("blob").and_then(Value::as_str).is_some()
15024                    });
15025                if !has_published_envelope {
15026                    return Err(invalid_recorded_history(
15027                        "side_effect_payload_malformed",
15028                        sequence,
15029                        "payload blob or {codec, blob} envelope",
15030                        &result.to_string(),
15031                        "side-effect history result does not use a published payload envelope",
15032                    ));
15033                }
15034                let codec = event
15035                    .payload
15036                    .get("payload_codec")
15037                    .and_then(Value::as_str)
15038                    .unwrap_or(fallback_codec);
15039                let value = decode_wire_avro_value(result, codec).map_err(|error| {
15040                    if error.to_string().contains("unsupported_payload_codec") {
15041                        return error;
15042                    }
15043
15044                    invalid_recorded_history(
15045                        "side_effect_payload_incompatible",
15046                        sequence,
15047                        &format!("valid {codec} payload envelope"),
15048                        &error.to_string(),
15049                        "side-effect history payload cannot be decoded with its recorded codec",
15050                    )
15051                })?;
15052                return Ok(RecordedCommand::SideEffect { sequence, value });
15053            }
15054
15055            if !version_marker_events.is_empty() {
15056                if version_marker_events.len() != 1 {
15057                    return Err(invalid_recorded_history(
15058                        "duplicate_version_marker_record",
15059                        sequence,
15060                        "one VersionMarkerRecorded event",
15061                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
15062                        "version-marker history records one workflow command more than once",
15063                    ));
15064                }
15065                let payload = &version_marker_events[0].payload;
15066                let change_id = payload
15067                    .get("change_id")
15068                    .and_then(Value::as_str)
15069                    .filter(|value| !value.is_empty())
15070                    .map(str::to_string)
15071                    .ok_or_else(|| {
15072                        invalid_recorded_history(
15073                            "version_marker_field_missing",
15074                            sequence,
15075                            "non-empty change_id",
15076                            "missing or invalid change_id",
15077                            "version-marker history is missing its stable change ID",
15078                        )
15079                    })?;
15080                let version = required_version_i32(payload, "version", sequence)?;
15081                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
15082                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
15083                if min_supported > max_supported || version < min_supported || version > max_supported {
15084                    return Err(invalid_recorded_history(
15085                        "version_marker_history_range_invalid",
15086                        sequence,
15087                        "min_supported <= version <= max_supported",
15088                        &format!("{min_supported} <= {version} <= {max_supported}"),
15089                        "recorded version marker contains an internally incompatible range",
15090                    ));
15091                }
15092                return Ok(RecordedCommand::VersionMarker {
15093                    sequence,
15094                    change_id,
15095                    version,
15096                });
15097            }
15098
15099            if !memo_events.is_empty() {
15100                if memo_events.len() != 1 {
15101                    return Err(invalid_recorded_history(
15102                        "duplicate_memo_upsert_record",
15103                        sequence,
15104                        "one MemoUpserted event",
15105                        &format!("{} MemoUpserted events", memo_events.len()),
15106                        "memo history records one workflow update more than once",
15107                    ));
15108                }
15109                let payload = &memo_events[0].payload;
15110                let entries = payload.get("entries").cloned().ok_or_else(|| {
15111                    invalid_recorded_history(
15112                        "memo_entries_missing",
15113                        sequence,
15114                        "memo entries object",
15115                        "missing entries",
15116                        "MemoUpserted history is missing replay identity entries",
15117                    )
15118                })?;
15119                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
15120                    invalid_recorded_history(
15121                        "memo_entries_invalid",
15122                        sequence,
15123                        "valid canonical memo entries",
15124                        &error.to_string(),
15125                        "MemoUpserted history contains invalid replay identity entries",
15126                    )
15127                })?;
15128                let merged = payload.get("merged").cloned().ok_or_else(|| {
15129                    invalid_recorded_history(
15130                        "memo_merged_projection_missing",
15131                        sequence,
15132                        "merged memo projection",
15133                        "missing merged",
15134                        "MemoUpserted history is missing its merged projection",
15135                    )
15136                })?;
15137                decode_memo_history_map(&merged, false).map_err(|error| {
15138                    invalid_recorded_history(
15139                        "memo_merged_projection_invalid",
15140                        sequence,
15141                        "valid merged memo projection",
15142                        &error.to_string(),
15143                        "MemoUpserted history contains an invalid merged projection",
15144                    )
15145                })?;
15146
15147                return Ok(RecordedCommand::Memo { sequence, entries });
15148            }
15149            let scheduled: Vec<_> = timer_events
15150                .iter()
15151                .copied()
15152                .filter(|event| event.event_type == "TimerScheduled")
15153                .collect();
15154            let fired: Vec<_> = timer_events
15155                .iter()
15156                .copied()
15157                .filter(|event| event.event_type == "TimerFired")
15158                .collect();
15159            if scheduled.len() != 1 {
15160                return Err(invalid_recorded_history(
15161                    "timer_schedule_missing_or_duplicate",
15162                    sequence,
15163                    "one TimerScheduled event",
15164                    &format!("{} TimerScheduled events", scheduled.len()),
15165                    "timer replay requires exactly one recorded schedule event",
15166                ));
15167            }
15168            if fired.len() > 1 {
15169                return Err(invalid_recorded_history(
15170                    "duplicate_timer_fire",
15171                    sequence,
15172                    "at most one TimerFired event",
15173                    "multiple TimerFired events",
15174                    "timer history contains more than one fire event for a workflow sequence",
15175                ));
15176            }
15177
15178            let scheduled = scheduled[0];
15179            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
15180            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
15181            if let Some(fired) = fired.first() {
15182                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
15183                if fired_timer_id != timer_id {
15184                    return Err(invalid_recorded_history(
15185                        "timer_identity_mismatch",
15186                        sequence,
15187                        &timer_id,
15188                        &fired_timer_id,
15189                        "TimerFired does not correspond to the recorded TimerScheduled event",
15190                    ));
15191                }
15192                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
15193                if fired_delay != delay_seconds {
15194                    return Err(invalid_recorded_history(
15195                        "timer_history_delay_mismatch",
15196                        sequence,
15197                        &delay_seconds.to_string(),
15198                        &fired_delay.to_string(),
15199                        "TimerScheduled and TimerFired record different delays",
15200                    ));
15201                }
15202            }
15203
15204            Ok(RecordedCommand::Timer {
15205                sequence,
15206                delay_seconds,
15207                fired: !fired.is_empty(),
15208                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
15209            })
15210        })
15211        .collect::<Result<_>>()?;
15212
15213    let mut marker_sequences = HashMap::new();
15214    for command in &commands {
15215        if let RecordedCommand::VersionMarker {
15216            sequence,
15217            change_id,
15218            ..
15219        } = command
15220        {
15221            if let Some(first_sequence) = marker_sequences.insert(change_id.clone(), *sequence) {
15222                return Err(invalid_recorded_history(
15223                    "duplicate_version_marker",
15224                    *sequence,
15225                    &format!("one marker for change ID {change_id:?}"),
15226                    &format!("markers at sequences {first_sequence} and {sequence}"),
15227                    "workflow history contains duplicate markers for one stable change ID",
15228                ));
15229            }
15230        }
15231    }
15232
15233    Ok(commands)
15234}
15235
15236fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
15237    payload
15238        .get(field)
15239        .and_then(Value::as_i64)
15240        .and_then(|value| i32::try_from(value).ok())
15241        .ok_or_else(|| {
15242            invalid_recorded_history(
15243                "version_marker_field_missing",
15244                sequence,
15245                &format!("integer {field}"),
15246                "missing or out-of-range integer",
15247                "version-marker history is missing a required integer field",
15248            )
15249        })
15250}
15251
15252fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
15253    event
15254        .payload
15255        .get("sequence")
15256        .or_else(|| event.payload.get("workflow_sequence"))
15257        .or_else(|| event.raw.get("sequence"))
15258        .or_else(|| event.raw.get("workflow_sequence"))
15259        .and_then(value_as_u64)
15260}
15261
15262fn is_internal_timer_event(event: &HistoryEvent) -> bool {
15263    matches!(
15264        event
15265            .payload
15266            .get("timer_kind")
15267            .or_else(|| event.raw.get("timer_kind"))
15268            .and_then(Value::as_str),
15269        Some("condition_timeout" | "signal_timeout")
15270    )
15271}
15272
15273fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
15274    matches!(
15275        event.event_type.as_str(),
15276        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15277    )
15278}
15279
15280fn recorded_condition_wait(
15281    sequence: u64,
15282    condition_events: &[&HistoryEvent],
15283    all_events: &[HistoryEvent],
15284) -> Result<RecordedCommand> {
15285    let opened = condition_events
15286        .iter()
15287        .copied()
15288        .filter(|event| event.event_type == "ConditionWaitOpened")
15289        .collect::<Vec<_>>();
15290    if opened.len() != 1 {
15291        return Err(invalid_recorded_history(
15292            "condition_wait_open_missing_or_duplicate",
15293            sequence,
15294            "one ConditionWaitOpened event",
15295            &format!("{} ConditionWaitOpened events", opened.len()),
15296            "condition replay requires exactly one canonical wait-open event",
15297        ));
15298    }
15299    let terminal = condition_events
15300        .iter()
15301        .copied()
15302        .filter(|event| {
15303            matches!(
15304                event.event_type.as_str(),
15305                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15306            )
15307        })
15308        .collect::<Vec<_>>();
15309    if terminal.len() > 1 {
15310        return Err(invalid_recorded_history(
15311            "duplicate_condition_wait_terminal_event",
15312            sequence,
15313            "at most one condition terminal event",
15314            "multiple condition terminal events",
15315            "condition history settles one durable wait more than once",
15316        ));
15317    }
15318
15319    let opened = opened[0];
15320    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
15321    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
15322    for event in condition_events
15323        .iter()
15324        .copied()
15325        .filter(|event| !std::ptr::eq(*event, opened))
15326    {
15327        let event_wait_id = required_condition_wait_id(event, sequence)?;
15328        if event_wait_id != condition_wait_id {
15329            return Err(invalid_recorded_history(
15330                "condition_wait_id_mismatch",
15331                sequence,
15332                &condition_wait_id,
15333                &event_wait_id,
15334                "condition lifecycle events at one sequence disagree on wait identity",
15335            ));
15336        }
15337        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
15338        if event_occurrence_id != occurrence_id {
15339            return Err(invalid_recorded_history(
15340                "condition_wait_occurrence_history_mismatch",
15341                sequence,
15342                &occurrence_id,
15343                &event_occurrence_id,
15344                "condition lifecycle events at one sequence disagree on authored occurrence identity",
15345            ));
15346        }
15347    }
15348
15349    let condition_key = optional_non_empty_history_string(opened, "condition_key");
15350    let predicate_identity = opened
15351        .payload
15352        .get("condition_definition_fingerprint")
15353        .and_then(Value::as_str)
15354        .filter(|value| !value.is_empty())
15355        .map(str::to_string)
15356        .ok_or_else(|| {
15357            invalid_recorded_history(
15358                "condition_wait_predicate_fingerprint_missing",
15359                sequence,
15360                "non-empty condition_definition_fingerprint",
15361                &opened.event_type,
15362                "canonical condition history is missing its predicate identity",
15363            )
15364        })?;
15365    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
15366    for event in condition_events
15367        .iter()
15368        .copied()
15369        .filter(|event| !std::ptr::eq(*event, opened))
15370    {
15371        for (field, opened_value) in [
15372            ("condition_key", condition_key.as_deref()),
15373            (
15374                "condition_definition_fingerprint",
15375                Some(predicate_identity.as_str()),
15376            ),
15377        ] {
15378            if let Some(value) = optional_non_empty_history_string(event, field) {
15379                if opened_value.is_some_and(|opened_value| opened_value != value) {
15380                    return Err(invalid_recorded_history(
15381                        "condition_wait_definition_history_mismatch",
15382                        sequence,
15383                        opened_value.unwrap_or_default(),
15384                        &value,
15385                        "condition lifecycle events disagree on the recorded definition",
15386                    ));
15387                }
15388            }
15389        }
15390        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
15391            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
15392                return Err(invalid_recorded_history(
15393                    "condition_wait_definition_history_mismatch",
15394                    sequence,
15395                    &format!("{}s", timeout_seconds.unwrap_or_default()),
15396                    &format!("{event_timeout}s"),
15397                    "condition lifecycle events disagree on the recorded timeout",
15398                ));
15399            }
15400        }
15401    }
15402
15403    let timeout_timer_events = all_events
15404        .iter()
15405        .filter(|event| {
15406            matches!(
15407                event.event_type.as_str(),
15408                "TimerScheduled" | "TimerCancelled" | "TimerFired"
15409            ) && event.payload.get("timer_kind").and_then(Value::as_str)
15410                == Some("condition_timeout")
15411                && event
15412                    .payload
15413                    .get("condition_wait_id")
15414                    .and_then(Value::as_str)
15415                    == Some(condition_wait_id.as_str())
15416        })
15417        .collect::<Vec<_>>();
15418    let scheduled = timeout_timer_events
15419        .iter()
15420        .copied()
15421        .filter(|event| event.event_type == "TimerScheduled")
15422        .collect::<Vec<_>>();
15423    let fired = timeout_timer_events
15424        .iter()
15425        .copied()
15426        .filter(|event| event.event_type == "TimerFired")
15427        .collect::<Vec<_>>();
15428    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
15429        return Err(invalid_recorded_history(
15430            "condition_wait_timeout_history_invalid",
15431            sequence,
15432            "one timeout schedule and at most one fire",
15433            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
15434            "condition timeout history has a missing or duplicate lifecycle event",
15435        ));
15436    }
15437    if let Some(scheduled) = scheduled.first() {
15438        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
15439        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
15440        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
15441            return Err(invalid_recorded_history(
15442                "condition_wait_timeout_delay_mismatch",
15443                sequence,
15444                &format!("{}s", timeout_seconds.unwrap_or_default()),
15445                &format!("{delay_seconds}s"),
15446                "condition timeout timer differs from the wait definition",
15447            ));
15448        }
15449        if let Some(fired) = fired.first() {
15450            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
15451            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
15452            if fired_timer_id != timer_id || fired_delay != delay_seconds {
15453                return Err(invalid_recorded_history(
15454                    "condition_wait_timeout_identity_mismatch",
15455                    sequence,
15456                    &format!("{timer_id}:{delay_seconds}s"),
15457                    &format!("{fired_timer_id}:{fired_delay}s"),
15458                    "condition timeout fire does not match its durable schedule",
15459                ));
15460            }
15461        }
15462    }
15463
15464    let result = terminal.first().map(|event| {
15465        if event.event_type == "ConditionWaitTimedOut" {
15466            ConditionWaitResult::TimedOut
15467        } else {
15468            ConditionWaitResult::Satisfied
15469        }
15470    });
15471    let result = if !fired.is_empty() {
15472        if result == Some(ConditionWaitResult::Satisfied) {
15473            return Err(invalid_recorded_history(
15474                "condition_wait_terminal_conflict",
15475                sequence,
15476                "one satisfied or timed-out outcome",
15477                "satisfied event and fired timeout",
15478                "condition history records conflicting terminal outcomes",
15479            ));
15480        }
15481        Some(ConditionWaitResult::TimedOut)
15482    } else {
15483        result
15484    };
15485
15486    Ok(RecordedCommand::ConditionWait {
15487        sequence,
15488        occurrence_id,
15489        condition_key,
15490        predicate_identity,
15491        timeout_seconds,
15492        result,
15493        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
15494    })
15495}
15496
15497fn recorded_condition_group_path(
15498    condition_events: &[&HistoryEvent],
15499    all_events: &[HistoryEvent],
15500    sequence: u64,
15501) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15502    let opened = condition_events
15503        .iter()
15504        .copied()
15505        .find(|event| event.event_type == "ConditionWaitOpened")
15506        .expect("canonical condition opener is validated first");
15507    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
15508    let previous_events = all_events
15509        .iter()
15510        .take_while(|event| !std::ptr::eq(*event, opened))
15511        .collect::<Vec<_>>();
15512    let originals = previous_events
15513        .iter()
15514        .copied()
15515        .filter(|event| event.event_type == "ConditionWaitOpened")
15516        .filter(|event| {
15517            event
15518                .payload
15519                .get("condition_wait_occurrence_id")
15520                .and_then(Value::as_str)
15521                == Some(occurrence.as_str())
15522        })
15523        .collect::<Vec<_>>();
15524    let Some(original) = originals.first().copied() else {
15525        return recorded_parallel_group_path(condition_events, sequence);
15526    };
15527    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
15528    if authored_sequence == sequence {
15529        return recorded_parallel_group_path(condition_events, sequence);
15530    }
15531    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
15532    if original_path.is_none() {
15533        return recorded_parallel_group_path(condition_events, sequence);
15534    }
15535    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
15536    let identity_matches = [
15537        "condition_key",
15538        "condition_definition_fingerprint",
15539        "timeout_seconds",
15540    ]
15541    .iter()
15542    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
15543    let previous = originals
15544        .iter()
15545        .copied()
15546        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
15547        .max_by_key(|event| durable_event_sequence(event));
15548    let previously_satisfied = previous.is_some_and(|previous| {
15549        previous_events.iter().any(|event| {
15550            event.event_type == "ConditionWaitSatisfied"
15551                && event.payload.get("condition_wait_id")
15552                    == previous.payload.get("condition_wait_id")
15553                && event.payload.get("condition_wait_occurrence_id")
15554                    == previous.payload.get("condition_wait_occurrence_id")
15555                && durable_event_sequence(event) == durable_event_sequence(previous)
15556        })
15557    });
15558    if !identity_matches || reopened_path != original_path || !previously_satisfied {
15559        return Err(invalid_recorded_history(
15560            "condition_wait_group_reopen_mismatch",
15561            sequence,
15562            "same authored condition and group path after a satisfied physical wait",
15563            &opened.payload.to_string(),
15564            "grouped condition reopen has no matching recorded predecessor",
15565        ));
15566    }
15567    Ok(reopened_path)
15568}
15569
15570fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
15571    event
15572        .payload
15573        .get("condition_wait_occurrence_id")
15574        .and_then(Value::as_str)
15575        .filter(|value| !value.is_empty())
15576        .map(str::to_string)
15577        .ok_or_else(|| {
15578            invalid_recorded_history(
15579                "condition_wait_occurrence_id_missing",
15580                sequence,
15581                "non-empty condition_wait_occurrence_id",
15582                &event.event_type,
15583                "condition history is missing authored occurrence identity",
15584            )
15585        })
15586}
15587
15588fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
15589    event
15590        .payload
15591        .get("condition_wait_id")
15592        .and_then(Value::as_str)
15593        .filter(|value| !value.is_empty())
15594        .map(str::to_string)
15595        .ok_or_else(|| {
15596            invalid_recorded_history(
15597                "condition_wait_id_missing",
15598                sequence,
15599                "non-empty condition_wait_id",
15600                &event.event_type,
15601                "canonical condition history is missing its durable wait identity",
15602            )
15603        })
15604}
15605
15606fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
15607    event
15608        .payload
15609        .get(field)
15610        .and_then(Value::as_str)
15611        .filter(|value| !value.is_empty())
15612        .map(str::to_string)
15613}
15614
15615fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
15616    match event.payload.get(field) {
15617        None | Some(Value::Null) => Ok(None),
15618        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
15619            invalid_recorded_history(
15620                "condition_wait_definition_invalid",
15621                sequence,
15622                &format!("non-negative integer {field}"),
15623                &value.to_string(),
15624                "condition history contains an invalid numeric definition field",
15625            )
15626        }),
15627    }
15628}
15629
15630fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
15631    event
15632        .payload
15633        .get("signal_name")
15634        .or_else(|| event.raw.get("signal_name"))
15635        .and_then(Value::as_str)
15636        .filter(|value| !value.is_empty())
15637        .map(str::to_string)
15638        .ok_or_else(|| {
15639            invalid_recorded_history(
15640                "signal_wait_name_missing",
15641                sequence,
15642                "non-empty signal_name",
15643                &event.event_type,
15644                "canonical signal-wait history is missing its signal identity",
15645            )
15646        })
15647}
15648
15649fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
15650    matches!(
15651        event.event_type.as_str(),
15652        "SignalWaitOpened" | "SignalApplied"
15653    )
15654}
15655
15656fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
15657    event
15658        .payload
15659        .get(field)
15660        .and_then(Value::as_str)
15661        .filter(|value| !value.is_empty())
15662        .map(str::to_string)
15663        .ok_or_else(|| {
15664            invalid_recorded_history(
15665                "timer_history_field_missing",
15666                sequence,
15667                field,
15668                &event.event_type,
15669                "timer history is missing a required identity field",
15670            )
15671        })
15672}
15673
15674fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
15675    event
15676        .payload
15677        .get(field)
15678        .and_then(value_as_u64)
15679        .ok_or_else(|| {
15680            invalid_recorded_history(
15681                "timer_history_field_missing",
15682                sequence,
15683                field,
15684                &event.event_type,
15685                "timer history is missing a required numeric field",
15686            )
15687        })
15688}
15689
15690fn recorded_search_attribute_types(
15691    payload: &Value,
15692    attributes: &Value,
15693    sequence: u64,
15694) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
15695    let Some(raw_types) = payload.get("attribute_types") else {
15696        // This is the explicit compatibility rule for histories recorded
15697        // before typed identity was persisted. Values still constrain replay;
15698        // the unknown type snapshot does not assert a typed match.
15699        return Ok(RecordedSnapshotValue::Unknown);
15700    };
15701    let Some(raw_types) = raw_types.as_object() else {
15702        return Err(invalid_recorded_history(
15703            "search_attribute_types_malformed",
15704            sequence,
15705            "canonical attribute type map",
15706            &raw_types.to_string(),
15707            "search-attribute history contains malformed type identity",
15708        ));
15709    };
15710    let attribute_keys = attributes
15711        .as_object()
15712        .expect("recorded search attributes were validated as an object");
15713    let mut types = BTreeMap::new();
15714    for (key, value) in raw_types {
15715        let Some(attribute_type) = value.as_str() else {
15716            return Err(invalid_recorded_history(
15717                "search_attribute_types_malformed",
15718                sequence,
15719                "canonical string type name",
15720                &value.to_string(),
15721                "search-attribute history contains a non-string type identity",
15722            ));
15723        };
15724        if !attribute_keys.contains_key(key)
15725            || !matches!(
15726                attribute_type,
15727                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
15728            )
15729        {
15730            return Err(invalid_recorded_history(
15731                "search_attribute_types_malformed",
15732                sequence,
15733                "canonical types for keys present in attributes",
15734                &format!("{key}:{attribute_type}"),
15735                "search-attribute history contains unsupported or orphaned type identity",
15736            ));
15737        }
15738        types.insert(key.clone(), attribute_type.to_string());
15739    }
15740    Ok(RecordedSnapshotValue::Known(types))
15741}
15742
15743fn invalid_recorded_history(
15744    reason: &str,
15745    sequence: u64,
15746    expected: &str,
15747    actual: &str,
15748    message: &str,
15749) -> Error {
15750    Error::NonDeterministicReplay(ReplayFailure::new(
15751        reason,
15752        Some(sequence),
15753        Some(expected.to_string()),
15754        Some(actual.to_string()),
15755        message,
15756    ))
15757}
15758
15759type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
15760
15761fn activity_outcome(
15762    event: &HistoryEvent,
15763    fallback_codec: &str,
15764    recorded_activity_type: Option<String>,
15765) -> Result<ActivityOutcome> {
15766    if event.event_type == "ActivityCompleted" {
15767        let codec = event
15768            .payload
15769            .get("payload_codec")
15770            .and_then(Value::as_str)
15771            .unwrap_or(fallback_codec);
15772        return Ok(Ok(decode_wire_avro_value(
15773            event.payload.get("result").unwrap_or(&Value::Null),
15774            codec,
15775        )?));
15776    }
15777
15778    let payload = &event.payload;
15779    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
15780        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
15781        "ActivityCancelled" => (
15782            ActivityFailureKind::Cancelled,
15783            "cancelled",
15784            "activity was cancelled",
15785        ),
15786        "ActivityTimedOut" => (
15787            ActivityFailureKind::TimedOut,
15788            "timeout",
15789            "activity timed out",
15790        ),
15791        _ => unreachable!("activity_outcome is called only for terminal activity events"),
15792    };
15793    let exception = payload
15794        .get("exception")
15795        .filter(|value| !value.is_null())
15796        .cloned();
15797    let failure_category = payload_string(payload, "failure_category");
15798    let timeout_kind = payload_string(payload, "timeout_kind");
15799    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
15800        ActivityFailureKind::Failed => failure_category
15801            .clone()
15802            .unwrap_or_else(|| fallback_reason.to_string()),
15803        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
15804        ActivityFailureKind::TimedOut => timeout_kind
15805            .clone()
15806            .unwrap_or_else(|| fallback_reason.to_string()),
15807    });
15808    let message = payload_string(payload, "message")
15809        .or_else(|| {
15810            exception
15811                .as_ref()
15812                .and_then(|value| payload_string(value, "message"))
15813        })
15814        .unwrap_or_else(|| fallback_message.to_string());
15815
15816    Ok(Err(ActivityFailure {
15817        kind,
15818        reason,
15819        message,
15820        activity_execution_id: payload_string(payload, "activity_execution_id"),
15821        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
15822        activity_type: payload_string(payload, "activity_type")
15823            .or_else(|| payload_string(payload, "activity_name"))
15824            .or(recorded_activity_type),
15825        activity_class: payload_string(payload, "activity_class"),
15826        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
15827        failure_id: payload_string(payload, "failure_id"),
15828        failure_category,
15829        timeout_kind,
15830        non_retryable: payload
15831            .get("non_retryable")
15832            .and_then(Value::as_bool)
15833            .unwrap_or(false),
15834        exception_type: payload_string(payload, "exception_type").or_else(|| {
15835            exception
15836                .as_ref()
15837                .and_then(|value| payload_string(value, "type"))
15838        }),
15839        exception_class: payload_string(payload, "exception_class").or_else(|| {
15840            exception
15841                .as_ref()
15842                .and_then(|value| payload_string(value, "class"))
15843        }),
15844        code: payload
15845            .get("code")
15846            .filter(|value| !value.is_null())
15847            .cloned(),
15848        exception,
15849    }))
15850}
15851
15852type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
15853
15854fn child_workflow_outcomes(
15855    events: &[HistoryEvent],
15856    fallback_codec: &str,
15857    parent: WorkflowIdentity,
15858) -> Result<Vec<ChildWorkflowOutcome>> {
15859    let mut outcomes = Vec::new();
15860
15861    for event in events {
15862        let kind = match event.event_type.as_str() {
15863            "ChildRunCompleted" => None,
15864            "ChildRunFailed" => Some((
15865                ChildWorkflowFailureKind::Failed,
15866                "child_workflow",
15867                "child workflow failed",
15868            )),
15869            "ChildRunCancelled" => Some((
15870                ChildWorkflowFailureKind::Cancelled,
15871                "cancelled",
15872                "child workflow was cancelled",
15873            )),
15874            "ChildRunTerminated" => Some((
15875                ChildWorkflowFailureKind::Terminated,
15876                "terminated",
15877                "child workflow was terminated",
15878            )),
15879            _ => continue,
15880        };
15881        let payload = &event.payload;
15882        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
15883        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
15884        let child_workflow_type = payload_string(payload, "child_workflow_type");
15885
15886        if let Some((kind, reason, fallback_message)) = kind {
15887            let exception = payload
15888                .get("exception")
15889                .filter(|value| !value.is_null())
15890                .cloned();
15891            let message = payload_string(payload, "message")
15892                .or_else(|| {
15893                    exception
15894                        .as_ref()
15895                        .and_then(|value| payload_string(value, "message"))
15896                })
15897                .unwrap_or_else(|| fallback_message.to_string());
15898            let exception_type = payload_string(payload, "exception_type").or_else(|| {
15899                exception
15900                    .as_ref()
15901                    .and_then(|value| payload_string(value, "type"))
15902            });
15903            let exception_class = payload_string(payload, "exception_class").or_else(|| {
15904                exception
15905                    .as_ref()
15906                    .and_then(|value| payload_string(value, "class"))
15907            });
15908            outcomes.push(Err(ChildWorkflowFailure {
15909                kind,
15910                reason: reason.to_string(),
15911                message,
15912                parent_workflow_id: parent.workflow_id.clone(),
15913                parent_workflow_run_id: parent.run_id.clone(),
15914                child_workflow_id,
15915                child_workflow_run_id,
15916                child_workflow_type,
15917                failure_id: payload_string(payload, "failure_id"),
15918                failure_category: payload_string(payload, "failure_category"),
15919                exception_type,
15920                exception_class,
15921                non_retryable: payload
15922                    .get("non_retryable")
15923                    .and_then(Value::as_bool)
15924                    .unwrap_or(false),
15925                code: payload
15926                    .get("code")
15927                    .filter(|value| !value.is_null())
15928                    .cloned(),
15929                exception,
15930            }));
15931            continue;
15932        }
15933
15934        let codec = payload
15935            .get("payload_codec")
15936            .and_then(Value::as_str)
15937            .unwrap_or(fallback_codec);
15938        let result = payload
15939            .get("result")
15940            .or_else(|| payload.get("output"))
15941            .unwrap_or(&Value::Null);
15942        outcomes.push(Ok(ChildWorkflowAvroResult {
15943            parent: parent.clone(),
15944            child: WorkflowIdentity {
15945                workflow_id: child_workflow_id,
15946                run_id: child_workflow_run_id,
15947            },
15948            child_workflow_type,
15949            result: decode_wire_avro_value(result, codec)?,
15950        }));
15951    }
15952
15953    Ok(outcomes)
15954}
15955
15956fn payload_string(payload: &Value, key: &str) -> Option<String> {
15957    payload
15958        .get(key)
15959        .and_then(Value::as_str)
15960        .filter(|value| !value.is_empty())
15961        .map(str::to_string)
15962}
15963
15964fn recorded_activity_failure_boundary(
15965    ctx: &WorkflowContext,
15966    error: &Error,
15967) -> Option<(u64, String)> {
15968    let Error::ActivityFailed(failure) = error else {
15969        return None;
15970    };
15971    if failure.kind != ActivityFailureKind::Failed {
15972        return None;
15973    }
15974    let activity_execution_id = failure
15975        .activity_execution_id
15976        .as_deref()
15977        .filter(|value| !value.is_empty())?;
15978    let state = ctx.state.lock().ok()?;
15979    let mut matches = state.recorded_commands.iter().filter_map(|command| {
15980        let RecordedCommand::Activity {
15981            sequence,
15982            outcome: Some(Err(recorded_failure)),
15983            ..
15984        } = command
15985        else {
15986            return None;
15987        };
15988        (*sequence > 0 && recorded_failure == failure)
15989            .then_some((*sequence, activity_execution_id.to_string()))
15990    });
15991    let boundary = matches.next()?;
15992    matches.next().is_none().then_some(boundary)
15993}
15994
15995fn workflow_failure_command(
15996    error: &Error,
15997    failed_activity_boundary: Option<(u64, String)>,
15998) -> Value {
15999    let (exception_type, exception_class, properties) = match error {
16000        Error::ActivityFailed(failure) => (
16001            match failure.kind {
16002                ActivityFailureKind::Failed => "ActivityFailed",
16003                ActivityFailureKind::Cancelled => "ActivityCancelled",
16004                ActivityFailureKind::TimedOut => "ActivityTimedOut",
16005            },
16006            "durable_workflow::ActivityFailure",
16007            json!({
16008                "reason": failure.reason,
16009                "activity_execution_id": failure.activity_execution_id,
16010                "activity_attempt_id": failure.activity_attempt_id,
16011                "activity_type": failure.activity_type,
16012                "activity_class": failure.activity_class,
16013                "attempt_number": failure.attempt_number,
16014                "failure_id": failure.failure_id,
16015                "failure_category": failure.failure_category,
16016                "timeout_kind": failure.timeout_kind,
16017                "activity_non_retryable": failure.non_retryable,
16018                "activity_exception_type": failure.exception_type,
16019                "activity_exception_class": failure.exception_class,
16020                "activity_code": failure.code,
16021                "activity_exception": failure.exception,
16022            }),
16023        ),
16024        Error::ChildWorkflowFailed(failure) => (
16025            match failure.kind {
16026                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16027                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16028                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16029            },
16030            "durable_workflow::ChildWorkflowFailure",
16031            json!({
16032                "reason": failure.reason,
16033                "parent_workflow_id": failure.parent_workflow_id,
16034                "parent_workflow_run_id": failure.parent_workflow_run_id,
16035                "child_workflow_id": failure.child_workflow_id,
16036                "child_workflow_run_id": failure.child_workflow_run_id,
16037                "child_workflow_type": failure.child_workflow_type,
16038                "failure_id": failure.failure_id,
16039                "failure_category": failure.failure_category,
16040                "child_exception_type": failure.exception_type,
16041                "child_exception_class": failure.exception_class,
16042                "child_non_retryable": failure.non_retryable,
16043                "child_code": failure.code,
16044                "child_exception": failure.exception,
16045            }),
16046        ),
16047        Error::ParallelFailed(failure) => (
16048            "ParallelFailed",
16049            "durable_workflow::ParallelFailure",
16050            json!({
16051                "parallel_group_id": failure.group_id,
16052                "parallel_member_path": failure.member_path,
16053                "parallel_group_path": failure.group_path,
16054                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
16055                "cause_type": workflow_error_type(&failure.cause),
16056                "cause_message": failure.cause.to_string(),
16057            }),
16058        ),
16059        Error::SagaCompensationFailed(failure) => (
16060            "SagaCompensationFailed",
16061            "durable_workflow::SagaCompensationFailure",
16062            json!({
16063                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
16064                "initiating_failure_message": failure.initiating_failure.to_string(),
16065                "compensation_activity_type": failure.compensation_activity_type,
16066                "compensation_registration_order": failure.compensation_registration_order,
16067                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
16068                "compensation_failure_message": failure.compensation_failure.to_string(),
16069            }),
16070        ),
16071        Error::WorkflowCancellationRequested(_) => (
16072            "WorkflowCancellationRequested",
16073            "durable_workflow::WorkflowCancellationRequested",
16074            json!({"reason": "cancelled"}),
16075        ),
16076        Error::CooperativeCancellationRequested(cancellation) => (
16077            "WorkflowCancellationRequested",
16078            "durable_workflow::CooperativeCancellationRequested",
16079            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
16080                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
16081        ),
16082        Error::CancellationScopeRequested(cancellation) => (
16083            "WorkflowCancellationRequested",
16084            "durable_workflow::CancellationScopeRequested",
16085            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
16086                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
16087                "cancellation":cancellation.context.to_value()}),
16088        ),
16089        Error::NonDeterministicReplay(_) => (
16090            "NonDeterministicReplay",
16091            "durable_workflow::Error",
16092            Value::Null,
16093        ),
16094        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
16095    };
16096    let non_retryable = match error {
16097        Error::ActivityFailed(failure) => failure.non_retryable,
16098        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16099        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16100        Error::SagaCompensationFailed(failure) => {
16101            workflow_error_non_retryable(&failure.compensation_failure)
16102        }
16103        Error::WorkflowCancellationRequested(_)
16104        | Error::CooperativeCancellationRequested(_)
16105        | Error::CancellationScopeRequested(_) => true,
16106        Error::NonDeterministicReplay(_) => true,
16107        _ => false,
16108    };
16109
16110    let mut command = json!({
16111        "type": "fail_workflow",
16112        "message": error.to_string(),
16113        "exception_type": exception_type,
16114        "exception_class": exception_class,
16115        "non_retryable": non_retryable,
16116        "exception": {
16117            "type": exception_type,
16118            "class": exception_class,
16119            "message": error.to_string(),
16120            "properties": properties,
16121        }
16122    });
16123
16124    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
16125        command["failed_step_sequence"] = json!(sequence);
16126        command["failed_activity_execution_id"] = json!(activity_execution_id);
16127    }
16128
16129    command
16130}
16131
16132fn workflow_error_type(error: &Error) -> &'static str {
16133    match error {
16134        Error::ActivityFailed(failure) => match failure.kind {
16135            ActivityFailureKind::Failed => "ActivityFailed",
16136            ActivityFailureKind::Cancelled => "ActivityCancelled",
16137            ActivityFailureKind::TimedOut => "ActivityTimedOut",
16138        },
16139        Error::ChildWorkflowFailed(failure) => match failure.kind {
16140            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16141            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16142            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16143        },
16144        Error::ParallelFailed(_) => "ParallelFailed",
16145        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
16146        Error::WorkflowCancellationRequested(_)
16147        | Error::CooperativeCancellationRequested(_)
16148        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
16149        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
16150        _ => "RustWorkflowError",
16151    }
16152}
16153
16154fn workflow_error_non_retryable(error: &Error) -> bool {
16155    match error {
16156        Error::ActivityFailed(failure) => failure.non_retryable,
16157        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16158        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16159        Error::SagaCompensationFailed(failure) => {
16160            workflow_error_non_retryable(&failure.compensation_failure)
16161        }
16162        Error::WorkflowCancellationRequested(_)
16163        | Error::CooperativeCancellationRequested(_)
16164        | Error::CancellationScopeRequested(_)
16165        | Error::NonDeterministicReplay(_) => true,
16166        _ => false,
16167    }
16168}
16169
16170fn workflow_task_integrity_error(error: &Error) -> bool {
16171    matches!(
16172        error,
16173        Error::NonDeterministicReplay(_)
16174            | Error::Protocol(_)
16175            | Error::CancellationScopeExecutionUnavailable
16176            | Error::MissingWorkflowCommandIdentity
16177            | Error::WorkflowStatePoisoned
16178    )
16179}
16180
16181fn decode_signal_event_arguments(
16182    event: &HistoryEvent,
16183    fallback_codec: &str,
16184) -> Result<Vec<AvroValue>> {
16185    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16186    validate_payload_codec(codec)?;
16187    let raw = signal_history_payload(&event.payload);
16188    let decoded = match raw.filter(|value| !value.is_null()) {
16189        Some(value) => decode_wire_avro_value(value, codec)?,
16190        None => AvroValue::Array(Vec::new()),
16191    };
16192    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16193        unreachable!("normalize_avro_arguments always returns an array");
16194    };
16195    Ok(arguments)
16196}
16197
16198fn decode_update_event_arguments(
16199    event: &HistoryEvent,
16200    fallback_codec: &str,
16201) -> Result<Vec<AvroValue>> {
16202    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16203    validate_payload_codec(codec)?;
16204    let decoded = match event
16205        .payload
16206        .get("arguments")
16207        .filter(|value| !value.is_null())
16208    {
16209        Some(value) => decode_wire_avro_value(value, codec)?,
16210        None => AvroValue::Array(Vec::new()),
16211    };
16212    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16213        unreachable!("normalize_avro_arguments always returns an array");
16214    };
16215    Ok(arguments)
16216}
16217
16218fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16219    let Some(export_events) = task
16220        .history_export
16221        .as_ref()
16222        .and_then(|export| export.get("history_events"))
16223        .and_then(Value::as_array)
16224    else {
16225        return Ok(());
16226    };
16227
16228    if export_events.len() > task.history_events.len() {
16229        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
16230    }
16231
16232    Ok(())
16233}
16234
16235fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16236    let Some(export) = task.history_export.as_ref() else {
16237        return Ok(());
16238    };
16239    let signals = export
16240        .get("signals")
16241        .and_then(Value::as_array)
16242        .cloned()
16243        .unwrap_or_default();
16244    let activities = export
16245        .get("activities")
16246        .and_then(Value::as_array)
16247        .cloned()
16248        .unwrap_or_default();
16249    let export_codec = export
16250        .get("payloads")
16251        .and_then(|payloads| payloads.get("codec"))
16252        .and_then(Value::as_str)
16253        .unwrap_or(&task.payload_codec)
16254        .to_string();
16255    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
16256
16257    for event in &mut task.history_events {
16258        if event.event_type == "ActivityCompleted" {
16259            let sequence = event
16260                .payload
16261                .get("sequence")
16262                .or_else(|| event.payload.get("workflow_sequence"))
16263                .and_then(value_as_u64);
16264            let Some(activity) = sequence.and_then(|sequence| {
16265                activities.iter().find(|activity| {
16266                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
16267                })
16268            }) else {
16269                continue;
16270            };
16271            let Some(payload) = event.payload.as_object_mut() else {
16272                continue;
16273            };
16274            if missing_payload(payload.get("result")) {
16275                if let Some(result) = activity
16276                    .get("result")
16277                    .filter(|value| !missing_payload(Some(value)))
16278                {
16279                    payload.insert("result".to_string(), result.clone());
16280                }
16281            }
16282            for field in ["payload_codec", "activity_type"] {
16283                if payload
16284                    .get(field)
16285                    .and_then(Value::as_str)
16286                    .unwrap_or_default()
16287                    .is_empty()
16288                {
16289                    if let Some(value) = activity.get(field) {
16290                        payload.insert(field.to_string(), value.clone());
16291                    }
16292                }
16293            }
16294            continue;
16295        }
16296
16297        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
16298            continue;
16299        }
16300        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
16301        let command_id = event
16302            .payload
16303            .get("workflow_command_id")
16304            .or_else(|| event.raw.get("workflow_command_id"))
16305            .and_then(Value::as_str);
16306        let signal_name = event
16307            .payload
16308            .get("signal_name")
16309            .and_then(Value::as_str)
16310            .unwrap_or_default()
16311            .to_string();
16312        let matched = signals
16313            .iter()
16314            .find(|signal| {
16315                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
16316            })
16317            .or_else(|| {
16318                signals.iter().find(|signal| {
16319                    command_id.is_some()
16320                        && signal.get("command_id").and_then(Value::as_str) == command_id
16321                })
16322            })
16323            .or_else(|| {
16324                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
16325                let signal = signals
16326                    .iter()
16327                    .filter(|signal| {
16328                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
16329                    })
16330                    .nth(*offset);
16331                if signal.is_some() {
16332                    *offset += 1;
16333                }
16334                signal
16335            });
16336        let Some(signal) = matched else {
16337            continue;
16338        };
16339        let signal_codec = signal
16340            .get("payload_codec")
16341            .and_then(Value::as_str)
16342            .unwrap_or(&export_codec);
16343        let Some(payload) = event.payload.as_object_mut() else {
16344            continue;
16345        };
16346        if missing_payload(payload.get("arguments")) {
16347            if let Some(arguments) = signal
16348                .get("arguments")
16349                .filter(|value| !missing_payload(Some(value)))
16350            {
16351                let envelope = match arguments {
16352                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
16353                    other => other.clone(),
16354                };
16355                payload.insert("arguments".to_string(), envelope);
16356            }
16357        }
16358        if payload
16359            .get("payload_codec")
16360            .and_then(Value::as_str)
16361            .unwrap_or_default()
16362            .is_empty()
16363        {
16364            payload.insert("payload_codec".to_string(), json!(signal_codec));
16365        }
16366    }
16367
16368    Ok(())
16369}
16370
16371fn missing_payload(value: Option<&Value>) -> bool {
16372    match value {
16373        None | Some(Value::Null) => true,
16374        Some(Value::String(value)) => value.is_empty(),
16375        Some(_) => false,
16376    }
16377}
16378
16379fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
16380    let export_signals = task
16381        .history_export
16382        .as_ref()
16383        .and_then(|export| export.get("signals"))
16384        .and_then(Value::as_array)
16385        .cloned()
16386        .unwrap_or_default();
16387    let export_codec = task
16388        .history_export
16389        .as_ref()
16390        .and_then(|export| export.get("payloads"))
16391        .and_then(|payloads| payloads.get("codec"))
16392        .and_then(Value::as_str)
16393        .unwrap_or(&task.payload_codec);
16394    let mut name_offsets: HashMap<String, usize> = HashMap::new();
16395    let mut signals = Vec::new();
16396
16397    for event in &task.history_events {
16398        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
16399            continue;
16400        }
16401
16402        let name = event
16403            .payload
16404            .get("signal_name")
16405            .and_then(Value::as_str)
16406            .unwrap_or_default();
16407        if name.is_empty() {
16408            continue;
16409        }
16410        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
16411        let command_id = event
16412            .payload
16413            .get("workflow_command_id")
16414            .or_else(|| event.raw.get("workflow_command_id"))
16415            .and_then(Value::as_str);
16416        let matched_export = export_signals
16417            .iter()
16418            .find(|candidate| {
16419                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
16420            })
16421            .or_else(|| {
16422                export_signals.iter().find(|candidate| {
16423                    command_id.is_some()
16424                        && candidate.get("command_id").and_then(Value::as_str) == command_id
16425                })
16426            })
16427            .or_else(|| {
16428                let offset = name_offsets.entry(name.to_string()).or_default();
16429                let candidate = export_signals
16430                    .iter()
16431                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
16432                    .nth(*offset);
16433                if candidate.is_some() {
16434                    *offset += 1;
16435                }
16436                candidate
16437            });
16438        let codec = event
16439            .payload
16440            .get("payload_codec")
16441            .and_then(Value::as_str)
16442            .or_else(|| {
16443                matched_export
16444                    .and_then(|signal| signal.get("payload_codec"))
16445                    .and_then(Value::as_str)
16446            })
16447            .unwrap_or(export_codec);
16448        let raw_arguments = signal_history_payload(&event.payload)
16449            .filter(|value| !value.is_null())
16450            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
16451        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
16452        let workflow_sequence = event
16453            .payload
16454            .get("workflow_sequence")
16455            .and_then(value_as_u64)
16456            .or_else(|| {
16457                matched_export
16458                    .and_then(|signal| signal.get("workflow_sequence"))
16459                    .and_then(value_as_u64)
16460            });
16461
16462        signals.push(QuerySignal {
16463            id: signal_id.map(str::to_string).or_else(|| {
16464                matched_export
16465                    .and_then(|signal| signal.get("id"))
16466                    .and_then(Value::as_str)
16467                    .map(str::to_string)
16468            }),
16469            name: name.to_string(),
16470            arguments,
16471            avro_arguments,
16472            workflow_sequence,
16473        });
16474    }
16475
16476    if signals.is_empty() {
16477        for signal in export_signals {
16478            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
16479                continue;
16480            }
16481            let Some(name) = signal.get("name").and_then(Value::as_str) else {
16482                continue;
16483            };
16484            let codec = signal
16485                .get("payload_codec")
16486                .and_then(Value::as_str)
16487                .unwrap_or(export_codec);
16488            let (arguments, avro_arguments) =
16489                decode_query_signal_arguments(signal.get("arguments"), codec)?;
16490            signals.push(QuerySignal {
16491                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
16492                name: name.to_string(),
16493                arguments,
16494                avro_arguments,
16495                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
16496            });
16497        }
16498        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
16499    }
16500
16501    Ok(signals)
16502}
16503
16504fn decode_query_signal_arguments(
16505    raw: Option<&Value>,
16506    codec: &str,
16507) -> Result<(Vec<Value>, Vec<AvroValue>)> {
16508    validate_payload_codec(codec)?;
16509    let decoded = match raw.filter(|value| !value.is_null()) {
16510        Some(value) => decode_wire_avro_value(value, codec)?,
16511        None => AvroValue::Array(Vec::new()),
16512    };
16513    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
16514        unreachable!("normalize_avro_arguments always returns an array");
16515    };
16516    let arguments = avro_arguments
16517        .iter()
16518        .cloned()
16519        .map(AvroValue::into_json)
16520        .collect::<Result<Vec<_>>>()?;
16521    Ok((arguments, avro_arguments))
16522}
16523
16524fn value_as_u64(value: &Value) -> Option<u64> {
16525    value
16526        .as_u64()
16527        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
16528}
16529
16530#[cfg(test)]
16531mod tests {
16532    use super::*;
16533    mod activity_cancellation_policies;
16534    mod cancellation_scope_admission;
16535    mod cancellation_scope_authoring;
16536    mod cancellation_scope_history;
16537    mod cancellation_scope_opening;
16538    mod cancellation_scope_replay;
16539    mod child_workflow_policies;
16540    mod cooperative_cancellation;
16541    mod runtime_payloads;
16542    mod runtime_uploads;
16543    use std::{
16544        fs,
16545        io::{Read, Write},
16546        net::{SocketAddr, TcpListener, TcpStream},
16547        process::Command as ProcessCommand,
16548        sync::atomic::AtomicUsize,
16549        thread,
16550    };
16551
16552    #[derive(Clone, Copy, Debug)]
16553    enum InvalidTaskPayloadCodec {
16554        Missing,
16555        Null,
16556        NonString,
16557    }
16558
16559    impl InvalidTaskPayloadCodec {
16560        fn label(self) -> &'static str {
16561            match self {
16562                Self::Missing => "missing",
16563                Self::Null => "null",
16564                Self::NonString => "non-string",
16565            }
16566        }
16567
16568        fn apply(self, task: &mut Value) {
16569            let task = task.as_object_mut().expect("task fixture object");
16570            match self {
16571                Self::Missing => {
16572                    task.remove("payload_codec");
16573                }
16574                Self::Null => {
16575                    task.insert("payload_codec".to_string(), Value::Null);
16576                }
16577                Self::NonString => {
16578                    task.insert("payload_codec".to_string(), json!(42));
16579                }
16580            }
16581        }
16582    }
16583
16584    fn fixture_envelope(value: Value) -> Value {
16585        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
16586    }
16587
16588    fn fixture_blob(value: Value) -> String {
16589        encode_payload(&value, DEFAULT_CODEC)
16590            .expect("encode Avro test fixture")
16591            .blob
16592    }
16593
16594    #[test]
16595    fn client_builder_rejects_the_sdk_owned_api_suffix() {
16596        for base_url in [
16597            "http://127.0.0.1:8080/api",
16598            "http://localhost:8080/api/",
16599            "https://runtime.example.test/namespaces/orders/api",
16600        ] {
16601            let error = Client::builder(base_url)
16602                .build()
16603                .expect_err("SDK-owned /api suffix must be rejected during build");
16604
16605            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
16606            assert!(
16607                error.to_string().contains("SDK appends /api automatically"),
16608                "the validation error must explain how to fix the endpoint"
16609            );
16610        }
16611    }
16612
16613    #[test]
16614    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
16615        for (base_url, expected) in [
16616            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
16617            (
16618                "http://localhost:8080/durable-workflow/",
16619                "http://localhost:8080/durable-workflow",
16620            ),
16621            (
16622                "https://runtime.example.test/namespaces/orders",
16623                "https://runtime.example.test/namespaces/orders",
16624            ),
16625            (
16626                "https://runtime.example.test/gateway/api/namespaces/orders",
16627                "https://runtime.example.test/gateway/api/namespaces/orders",
16628            ),
16629            (
16630                "https://api.example.test/runtime/orders/",
16631                "https://api.example.test/runtime/orders",
16632            ),
16633        ] {
16634            let client = Client::builder(base_url)
16635                .build()
16636                .expect("Server and Cloud runtime base URL must remain valid");
16637
16638            assert_eq!(client.base_url, expected);
16639        }
16640    }
16641
16642    #[test]
16643    fn workflow_completion_uses_the_additive_command_protocol_floor() {
16644        assert_eq!(
16645            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
16646            WORKER_PROTOCOL_VERSION
16647        );
16648        assert_eq!(
16649            workflow_completion_protocol_version(&[json!({
16650                "type": "upsert_search_attributes",
16651                "attributes": {"OrderStatus": "waiting"},
16652            })]),
16653            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
16654        );
16655        assert_eq!(
16656            workflow_completion_protocol_version(&[json!({
16657                "type": "upsert_search_attributes",
16658                "attributes": {"OrderStatus": "waiting"},
16659                "attribute_types": {"OrderStatus": "keyword"},
16660            })]),
16661            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
16662        );
16663        assert_eq!(
16664            workflow_completion_protocol_version(&[
16665                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
16666                json!({"type": "open_condition_wait", "condition_key": "ready"}),
16667            ]),
16668            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
16669        );
16670        assert_eq!(
16671            workflow_completion_protocol_version(&[
16672                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
16673                json!({"type": "open_condition_wait", "condition_key": "ready"}),
16674            ]),
16675            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
16676        );
16677        assert_eq!(
16678            workflow_completion_protocol_version(&[json!({
16679                "type": "open_condition_wait",
16680                "condition_wait_occurrence_id": "rust:condition-wait:0",
16681                "condition_key": "ready",
16682            })]),
16683            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
16684        );
16685        assert_eq!(
16686            workflow_completion_protocol_version_with_message_streams(
16687                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
16688                true,
16689            ),
16690            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
16691        );
16692        assert_eq!(
16693            workflow_completion_protocol_version_with_message_streams(
16694                &[json!({
16695                    "type": "open_condition_wait",
16696                    "condition_wait_occurrence_id": "rust:condition-wait:0",
16697                    "condition_key": "ready",
16698                })],
16699                true,
16700            ),
16701            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
16702        );
16703    }
16704
16705    #[test]
16706    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
16707        let manifest = portable_worker_affinity_capability_manifest();
16708
16709        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
16710            assert_eq!(manifest[capability]["supported"], json!(false));
16711            assert_eq!(
16712                manifest[capability]["minimum_protocol_version"],
16713                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
16714            );
16715            assert!(manifest[capability]["reason"]
16716                .as_str()
16717                .is_some_and(|reason| !reason.is_empty()));
16718        }
16719    }
16720
16721    fn typed_fidelity_probe() -> AvroValue {
16722        AvroValue::Map(BTreeMap::from([
16723            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
16724            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
16725            (
16726                "numeric".to_string(),
16727                AvroValue::Map(BTreeMap::from([
16728                    ("0".to_string(), AvroValue::String("zero".to_string())),
16729                    ("1".to_string(), AvroValue::String("one".to_string())),
16730                ])),
16731            ),
16732            (
16733                "nested".to_string(),
16734                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
16735                    "enabled".to_string(),
16736                    AvroValue::Boolean(true),
16737                )]))]),
16738            ),
16739            (
16740                "projection_collisions".to_string(),
16741                AvroValue::Array(projection_collision_probe()),
16742            ),
16743        ]))
16744    }
16745
16746    fn projection_collision_probe() -> Vec<AvroValue> {
16747        vec![
16748            AvroValue::Map(BTreeMap::from([
16749                ("$type".to_string(), AvroValue::String("bytes".to_string())),
16750                (
16751                    "base64".to_string(),
16752                    AvroValue::String("ordinary user text".to_string()),
16753                ),
16754            ])),
16755            AvroValue::Map(BTreeMap::from([
16756                ("$type".to_string(), AvroValue::String("map".to_string())),
16757                (
16758                    "entries".to_string(),
16759                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
16760                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
16761                        (
16762                            "value".to_string(),
16763                            AvroValue::String("user map".to_string()),
16764                        ),
16765                    ]))]),
16766                ),
16767            ])),
16768        ]
16769    }
16770
16771    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
16772    struct TypedContract {
16773        nested: TypedNested,
16774        mode: TypedMode,
16775        optional: Option<String>,
16776        absent: Option<String>,
16777        items: Vec<i64>,
16778        labels: BTreeMap<String, String>,
16779        bytes: serde_bytes::ByteBuf,
16780        signed: i64,
16781        finite: f64,
16782    }
16783
16784    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
16785    struct TypedNested {
16786        enabled: bool,
16787    }
16788
16789    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
16790    enum TypedMode {
16791        Detailed { label: String },
16792    }
16793
16794    fn typed_contract() -> TypedContract {
16795        TypedContract {
16796            nested: TypedNested { enabled: true },
16797            mode: TypedMode::Detailed {
16798                label: "compiler-checked".to_string(),
16799            },
16800            optional: Some("present".to_string()),
16801            absent: None,
16802            items: vec![i64::MIN, 0, i64::MAX],
16803            labels: BTreeMap::from([
16804                ("language".to_string(), "rust".to_string()),
16805                ("wire".to_string(), "avro".to_string()),
16806            ]),
16807            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
16808            signed: -9_223_372_036_854_775_000,
16809            finite: 12.5,
16810        }
16811    }
16812
16813    #[derive(Clone, Debug, Default, PartialEq)]
16814    struct ReplayCounterState {
16815        loaded: Option<String>,
16816        count: i64,
16817        finished: bool,
16818    }
16819
16820    fn replay_counter_worker() -> Worker {
16821        let client = Client::new("http://127.0.0.1:8080").expect("client");
16822        let mut worker = Worker::new(client, "rust-workers");
16823        worker.register_replayed_workflow(
16824            "replay-counter",
16825            ReplayCounterState::default,
16826            |ctx, _input, state| async move {
16827                let loaded = ctx.activity("load-counter", json!([])).await?;
16828                state.update(|current| {
16829                    current.loaded = loaded.as_str().map(str::to_string);
16830                })?;
16831                for _ in 0..2 {
16832                    let signal = ctx.wait_signal("increment").await?;
16833                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
16834                    state.update(|current| current.count += amount)?;
16835                }
16836                state.update(|current| current.finished = true)?;
16837                state.read(|current| Ok(json!(current.count)))?
16838            },
16839        );
16840        worker.register_replayed_query::<ReplayCounterState, _, _>(
16841            "replay-counter",
16842            "current",
16843            |_ctx, state, _args| async move {
16844                Ok(json!({
16845                    "loaded": state.loaded,
16846                    "count": state.count,
16847                    "finished": state.finished,
16848                }))
16849            },
16850        );
16851        worker.register_replayed_query::<ReplayCounterState, _, _>(
16852            "replay-counter",
16853            "detached-mutation",
16854            |_ctx, state, _args| async move {
16855                let mut detached = (*state).clone();
16856                detached.count = 999;
16857                Ok(json!(detached.count))
16858            },
16859        );
16860        worker.register_replayed_query::<ReplayCounterState, _, _>(
16861            "replay-counter",
16862            "failed-mutation",
16863            |_ctx, state, _args| async move {
16864                let mut detached = (*state).clone();
16865                detached.count = 999;
16866                Err(Error::WorkerLoop("query refused".to_string()))
16867            },
16868        );
16869        worker
16870    }
16871
16872    fn replay_counter_query(
16873        query_name: &str,
16874        history_events: Value,
16875        run_status: &str,
16876    ) -> QueryTask {
16877        let arguments = fixture_envelope(json!([]));
16878        serde_json::from_value(json!({
16879            "query_task_id": format!("query-{query_name}"),
16880            "workflow_type": "replay-counter",
16881            "query_name": query_name,
16882            "payload_codec": DEFAULT_CODEC,
16883            "workflow_arguments": arguments.clone(),
16884            "query_arguments": arguments,
16885            "history_events": history_events,
16886            "run_status": run_status,
16887        }))
16888        .expect("query task")
16889    }
16890
16891    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
16892        workflow_context_with_codec(history, DEFAULT_CODEC)
16893    }
16894
16895    fn workflow_context_with_codec(
16896        history: Vec<HistoryEvent>,
16897        payload_codec: &str,
16898    ) -> WorkflowContext {
16899        WorkflowContext {
16900            cancellation_scope_id: "root".into(),
16901            state: Arc::new(Mutex::new(
16902                WorkflowState::new_with_identity(
16903                    history,
16904                    None,
16905                    None,
16906                    "rust-workers".to_string(),
16907                    payload_codec.to_string(),
16908                    None,
16909                )
16910                .expect("valid workflow history"),
16911            )),
16912        }
16913    }
16914
16915    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
16916        HistoryEvent {
16917            event_type: event_type.to_string(),
16918            payload,
16919            raw: HashMap::new(),
16920        }
16921    }
16922
16923    fn parallel_path_entry(
16924        kind: &str,
16925        base: u64,
16926        size: usize,
16927        index: usize,
16928    ) -> ParallelGroupMetadata {
16929        parallel_group_entry(base, size, index, kind)
16930    }
16931
16932    fn parallel_history_event(
16933        event_type: &str,
16934        sequence: u64,
16935        identity_field: &str,
16936        identity: &str,
16937        path: Vec<ParallelGroupMetadata>,
16938        result: Option<Value>,
16939    ) -> HistoryEvent {
16940        let mut payload = serde_json::Map::from_iter([
16941            ("sequence".to_string(), json!(sequence)),
16942            (identity_field.to_string(), json!(identity)),
16943        ]);
16944        let inner = path.last().expect("parallel history path");
16945        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
16946        payload.insert("parallel_group_path".to_string(), json!(path));
16947        if let Some(result) = result {
16948            let field = if event_type == "ChildRunCompleted" {
16949                "result"
16950            } else {
16951                "result"
16952            };
16953            payload.insert(field.to_string(), fixture_envelope(result));
16954            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
16955        }
16956        history_event(event_type, Value::Object(payload))
16957    }
16958
16959    fn nested_parallel_operations() -> Vec<ParallelOperation> {
16960        vec![
16961            ParallelOperation::activity("first", json!([])),
16962            ParallelOperation::group(vec![
16963                ParallelOperation::child_workflow(
16964                    "second",
16965                    ChildWorkflowOptions::new("child-workers"),
16966                    json!([]),
16967                ),
16968                ParallelOperation::activity("third", json!([])),
16969            ]),
16970        ]
16971    }
16972
16973    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
16974        let outer = [
16975            parallel_path_entry("mixed", 1, 3, 0),
16976            parallel_path_entry("mixed", 1, 3, 1),
16977            parallel_path_entry("mixed", 1, 3, 2),
16978        ];
16979        [
16980            vec![outer[0].clone()],
16981            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
16982            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
16983        ]
16984    }
16985
16986    #[test]
16987    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
16988        let ctx = workflow_context(Vec::new());
16989        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
16990        let mut task_context = TaskContext::from_waker(noop_waker_ref());
16991
16992        assert!(matches!(
16993            call.as_mut().poll(&mut task_context),
16994            Poll::Pending
16995        ));
16996        let commands = ctx.take_commands().expect("parallel commands");
16997        assert_eq!(
16998            commands
16999                .iter()
17000                .map(|command| command["type"].as_str().unwrap_or_default())
17001                .collect::<Vec<_>>(),
17002            [
17003                "schedule_activity",
17004                "start_child_workflow",
17005                "schedule_activity"
17006            ]
17007        );
17008        let paths = nested_parallel_paths();
17009        for (command, path) in commands.iter().zip(paths) {
17010            assert_eq!(command["parallel_group_path"], json!(path));
17011            assert_eq!(
17012                command["parallel_group_id"],
17013                json!(path.last().expect("inner group").parallel_group_id)
17014            );
17015        }
17016    }
17017
17018    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
17019        let paths = nested_parallel_paths();
17020        let third = parallel_history_event(
17021            "ActivityCompleted",
17022            3,
17023            "activity_type",
17024            "third",
17025            paths[2].clone(),
17026            Some(json!("three")),
17027        );
17028        vec![
17029            parallel_history_event(
17030                "ActivityCompleted",
17031                1,
17032                "activity_type",
17033                "first",
17034                paths[0].clone(),
17035                Some(json!("one")),
17036            ),
17037            parallel_history_event(
17038                "ChildWorkflowScheduled",
17039                2,
17040                "child_workflow_type",
17041                "second",
17042                paths[1].clone(),
17043                None,
17044            ),
17045            parallel_history_event(
17046                "ChildRunCompleted",
17047                2,
17048                "child_workflow_type",
17049                "second",
17050                paths[1].clone(),
17051                Some(json!("two")),
17052            ),
17053            third.clone(),
17054            third,
17055        ]
17056    }
17057
17058    #[test]
17059    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
17060        for _restart_or_completed_replay in 0..2 {
17061            let ctx = workflow_context(completed_nested_parallel_history());
17062            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17063            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17064            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
17065                panic!("completed nested parallel history must replay");
17066            };
17067            assert_eq!(
17068                results,
17069                vec![
17070                    ParallelResult::Activity(json!("one")),
17071                    ParallelResult::Group(vec![
17072                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
17073                            parent: WorkflowIdentity {
17074                                workflow_id: None,
17075                                run_id: None,
17076                            },
17077                            child: WorkflowIdentity {
17078                                workflow_id: None,
17079                                run_id: None,
17080                            },
17081                            child_workflow_type: Some("second".to_string()),
17082                            result: json!("two"),
17083                        }),
17084                        ParallelResult::Activity(json!("three")),
17085                    ]),
17086                ]
17087            );
17088            assert!(ctx.take_commands().expect("commands").is_empty());
17089            ctx.ensure_history_consumed().expect("history consumed");
17090        }
17091    }
17092
17093    #[test]
17094    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
17095        let paths = nested_parallel_paths();
17096        let history = vec![
17097            parallel_history_event(
17098                "ActivityCompleted",
17099                1,
17100                "activity_type",
17101                "first",
17102                paths[0].clone(),
17103                Some(json!("one")),
17104            ),
17105            parallel_history_event(
17106                "ChildWorkflowScheduled",
17107                2,
17108                "child_workflow_type",
17109                "second",
17110                paths[1].clone(),
17111                None,
17112            ),
17113            parallel_history_event(
17114                "ChildRunFailed",
17115                2,
17116                "child_workflow_type",
17117                "second",
17118                paths[1].clone(),
17119                None,
17120            ),
17121            parallel_history_event(
17122                "ActivityCompleted",
17123                3,
17124                "activity_type",
17125                "third",
17126                paths[2].clone(),
17127                Some(json!("late")),
17128            ),
17129        ];
17130        let ctx = workflow_context(history);
17131        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17132        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17133        let outcome = call.as_mut().poll(&mut task_context);
17134        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
17135            panic!("one failed child must return a typed partial failure: {outcome:?}");
17136        };
17137        assert_eq!(failure.member_path, [1, 0]);
17138        assert_eq!(failure.group_id, "parallel-calls:1:3");
17139        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
17140        assert_eq!(
17141            failure
17142                .completed
17143                .iter()
17144                .map(|completion| completion.member_path.clone())
17145                .collect::<Vec<_>>(),
17146            [vec![0], vec![1, 1]]
17147        );
17148    }
17149
17150    #[test]
17151    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
17152        let paths = nested_parallel_paths();
17153        let history = vec![
17154            parallel_history_event(
17155                "ActivityScheduled",
17156                1,
17157                "activity_type",
17158                "first",
17159                paths[0].clone(),
17160                None,
17161            ),
17162            parallel_history_event(
17163                "ChildWorkflowScheduled",
17164                2,
17165                "child_workflow_type",
17166                "second",
17167                paths[1].clone(),
17168                None,
17169            ),
17170            parallel_history_event(
17171                "ActivityScheduled",
17172                3,
17173                "activity_type",
17174                "third",
17175                paths[2].clone(),
17176                None,
17177            ),
17178        ];
17179        for _restart in 0..2 {
17180            let ctx = workflow_context(history.clone());
17181            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17182            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17183            let outcome = call.as_mut().poll(&mut task_context);
17184            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
17185            assert!(ctx.take_commands().expect("commands").is_empty());
17186        }
17187    }
17188
17189    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
17190        vec![selection_group_entry(
17191            1,
17192            2,
17193            index,
17194            "activity",
17195            &SelectionMemberMetadata {
17196                key: SelectionKey::Name(key.to_string()),
17197                index,
17198                base_sequence: index as u64 + 1,
17199                size: 1,
17200                kind: "activity".to_string(),
17201            },
17202        )]
17203    }
17204
17205    fn selection_activity_event(
17206        event_type: &str,
17207        index: usize,
17208        key: &str,
17209        result: Option<Value>,
17210    ) -> HistoryEvent {
17211        let sequence = index as u64 + 1;
17212        let mut event = parallel_history_event(
17213            event_type,
17214            sequence,
17215            "activity_type",
17216            &format!("{key}-activity"),
17217            selection_path(index, key),
17218            result,
17219        );
17220        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
17221        event.raw.insert(
17222            "id".to_string(),
17223            json!(if event_type == "ActivityCompleted" {
17224                format!("event-{key}")
17225            } else {
17226                format!("{event_type}-{key}")
17227            }),
17228        );
17229        event
17230    }
17231
17232    fn selection_winner_marker() -> HistoryEvent {
17233        history_event(
17234            "SelectionResolved",
17235            json!({
17236                "selection_group_id": "select-calls:1:2",
17237                "selection_group_base_sequence": 1,
17238                "selection_group_size": 2,
17239                "member_key": "fast",
17240                "member_index": 1,
17241                "member_base_sequence": 2,
17242                "member_size": 1,
17243                "operation_kind": "activity",
17244                "operation_identity": "activity-fast",
17245                "outcome": "completed",
17246                "resolution_event_id": "event-fast",
17247                "resolution_event_type": "ActivityCompleted",
17248            }),
17249        )
17250    }
17251
17252    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
17253        ctx.select_keyed(vec![
17254            (
17255                "slow",
17256                ParallelOperation::activity_with_options(
17257                    "slow-activity",
17258                    ActivityOptions::new().task_queue("default"),
17259                    json!([]),
17260                ),
17261            ),
17262            (
17263                "fast",
17264                ParallelOperation::activity_with_options(
17265                    "fast-activity",
17266                    ActivityOptions::new().task_queue("default"),
17267                    json!([]),
17268                ),
17269            ),
17270        ])
17271    }
17272
17273    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
17274        let ctx = workflow_context(history);
17275        let mut call = Box::pin(keyed_activity_selection(&ctx));
17276        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17277        let selected = match call.as_mut().poll(&mut task_context) {
17278            Poll::Ready(Ok(selected)) => selected,
17279            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
17280            Poll::Pending => panic!("persisted selection winner must replay without pending"),
17281        };
17282        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
17283        assert_eq!(
17284            selected.value,
17285            Some(ParallelResult::Activity(json!("winner-value")))
17286        );
17287        let slow = selected
17288            .handle(&SelectionKey::Name("slow".to_string()))
17289            .expect("slow handle")
17290            .clone();
17291        let mut await_slow = Box::pin(slow.await_result());
17292        assert!(matches!(
17293            await_slow.as_mut().poll(&mut task_context),
17294            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
17295        ));
17296        assert!(ctx.take_commands().expect("commands").is_empty());
17297    }
17298
17299    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
17300
17301    fn canonical_selection_history() -> Vec<HistoryEvent> {
17302        const FIXTURE: &[u8] =
17303            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
17304        assert_eq!(
17305            format!("{:x}", Sha256::digest(FIXTURE)),
17306            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
17307        );
17308        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
17309
17310        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
17311    }
17312
17313    #[test]
17314    fn selection_fresh_process_entrypoint() {
17315        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
17316            return;
17317        };
17318        let persisted = fs::read(path).expect("persisted selection history");
17319        assert_eq!(
17320            format!("{:x}", Sha256::digest(&persisted)),
17321            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
17322        );
17323        let fixture: Value =
17324            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
17325        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
17326            .expect("valid persisted selection history");
17327
17328        assert_persisted_selection_replay(history);
17329    }
17330
17331    #[test]
17332    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
17333        let ctx = workflow_context(Vec::new());
17334        let mut call = Box::pin(keyed_activity_selection(&ctx));
17335        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17336
17337        assert!(matches!(
17338            call.as_mut().poll(&mut task_context),
17339            Poll::Pending
17340        ));
17341        let commands = ctx.take_commands().expect("selection commands");
17342        assert_eq!(commands.len(), 2);
17343        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
17344        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
17345        assert!(commands.iter().all(|command| {
17346            command["parallel_group_id"] == json!("select-calls:1:2")
17347                && command["parallel_group_mode"] == json!("select")
17348        }));
17349    }
17350
17351    #[test]
17352    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
17353        let ctx = workflow_context(Vec::new());
17354        let mut invalid = Box::pin(ctx.select_keyed(vec![(
17355            "",
17356            ParallelOperation::activity("invalid", json!([])),
17357        )]));
17358        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17359        assert!(matches!(
17360            invalid.as_mut().poll(&mut task_context),
17361            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
17362                reason: "selection_key_invalid",
17363                ..
17364            })))
17365        ));
17366
17367        for invalid_key in [json!(""), json!(-1)] {
17368            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
17369            event.payload["selection_member_key"] = invalid_key.clone();
17370            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
17371            assert!(matches!(
17372                WorkflowState::new_with_identity(
17373                    vec![event],
17374                    None,
17375                    None,
17376                    "rust-workers".to_string(),
17377                    DEFAULT_CODEC.to_string(),
17378                    None,
17379                ),
17380                Err(Error::NonDeterministicReplay(_))
17381            ));
17382        }
17383    }
17384
17385    #[test]
17386    fn selection_preserves_valid_named_and_numeric_keys() {
17387        let ctx = workflow_context(Vec::new());
17388        let mut selection = Box::pin(ctx.select_keyed(vec![
17389            (
17390                SelectionKey::Index(0),
17391                ParallelOperation::activity("numeric", json!([])),
17392            ),
17393            (
17394                SelectionKey::Name("named".to_string()),
17395                ParallelOperation::timer(Duration::from_secs(1)),
17396            ),
17397        ]));
17398        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17399
17400        assert!(matches!(
17401            selection.as_mut().poll(&mut task_context),
17402            Poll::Pending
17403        ));
17404        let commands = ctx.take_commands().expect("selection commands");
17405        assert_eq!(commands[0]["selection_member_key"], json!(0));
17406        assert_eq!(commands[1]["selection_member_key"], json!("named"));
17407    }
17408
17409    #[test]
17410    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
17411        let history = canonical_selection_history();
17412        assert_persisted_selection_replay(history.clone());
17413
17414        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
17415            .join("tests/fixtures/durable_selection_runtime_history.json");
17416        let output =
17417            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
17418                .args([
17419                    "--exact",
17420                    "tests::selection_fresh_process_entrypoint",
17421                    "--nocapture",
17422                ])
17423                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
17424                .output()
17425                .expect("run fresh selection replay process");
17426
17427        assert!(
17428            output.status.success(),
17429            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
17430            String::from_utf8_lossy(&output.stdout),
17431            String::from_utf8_lossy(&output.stderr),
17432        );
17433    }
17434
17435    #[test]
17436    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
17437        let mut history = canonical_selection_history();
17438        history.retain(|event| event.event_type != "SelectionResolved");
17439        let ctx = workflow_context(history);
17440        let mut selection = Box::pin(keyed_activity_selection(&ctx));
17441        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17442
17443        assert!(matches!(
17444            selection.as_mut().poll(&mut task_context),
17445            Poll::Pending
17446        ));
17447        assert!(ctx.take_commands().expect("commands").is_empty());
17448        assert!(
17449            ctx.matched_recorded_pending()
17450                .expect("selection pending state"),
17451            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
17452        );
17453    }
17454
17455    #[test]
17456    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
17457        for (terminal_event, predicate_satisfied, timeout_seconds) in [
17458            ("ConditionWaitSatisfied", true, None),
17459            ("ConditionWaitTimedOut", false, Some(0)),
17460        ] {
17461            let member = SelectionMemberMetadata {
17462                key: SelectionKey::Name("condition".to_string()),
17463                index: 0,
17464                base_sequence: 1,
17465                size: 1,
17466                kind: "condition".to_string(),
17467            };
17468            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
17469            let mut payload = json!({
17470                "sequence": 1,
17471                "condition_wait_id": "condition-1",
17472                "condition_wait_occurrence_id": "rust:condition-wait:0",
17473                "condition_key": "ready",
17474                "condition_definition_fingerprint": "sha256:ready-v1",
17475                "parallel_group_path": path,
17476            });
17477            payload
17478                .as_object_mut()
17479                .expect("condition history payload")
17480                .extend(
17481                    serde_json::to_value(&path[0])
17482                        .expect("condition selection metadata")
17483                        .as_object()
17484                        .expect("condition selection metadata object")
17485                        .clone(),
17486                );
17487            if let Some(timeout_seconds) = timeout_seconds {
17488                payload["timeout_seconds"] = json!(timeout_seconds);
17489            }
17490            let history = vec![
17491                history_event("ConditionWaitOpened", payload.clone()),
17492                history_event(terminal_event, payload),
17493            ];
17494            let ctx = workflow_context(history);
17495            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
17496            if timeout_seconds.is_some() {
17497                options = options.timeout(Duration::ZERO);
17498            }
17499            let mut selection = Box::pin(ctx.select_keyed(vec![(
17500                "condition",
17501                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
17502            )]));
17503            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17504
17505            assert!(matches!(
17506                selection.as_mut().poll(&mut task_context),
17507                Poll::Pending
17508            ));
17509            assert!(ctx.take_commands().expect("commands").is_empty());
17510            assert!(
17511                ctx.matched_recorded_pending()
17512                    .expect("condition selection pending state"),
17513                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
17514            );
17515        }
17516    }
17517
17518    #[test]
17519    fn selection_immediate_condition_members_open_a_durable_wait() {
17520        for predicate_satisfied in [true, false] {
17521            let ctx = workflow_context(Vec::new());
17522            let mut selection = Box::pin(ctx.select_keyed(vec![(
17523                "condition",
17524                ParallelOperation::condition(
17525                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
17526                    move || Ok(predicate_satisfied),
17527                ),
17528            )]));
17529            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17530
17531            assert!(matches!(
17532                selection.as_mut().poll(&mut task_context),
17533                Poll::Pending
17534            ));
17535            let commands = ctx.take_commands().expect("condition selection command");
17536            assert_eq!(commands.len(), 1);
17537            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
17538            assert_eq!(commands[0]["timeout_seconds"], json!(0));
17539            assert_eq!(
17540                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
17541                json!("select")
17542            );
17543        }
17544    }
17545
17546    #[test]
17547    fn selection_loser_cancellation_is_explicit_and_idempotent() {
17548        let history = vec![
17549            selection_activity_event("ActivityScheduled", 0, "slow", None),
17550            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
17551            selection_winner_marker(),
17552        ];
17553        let ctx = workflow_context(history.clone());
17554        let mut call = Box::pin(keyed_activity_selection(&ctx));
17555        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17556        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
17557            panic!("winner must replay");
17558        };
17559        let slow = selected
17560            .handle(&SelectionKey::Name("slow".to_string()))
17561            .expect("slow handle")
17562            .clone();
17563        let mut cancel = Box::pin(slow.cancel());
17564        assert!(matches!(
17565            cancel.as_mut().poll(&mut task_context),
17566            Poll::Pending
17567        ));
17568        assert!(matches!(
17569            cancel.as_mut().poll(&mut task_context),
17570            Poll::Pending
17571        ));
17572        let commands = ctx.take_commands().expect("cancel command");
17573        assert_eq!(commands.len(), 1);
17574        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
17575        assert_eq!(commands[0]["member_key"], json!("slow"));
17576
17577        let mut cancelled_history = history;
17578        cancelled_history.push(history_event(
17579            "SelectionOperationCancelled",
17580            json!({
17581                "selection_group_id": "select-calls:1:2",
17582                "member_key": "slow",
17583                "member_index": 0,
17584                "member_base_sequence": 1,
17585                "member_size": 1,
17586                "operation_kind": "activity",
17587                "operation_identity": "activity-slow",
17588                "cancelled_at": "2026-08-27T00:00:00Z",
17589            }),
17590        ));
17591        let replayed = workflow_context(cancelled_history);
17592        let mut call = Box::pin(keyed_activity_selection(&replayed));
17593        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
17594            panic!("winner must replay after cancellation");
17595        };
17596        let slow = selected
17597            .handle(&SelectionKey::Name("slow".to_string()))
17598            .expect("slow handle")
17599            .clone();
17600        let mut cancel = Box::pin(slow.cancel());
17601        assert!(matches!(
17602            cancel.as_mut().poll(&mut task_context),
17603            Poll::Ready(Ok(()))
17604        ));
17605        assert!(replayed.take_commands().expect("commands").is_empty());
17606    }
17607
17608    #[test]
17609    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
17610        let base_history = vec![
17611            selection_activity_event("ActivityScheduled", 0, "slow", None),
17612            selection_activity_event("ActivityScheduled", 1, "fast", None),
17613            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
17614            selection_winner_marker(),
17615        ];
17616        for (field, corrupt) in [
17617            ("member_key", json!("fast")),
17618            ("member_index", json!(1)),
17619            ("member_base_sequence", json!(3)),
17620            ("member_size", json!(2)),
17621            ("operation_kind", json!("timer")),
17622            ("operation_identity", json!("forged")),
17623        ] {
17624            let mut cancellation = json!({
17625                "selection_group_id": "select-calls:1:2",
17626                "member_key": "slow",
17627                "member_index": 0,
17628                "member_base_sequence": 1,
17629                "member_size": 1,
17630                "operation_kind": "activity",
17631                "operation_identity": "activity-slow",
17632            });
17633            cancellation[field] = corrupt;
17634            let mut history = base_history.clone();
17635            history.push(history_event("SelectionOperationCancelled", cancellation));
17636            let ctx = workflow_context(history);
17637            let mut selection = Box::pin(keyed_activity_selection(&ctx));
17638            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17639
17640            assert!(matches!(
17641                selection.as_mut().poll(&mut task_context),
17642                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
17643            ));
17644        }
17645    }
17646
17647    #[test]
17648    fn selection_child_identity_prefers_the_durable_run_id() {
17649        let ctx = workflow_context(vec![history_event(
17650            "ChildWorkflowScheduled",
17651            json!({
17652                "sequence": 1,
17653                "child_workflow_type": "child",
17654                "child_workflow_instance_id": "child-instance",
17655                "child_workflow_run_id": "child-run",
17656            }),
17657        )]);
17658        let state = ctx.state.lock().expect("workflow state");
17659
17660        assert_eq!(
17661            selection_operation_identity(&state, "child", 1, 1),
17662            "child-run"
17663        );
17664    }
17665
17666    #[test]
17667    fn selection_activity_identity_requires_canonical_execution_id() {
17668        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
17669        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
17670        let mut fast_completed =
17671            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
17672        for event in [&mut fast_open, &mut fast_completed] {
17673            event
17674                .payload
17675                .as_object_mut()
17676                .expect("activity payload")
17677                .remove("activity_execution_id");
17678            event.payload["activity_id"] = json!("forged-activity-id");
17679        }
17680        let mut marker = selection_winner_marker();
17681        marker.payload["operation_identity"] = json!("forged-activity-id");
17682        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
17683        let mut selection = Box::pin(keyed_activity_selection(&ctx));
17684        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17685
17686        assert!(matches!(
17687            selection.as_mut().poll(&mut task_context),
17688            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
17689        ));
17690    }
17691
17692    #[test]
17693    fn selection_completion_before_cancellation_remains_awaitable() {
17694        let history = vec![
17695            selection_activity_event("ActivityScheduled", 0, "slow", None),
17696            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
17697            selection_winner_marker(),
17698            selection_activity_event(
17699                "ActivityCompleted",
17700                0,
17701                "slow",
17702                Some(json!("completed-first")),
17703            ),
17704        ];
17705        let ctx = workflow_context(history);
17706        let mut selection = Box::pin(keyed_activity_selection(&ctx));
17707        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17708        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
17709            panic!("winner must replay");
17710        };
17711        let slow = selected
17712            .handle(&SelectionKey::Name("slow".to_string()))
17713            .expect("slow handle")
17714            .clone();
17715        let mut cancel = Box::pin(slow.cancel());
17716        assert!(matches!(
17717            cancel.as_mut().poll(&mut task_context),
17718            Poll::Ready(Ok(()))
17719        ));
17720        let mut await_slow = Box::pin(slow.await_result());
17721        assert!(matches!(
17722            await_slow.as_mut().poll(&mut task_context),
17723            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
17724        ));
17725        let commands = ctx.take_commands().expect("commands");
17726        assert!(commands.is_empty());
17727    }
17728
17729    #[test]
17730    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
17731        let nested_member = SelectionMemberMetadata {
17732            key: SelectionKey::Name("nested".to_string()),
17733            index: 0,
17734            base_sequence: 1,
17735            size: 2,
17736            kind: "group".to_string(),
17737        };
17738        let deadline_member = SelectionMemberMetadata {
17739            key: SelectionKey::Name("deadline".to_string()),
17740            index: 1,
17741            base_sequence: 3,
17742            size: 1,
17743            kind: "timer".to_string(),
17744        };
17745        let nested_paths = [
17746            vec![
17747                selection_group_entry(1, 3, 0, "mixed", &nested_member),
17748                parallel_group_entry(1, 2, 0, "activity"),
17749            ],
17750            vec![
17751                selection_group_entry(1, 3, 1, "mixed", &nested_member),
17752                parallel_group_entry(1, 2, 1, "activity"),
17753            ],
17754        ];
17755        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
17756        let mut timer_fired = parallel_history_event(
17757            "TimerFired",
17758            3,
17759            "timer_id",
17760            "timer-3",
17761            deadline_path.clone(),
17762            None,
17763        );
17764        timer_fired.payload["delay_seconds"] = json!(0);
17765        timer_fired
17766            .raw
17767            .insert("id".to_string(), json!("timer-fired"));
17768        let mut timer_scheduled = parallel_history_event(
17769            "TimerScheduled",
17770            3,
17771            "timer_id",
17772            "timer-3",
17773            deadline_path,
17774            None,
17775        );
17776        timer_scheduled.payload["delay_seconds"] = json!(0);
17777        let history = vec![
17778            parallel_history_event(
17779                "ActivityScheduled",
17780                1,
17781                "activity_type",
17782                "nested-first",
17783                nested_paths[0].clone(),
17784                None,
17785            ),
17786            parallel_history_event(
17787                "ActivityScheduled",
17788                2,
17789                "activity_type",
17790                "nested-second",
17791                nested_paths[1].clone(),
17792                None,
17793            ),
17794            timer_scheduled,
17795            timer_fired,
17796            history_event(
17797                "SelectionResolved",
17798                json!({
17799                    "selection_group_id": "select-calls:1:3",
17800                    "selection_group_base_sequence": 1,
17801                    "selection_group_size": 3,
17802                    "member_key": "deadline",
17803                    "member_index": 1,
17804                    "member_base_sequence": 3,
17805                    "member_size": 1,
17806                    "operation_kind": "timer",
17807                    "operation_identity": "timer-3",
17808                    "outcome": "completed",
17809                    "resolution_event_id": "timer-fired",
17810                    "resolution_event_type": "TimerFired",
17811                }),
17812            ),
17813            parallel_history_event(
17814                "ActivityFailed",
17815                2,
17816                "activity_type",
17817                "nested-second",
17818                nested_paths[1].clone(),
17819                None,
17820            ),
17821        ];
17822        let ctx = workflow_context(history);
17823        let mut selection = Box::pin(ctx.select_keyed(vec![
17824            (
17825                "nested",
17826                ParallelOperation::group(vec![
17827                    ParallelOperation::activity("nested-first", json!([])),
17828                    ParallelOperation::activity("nested-second", json!([])),
17829                ]),
17830            ),
17831            ("deadline", ParallelOperation::timer(Duration::ZERO)),
17832        ]));
17833        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17834        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
17835            panic!("deadline winner must replay");
17836        };
17837        let nested = selected
17838            .handle(&SelectionKey::Name("nested".to_string()))
17839            .expect("nested handle")
17840            .clone();
17841        let mut cancel = Box::pin(nested.cancel());
17842        assert!(matches!(
17843            cancel.as_mut().poll(&mut task_context),
17844            Poll::Ready(Ok(()))
17845        ));
17846        let mut await_nested = Box::pin(nested.await_result());
17847
17848        assert!(matches!(
17849            await_nested.as_mut().poll(&mut task_context),
17850            Poll::Ready(Err(Error::ActivityFailed(_)))
17851        ));
17852        assert!(ctx.take_commands().expect("commands").is_empty());
17853    }
17854
17855    #[test]
17856    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
17857        let ctx = workflow_context(Vec::new());
17858        let mut call = Box::pin(ctx.select(vec![
17859            ParallelOperation::child_workflow(
17860                "child",
17861                ChildWorkflowOptions::new("children"),
17862                json!([]),
17863            ),
17864            ParallelOperation::timer(Duration::from_secs(30)),
17865            ParallelOperation::signal("approval"),
17866            ParallelOperation::condition(
17867                ConditionWaitOptions::new("ready", "sha256:ready"),
17868                || Ok(false),
17869            ),
17870            ParallelOperation::group(vec![
17871                ParallelOperation::activity("nested-one", json!([])),
17872                ParallelOperation::activity("nested-two", json!([])),
17873            ]),
17874        ]));
17875        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17876        assert!(matches!(
17877            call.as_mut().poll(&mut task_context),
17878            Poll::Pending
17879        ));
17880        let commands = ctx.take_commands().expect("selection commands");
17881        assert_eq!(
17882            commands
17883                .iter()
17884                .map(|command| command["type"].as_str().unwrap_or_default())
17885                .collect::<Vec<_>>(),
17886            [
17887                "start_child_workflow",
17888                "start_timer",
17889                "open_signal_wait",
17890                "open_condition_wait",
17891                "schedule_activity",
17892                "schedule_activity",
17893            ]
17894        );
17895        assert!(commands.iter().all(|command| {
17896            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
17897        }));
17898        assert_eq!(
17899            commands[4]["parallel_group_path"].as_array().map(Vec::len),
17900            Some(2)
17901        );
17902        assert_eq!(
17903            commands[4]["parallel_group_path"][0]["selection_member_kind"],
17904            json!("group")
17905        );
17906        assert_eq!(
17907            commands[5]["parallel_group_path"][0]["selection_member_kind"],
17908            json!("group")
17909        );
17910
17911        let one_leaf_ctx = workflow_context(Vec::new());
17912        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
17913            ParallelOperation::activity("nested-only", json!([])),
17914        ])]));
17915        assert!(matches!(
17916            one_leaf.as_mut().poll(&mut task_context),
17917            Poll::Pending
17918        ));
17919        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
17920        assert_eq!(one_leaf_commands.len(), 1);
17921        assert_eq!(
17922            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
17923            json!("group")
17924        );
17925        assert_eq!(
17926            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
17927            json!(1)
17928        );
17929    }
17930
17931    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
17932        let mut saga = ctx.saga();
17933        let outcome = async {
17934            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
17935            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
17936            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
17937            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
17938            ctx.activity("trip.charge", json!([])).await?;
17939            Ok(json!({"status": "booked"}))
17940        }
17941        .await;
17942        saga.finish(outcome).await
17943    }
17944
17945    fn saga_activity(
17946        event_type: &str,
17947        sequence: u64,
17948        activity_type: &str,
17949        result: Option<Value>,
17950    ) -> HistoryEvent {
17951        let mut payload = json!({
17952            "sequence": sequence,
17953            "activity_type": activity_type,
17954            "message": format!("{activity_type} failed"),
17955            "exception_type": "PlannedFailure",
17956            "non_retryable": true,
17957        });
17958        if let Some(result) = result {
17959            payload["result"] = fixture_envelope(result);
17960        }
17961        history_event(event_type, payload)
17962    }
17963
17964    #[test]
17965    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
17966        let completed_hotel_compensation = saga_activity(
17967            "ActivityCompleted",
17968            4,
17969            "trip.cancel-hotel",
17970            Some(Value::Null),
17971        );
17972        let history = vec![
17973            saga_activity(
17974                "ActivityCompleted",
17975                1,
17976                "trip.reserve-flight",
17977                Some(json!("flight-1")),
17978            ),
17979            saga_activity(
17980                "ActivityCompleted",
17981                2,
17982                "trip.reserve-hotel",
17983                Some(json!("hotel-1")),
17984            ),
17985            saga_activity("ActivityFailed", 3, "trip.charge", None),
17986            completed_hotel_compensation.clone(),
17987            completed_hotel_compensation,
17988        ];
17989
17990        for _restart in 0..2 {
17991            let ctx = workflow_context(history.clone());
17992            let mut future = Box::pin(trip_saga(ctx.clone()));
17993            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17994            assert!(matches!(
17995                future.as_mut().poll(&mut task_context),
17996                Poll::Pending
17997            ));
17998            let commands = ctx.take_commands().expect("compensation command");
17999            assert_eq!(commands.len(), 1);
18000            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18001        }
18002    }
18003
18004    #[test]
18005    fn saga_compensation_failure_preserves_both_typed_failures() {
18006        let history = vec![
18007            saga_activity(
18008                "ActivityCompleted",
18009                1,
18010                "trip.reserve-flight",
18011                Some(json!("flight-1")),
18012            ),
18013            saga_activity(
18014                "ActivityCompleted",
18015                2,
18016                "trip.reserve-hotel",
18017                Some(json!("hotel-1")),
18018            ),
18019            saga_activity("ActivityFailed", 3, "trip.charge", None),
18020            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
18021        ];
18022        let ctx = workflow_context(history);
18023        let mut future = Box::pin(trip_saga(ctx));
18024        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18025        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
18026            future.as_mut().poll(&mut task_context)
18027        else {
18028            panic!("compensation failure must remain structured");
18029        };
18030        assert!(matches!(
18031            *failure.initiating_failure,
18032            Error::ActivityFailed(_)
18033        ));
18034        assert!(matches!(
18035            *failure.compensation_failure,
18036            Error::ActivityFailed(_)
18037        ));
18038        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
18039        assert_eq!(failure.compensation_registration_order, 2);
18040    }
18041
18042    #[test]
18043    fn saga_compensates_cooperative_cancellation() {
18044        let ctx = workflow_context(vec![saga_activity(
18045            "ActivityCompleted",
18046            1,
18047            "trip.reserve-flight",
18048            Some(json!("flight-1")),
18049        )]);
18050        ctx.state.lock().expect("state").cancel_requested = true;
18051        let run = {
18052            let ctx = ctx.clone();
18053            async move {
18054                let mut saga = ctx.saga();
18055                let outcome = async {
18056                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18057                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18058                    ctx.throw_if_cancellation_requested()?;
18059                    Ok(json!("unexpected"))
18060                }
18061                .await;
18062                saga.finish(outcome).await
18063            }
18064        };
18065        let mut future = Box::pin(run);
18066        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18067        assert!(matches!(
18068            future.as_mut().poll(&mut task_context),
18069            Poll::Pending
18070        ));
18071        let commands = ctx.take_commands().expect("cancellation compensation");
18072        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18073    }
18074
18075    fn workflow_task(
18076        workflow_type: &str,
18077        history_events: Vec<HistoryEvent>,
18078        payload_codec: &str,
18079    ) -> WorkflowTask {
18080        WorkflowTask {
18081            task_id: format!("wft-{workflow_type}"),
18082            workflow_command_id: None,
18083            workflow_id: Some(format!("wf-{workflow_type}")),
18084            run_id: Some(format!("run-{workflow_type}")),
18085            workflow_type: workflow_type.to_string(),
18086            cancel_requested: false,
18087            payload_codec: payload_codec.to_string(),
18088            arguments: Some(
18089                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
18090            ),
18091            total_history_events: Some(history_events.len() as u64),
18092            history_size_bytes: None,
18093            continue_as_new_recommended: None,
18094            history_budget_pressure: None,
18095            history_events,
18096            next_history_page_token: None,
18097            workflow_task_attempt: 1,
18098            workflow_signal_id: None,
18099            signal_name: None,
18100            signal_arguments: None,
18101            workflow_update_id: None,
18102            update_name: None,
18103            lease_owner: Some("rust-worker".to_string()),
18104        }
18105    }
18106
18107    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18108    struct SideEffectProbe {
18109        request_id: String,
18110        attempt: u32,
18111    }
18112
18113    #[test]
18114    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
18115        let calls = AtomicUsize::new(0);
18116        let ctx = workflow_context(Vec::new());
18117        let value = ctx
18118            .side_effect(|| {
18119                calls.fetch_add(1, Ordering::SeqCst);
18120                SideEffectProbe {
18121                    request_id: "request-42".to_string(),
18122                    attempt: 3,
18123                }
18124            })
18125            .expect("first side effect");
18126        assert_eq!(value.attempt, 3);
18127        assert_eq!(calls.load(Ordering::SeqCst), 1);
18128        let commands = ctx.take_commands().expect("commands");
18129        assert_eq!(commands.len(), 1);
18130        assert_eq!(commands[0]["type"], "record_side_effect");
18131        assert_eq!(
18132            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18133            serde_json::to_value(&value).expect("value")
18134        );
18135
18136        let replay = workflow_context(vec![history_event(
18137            "SideEffectRecorded",
18138            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18139        )]);
18140        let replayed: SideEffectProbe = replay
18141            .side_effect(|| {
18142                calls.fetch_add(1, Ordering::SeqCst);
18143                panic!("committed side-effect callbacks must not run during replay")
18144            })
18145            .expect("replayed side effect");
18146        assert_eq!(replayed, value);
18147        assert_eq!(calls.load(Ordering::SeqCst), 1);
18148        assert!(replay.take_commands().expect("commands").is_empty());
18149        replay.ensure_history_consumed().expect("history consumed");
18150    }
18151
18152    #[test]
18153    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
18154        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18155        let value = ctx
18156            .side_effect(|| SideEffectProbe {
18157                request_id: "avro-request".to_string(),
18158                attempt: 1,
18159            })
18160            .expect("Avro side effect");
18161        let uuid = ctx.uuid_v4().expect("deterministic UUID");
18162        let commands = ctx.take_commands().expect("commands");
18163        assert_eq!(commands.len(), 2);
18164        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
18165        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
18166        assert_eq!(
18167            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18168            serde_json::to_value(&value).expect("value")
18169        );
18170
18171        let replay = workflow_context_with_codec(
18172            vec![
18173                history_event(
18174                    "SideEffectRecorded",
18175                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18176                ),
18177                history_event(
18178                    "SideEffectRecorded",
18179                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
18180                ),
18181            ],
18182            DEFAULT_CODEC,
18183        );
18184        let replayed: SideEffectProbe = replay
18185            .side_effect(|| panic!("Avro callback must not run"))
18186            .expect("replayed Avro value");
18187        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
18188        assert_eq!(replayed, value);
18189        assert_eq!(replayed_uuid, uuid);
18190        assert!(replay.take_commands().expect("commands").is_empty());
18191    }
18192
18193    #[test]
18194    fn typed_side_effect_replay_preserves_bytes_and_maps() {
18195        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18196        let value = ctx
18197            .side_effect_avro_value(typed_fidelity_probe)
18198            .expect("typed side effect");
18199        let commands = ctx.take_commands().expect("side-effect command");
18200        assert_eq!(
18201            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
18202                .expect("recorded side effect"),
18203            value
18204        );
18205
18206        let replay = workflow_context_with_codec(
18207            vec![history_event(
18208                "SideEffectRecorded",
18209                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18210            )],
18211            DEFAULT_CODEC,
18212        );
18213        assert_eq!(
18214            replay
18215                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
18216                .expect("replayed typed side effect"),
18217            value
18218        );
18219    }
18220
18221    #[test]
18222    fn ordered_side_effects_share_the_durable_command_stream() {
18223        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
18224        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
18225        let ctx = workflow_context(vec![
18226            history_event(
18227                "SideEffectRecorded",
18228                json!({"sequence": 1, "result": first}),
18229            ),
18230            history_event(
18231                "SideEffectRecorded",
18232                json!({"sequence": 2, "result": second}),
18233            ),
18234        ]);
18235        let first: String = ctx
18236            .side_effect(|| panic!("first callback must not run"))
18237            .expect("first replay");
18238        let second: i32 = ctx
18239            .side_effect(|| panic!("second callback must not run"))
18240            .expect("second replay");
18241        assert_eq!(first, "first");
18242        assert_eq!(second, 29);
18243        ctx.ensure_history_consumed().expect("ordered history");
18244
18245        let reordered = workflow_context(vec![history_event(
18246            "VersionMarkerRecorded",
18247            json!({
18248                "sequence": 1,
18249                "change_id": "before-side-effect",
18250                "version": 1,
18251                "min_supported": 1,
18252                "max_supported": 1,
18253            }),
18254        )]);
18255        let error = reordered
18256            .side_effect(|| "new".to_string())
18257            .expect_err("command reordering must fail");
18258        assert!(matches!(
18259            error,
18260            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18261                if reason == "recorded_command_mismatch"
18262        ));
18263    }
18264
18265    #[test]
18266    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
18267        let ctx = workflow_context(Vec::new());
18268        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
18269        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
18270        assert!(ctx.patched("new-search").expect("patch"));
18271        ctx.deprecate_patch("new-search").expect("deprecate patch");
18272        let commands = ctx.take_commands().expect("commands");
18273        assert_eq!(commands.len(), 2);
18274        assert_eq!(commands[0]["type"], "record_version_marker");
18275        assert_eq!(commands[0]["version"], 2);
18276        assert_eq!(commands[1]["change_id"], "new-search");
18277
18278        let replay = workflow_context(vec![history_event(
18279            "VersionMarkerRecorded",
18280            json!({
18281                "sequence": 1,
18282                "change_id": "checkout-v2",
18283                "version": 2,
18284                "min_supported": 1,
18285                "max_supported": 2,
18286            }),
18287        )]);
18288        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
18289        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
18290        assert!(replay.take_commands().expect("commands").is_empty());
18291        replay.ensure_history_consumed().expect("history consumed");
18292    }
18293
18294    #[test]
18295    fn version_markers_reject_incompatible_or_malformed_history() {
18296        let incompatible = workflow_context(vec![history_event(
18297            "VersionMarkerRecorded",
18298            json!({
18299                "sequence": 1,
18300                "change_id": "checkout-v2",
18301                "version": 1,
18302                "min_supported": 1,
18303                "max_supported": 2,
18304            }),
18305        )]);
18306        let error = incompatible
18307            .get_version("checkout-v2", 2, 3)
18308            .expect_err("old version is unsupported");
18309        assert!(matches!(
18310            error,
18311            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18312                if reason == "version_marker_incompatible_range"
18313        ));
18314
18315        for (history, reason) in [
18316            (
18317                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
18318                "side_effect_result_missing",
18319            ),
18320            (
18321                vec![history_event(
18322                    "SideEffectRecorded",
18323                    json!({
18324                        "sequence": 1,
18325                        "result": {"codec": "avro", "blob": "not-base64"},
18326                    }),
18327                )],
18328                "side_effect_payload_incompatible",
18329            ),
18330            (
18331                vec![history_event(
18332                    "SideEffectRecorded",
18333                    json!({"sequence": 1, "result": {"unwrapped": true}}),
18334                )],
18335                "side_effect_payload_malformed",
18336            ),
18337            (
18338                vec![history_event(
18339                    "VersionMarkerRecorded",
18340                    json!({
18341                        "sequence": 1,
18342                        "change_id": "change",
18343                        "version": 1,
18344                        "min_supported": 2,
18345                        "max_supported": 1,
18346                    }),
18347                )],
18348                "version_marker_history_range_invalid",
18349            ),
18350        ] {
18351            let error = WorkflowState::new(
18352                history,
18353                "rust-workers".to_string(),
18354                DEFAULT_CODEC.to_string(),
18355                None,
18356            )
18357            .expect_err("malformed history must fail");
18358            assert!(matches!(
18359                error,
18360                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
18361                    if actual == reason
18362            ));
18363        }
18364    }
18365
18366    #[test]
18367    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
18368        let history = vec![history_event(
18369            "SearchAttributesUpserted",
18370            json!({
18371                "sequence": 1,
18372                "attributes": {"customer_tier": "gold"},
18373                "attribute_types": {"customer_tier": "keyword"},
18374                "merged": {"customer_tier": "gold"}
18375            }),
18376        )];
18377
18378        let matching = workflow_context(history.clone());
18379        matching
18380            .upsert_search_attributes(
18381                SearchAttributeUpdate::new()
18382                    .keyword("customer_tier", "gold")
18383                    .expect("keyword update"),
18384            )
18385            .expect("matching typed update must replay");
18386        matching
18387            .ensure_history_consumed()
18388            .expect("history consumed");
18389
18390        let changed_type = workflow_context(history.clone());
18391        let error = changed_type
18392            .upsert_search_attributes(
18393                SearchAttributeUpdate::new()
18394                    .string("customer_tier", "gold")
18395                    .expect("string update"),
18396            )
18397            .expect_err("same JSON value with a different declaration must be nondeterministic");
18398        let Error::NonDeterministicReplay(failure) = error else {
18399            panic!("typed identity drift must be a replay failure");
18400        };
18401        assert_eq!(failure.reason, "search_attribute_type_mismatch");
18402        assert_eq!(failure.sequence, Some(1));
18403
18404        let changed_value = workflow_context(history);
18405        let error = changed_value
18406            .upsert_search_attributes(
18407                SearchAttributeUpdate::new()
18408                    .keyword("customer_tier", "platinum")
18409                    .expect("keyword update"),
18410            )
18411            .expect_err("changed values must be nondeterministic");
18412        let Error::NonDeterministicReplay(failure) = error else {
18413            panic!("value drift must be a replay failure");
18414        };
18415        assert_eq!(failure.reason, "search_attribute_value_mismatch");
18416    }
18417
18418    #[test]
18419    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
18420        let history = vec![history_event(
18421            "SearchAttributesUpserted",
18422            json!({
18423                "sequence": 1,
18424                "attributes": {"customer_tier": "gold"},
18425                "merged": {"customer_tier": "gold"}
18426            }),
18427        )];
18428
18429        for update in [
18430            SearchAttributeUpdate::new()
18431                .keyword("customer_tier", "gold")
18432                .expect("keyword update"),
18433            SearchAttributeUpdate::new()
18434                .string("customer_tier", "gold")
18435                .expect("string update"),
18436        ] {
18437            let restarted = workflow_context(history.clone());
18438            restarted
18439                .upsert_search_attributes(update)
18440                .expect("legacy history constrains values but has unknown type identity");
18441            restarted
18442                .ensure_history_consumed()
18443                .expect("history consumed");
18444        }
18445    }
18446
18447    #[test]
18448    fn search_attribute_command_emits_canonical_types() {
18449        let ctx = workflow_context(Vec::new());
18450        ctx.upsert_search_attributes(
18451            SearchAttributeUpdate::new()
18452                .keyword("customer_tier", "gold")
18453                .expect("keyword update")
18454                .int("attempts", 3)
18455                .expect("int update")
18456                .delete("obsolete")
18457                .expect("delete update"),
18458        )
18459        .expect("valid search attributes");
18460
18461        assert_eq!(
18462            ctx.take_commands().expect("commands"),
18463            vec![json!({
18464                "type": "upsert_search_attributes",
18465                "attributes": {
18466                    "attempts": 3,
18467                    "customer_tier": "gold",
18468                    "obsolete": null
18469                },
18470                "attribute_types": {
18471                    "attempts": "int",
18472                    "customer_tier": "keyword"
18473                }
18474            })]
18475        );
18476    }
18477
18478    #[test]
18479    fn duplicate_side_effects_and_version_markers_are_rejected() {
18480        let duplicate_side_effect = WorkflowState::new(
18481            vec![
18482                history_event(
18483                    "SideEffectRecorded",
18484                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
18485                ),
18486                history_event(
18487                    "SideEffectRecorded",
18488                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
18489                ),
18490            ],
18491            "rust-workers".to_string(),
18492            DEFAULT_CODEC.to_string(),
18493            None,
18494        )
18495        .expect_err("duplicate side effect");
18496        assert!(matches!(
18497            duplicate_side_effect,
18498            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18499                if reason == "duplicate_side_effect_record"
18500        ));
18501
18502        let marker = |sequence| {
18503            history_event(
18504                "VersionMarkerRecorded",
18505                json!({
18506                    "sequence": sequence,
18507                    "change_id": "same-change",
18508                    "version": 1,
18509                    "min_supported": 1,
18510                    "max_supported": 1,
18511                }),
18512            )
18513        };
18514        let duplicate_marker = WorkflowState::new(
18515            vec![marker(1), marker(3)],
18516            "rust-workers".to_string(),
18517            DEFAULT_CODEC.to_string(),
18518            None,
18519        )
18520        .expect_err("duplicate marker");
18521        assert!(matches!(
18522            duplicate_marker,
18523            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18524                if reason == "duplicate_version_marker"
18525        ));
18526    }
18527
18528    #[test]
18529    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
18530        let mut state = WorkflowState::new(
18531            Vec::new(),
18532            "rust-workers".to_string(),
18533            DEFAULT_CODEC.to_string(),
18534            None,
18535        )
18536        .expect("workflow state");
18537        state.workflow_command_identity = "command-7".to_string();
18538        let context = WorkflowContext {
18539            state: Arc::new(Mutex::new(state)),
18540            cancellation_scope_id: "root".into(),
18541        };
18542        let item =
18543            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
18544
18545        context
18546            .append_workflow_stream("output", &[item], Some(10))
18547            .expect("append command");
18548        context
18549            .error_workflow_stream("output", "producer failed", None)
18550            .expect("error command");
18551        let commands = context.take_commands().expect("commands");
18552
18553        assert_eq!(commands[0]["type"], "record_side_effect");
18554        assert_eq!(
18555            commands[0]["workflow_stream"]["command_identity"],
18556            "command-7"
18557        );
18558        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
18559        assert_eq!(
18560            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
18561            "dw-stream:command-7:0:0"
18562        );
18563        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
18564
18565        let recorded = history_event(
18566            "SideEffectRecorded",
18567            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
18568        );
18569        let mut replay_state = WorkflowState::new(
18570            vec![recorded],
18571            "rust-workers".to_string(),
18572            DEFAULT_CODEC.to_string(),
18573            None,
18574        )
18575        .expect("replay state");
18576        replay_state.workflow_command_identity = "command-7".to_string();
18577        let replay_context = WorkflowContext {
18578            state: Arc::new(Mutex::new(replay_state)),
18579            cancellation_scope_id: "root".into(),
18580        };
18581        replay_context
18582            .append_workflow_stream(
18583                "output",
18584                &[WorkflowStreamAppendItem::from_reference(
18585                    "s3://bucket/item.avro",
18586                )],
18587                Some(10),
18588            )
18589            .expect("replayed append");
18590        assert!(replay_context
18591            .take_commands()
18592            .expect("replayed commands")
18593            .is_empty());
18594    }
18595
18596    #[test]
18597    fn workflow_stream_authoring_requires_server_durable_command_identity() {
18598        let context = workflow_context(Vec::new());
18599        let error = context
18600            .append_workflow_stream(
18601                "output",
18602                &[WorkflowStreamAppendItem::from_reference(
18603                    "s3://bucket/item.avro",
18604                )],
18605                None,
18606            )
18607            .expect_err("stream append without durable command identity must fail closed");
18608
18609        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
18610        assert!(context.take_commands().expect("commands").is_empty());
18611    }
18612
18613    #[test]
18614    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
18615        let client = Client::builder("http://localhost:8080").build().unwrap();
18616        let mut worker = Worker::new(client, "rust-workers");
18617        worker.register_workflow("streams.worker", |ctx, _| async move {
18618            ctx.append_workflow_stream(
18619                "output",
18620                &[WorkflowStreamAppendItem::new(json!("hello"))?],
18621                None,
18622            )?;
18623            ctx.close_workflow_stream("output", None)?;
18624            Ok(json!("done"))
18625        });
18626        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
18627            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
18628            task.workflow_command_id = command_id.clone();
18629            let expected_identity = command_id
18630                .as_deref()
18631                .filter(|id| !id.is_empty())
18632                .unwrap_or(&task.task_id)
18633                .to_string();
18634            let commands = worker
18635                .execute_workflow_task(task)
18636                .expect("ordinary worker stream output");
18637            assert_eq!(commands.len(), 3);
18638            assert_eq!(
18639                commands[0]["workflow_stream"]["command_identity"],
18640                expected_identity
18641            );
18642            assert_eq!(
18643                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
18644                format!("dw-stream:{expected_identity}:0:0")
18645            );
18646            assert_eq!(
18647                commands[1]["workflow_stream"]["command_identity"],
18648                expected_identity
18649            );
18650            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
18651            let history = commands[..2]
18652                .iter()
18653                .enumerate()
18654                .map(|(index, command)| {
18655                    history_event(
18656                        "SideEffectRecorded",
18657                        json!({"sequence":index + 1,"result":command["result"]}),
18658                    )
18659                })
18660                .collect();
18661            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
18662            replay.task_id = "replacement-task".to_string();
18663            let replayed = worker
18664                .execute_workflow_task(replay)
18665                .expect("replacement worker consumes recorded stream effects");
18666            assert_eq!(replayed.len(), 1);
18667            assert_eq!(replayed[0]["type"], "complete_workflow");
18668        }
18669        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
18670        missing.task_id.clear();
18671        assert!(matches!(
18672            worker.execute_workflow_task(missing),
18673            Err(Error::MissingWorkflowCommandIdentity)
18674        ));
18675    }
18676
18677    #[test]
18678    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
18679        fn worker(calls: Arc<AtomicUsize>) -> Worker {
18680            let client = Client::new("http://127.0.0.1:8080").expect("client");
18681            let mut worker = Worker::new(client, "rust-workers");
18682            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
18683                let calls = Arc::clone(&calls);
18684                async move {
18685                    let captured = ctx.side_effect(|| {
18686                        calls.fetch_add(1, Ordering::SeqCst);
18687                        "captured-once".to_string()
18688                    })?;
18689                    let version = ctx.get_version("cold-restart", 1, 2)?;
18690                    Ok(json!({"captured": captured, "version": version}))
18691                }
18692            });
18693            worker
18694        }
18695
18696        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
18697            WorkflowTask {
18698                task_id: "wft-side-effect-version".to_string(),
18699                workflow_command_id: None,
18700                workflow_id: Some("wf-side-effect-version".to_string()),
18701                run_id: Some("run-side-effect-version".to_string()),
18702                workflow_type: "rust.side-effect-version".to_string(),
18703                cancel_requested: false,
18704                payload_codec: DEFAULT_CODEC.to_string(),
18705                arguments: Some(
18706                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
18707                ),
18708                history_events,
18709                total_history_events: None,
18710                history_size_bytes: None,
18711                continue_as_new_recommended: None,
18712                history_budget_pressure: None,
18713                next_history_page_token: None,
18714                workflow_task_attempt: 1,
18715                workflow_signal_id: None,
18716                signal_name: None,
18717                signal_arguments: None,
18718                workflow_update_id: None,
18719                update_name: None,
18720                lease_owner: Some("rust-worker".to_string()),
18721            }
18722        }
18723
18724        let calls = Arc::new(AtomicUsize::new(0));
18725        let initial = worker(Arc::clone(&calls))
18726            .execute_workflow_task(task(Vec::new()))
18727            .expect("initial execution");
18728        assert_eq!(
18729            initial
18730                .iter()
18731                .map(|command| &command["type"])
18732                .collect::<Vec<_>>(),
18733            vec![
18734                "record_side_effect",
18735                "record_version_marker",
18736                "complete_workflow"
18737            ]
18738        );
18739        assert_eq!(calls.load(Ordering::SeqCst), 1);
18740
18741        let restarted = worker(Arc::clone(&calls));
18742        let replayed = restarted
18743            .execute_workflow_task(task(vec![
18744                history_event(
18745                    "SideEffectRecorded",
18746                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
18747                ),
18748                history_event(
18749                    "VersionMarkerRecorded",
18750                    json!({
18751                        "sequence": 2,
18752                        "change_id": "cold-restart",
18753                        "version": 2,
18754                        "min_supported": 1,
18755                        "max_supported": 2,
18756                    }),
18757                ),
18758            ]))
18759            .expect("cold replay");
18760        assert_eq!(replayed.len(), 1);
18761        assert_eq!(replayed[0]["type"], "complete_workflow");
18762        assert_eq!(calls.load(Ordering::SeqCst), 1);
18763    }
18764
18765    #[test]
18766    fn side_effect_replay_rejects_changed_rust_value_type() {
18767        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
18768        let ctx = workflow_context(vec![history_event(
18769            "SideEffectRecorded",
18770            json!({"sequence": 1, "result": result}),
18771        )]);
18772        let error = ctx
18773            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
18774            .expect_err("changed type must fail replay");
18775        assert!(matches!(
18776            error,
18777            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18778                if reason == "side_effect_type_mismatch"
18779        ));
18780    }
18781
18782    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
18783        vec![
18784            history_event(
18785                "ActivityScheduled",
18786                json!({
18787                    "sequence": 1,
18788                    "activity_type": "flaky",
18789                    "activity_execution_id": "act-1",
18790                    "activity": {
18791                        "id": "act-1",
18792                        "sequence": 1,
18793                        "type": "flaky",
18794                        "queue": "critical-activities",
18795                        "execution_mode": null,
18796                        "retry_policy": {
18797                            "snapshot_version": 1,
18798                            "max_attempts": 3,
18799                            "backoff_seconds": [2, 4],
18800                            "start_to_close_timeout": 30,
18801                            "schedule_to_start_timeout": 5,
18802                            "schedule_to_close_timeout": 90,
18803                            "heartbeat_timeout": 10,
18804                            "non_retryable_error_types": ["PermanentError"]
18805                        }
18806                    }
18807                }),
18808            ),
18809            history_event(
18810                "ActivityStarted",
18811                json!({
18812                    "sequence": 1,
18813                    "activity_type": "flaky",
18814                    "activity_execution_id": "act-1",
18815                    "activity_attempt_id": "attempt-1",
18816                    "attempt_number": 1
18817                }),
18818            ),
18819            history_event(
18820                "ActivityRetryScheduled",
18821                json!({
18822                    "sequence": 1,
18823                    "activity_type": "flaky",
18824                    "activity_execution_id": "act-1",
18825                    "activity_attempt_id": "attempt-1",
18826                    "attempt_number": 1,
18827                    "retry_after_attempt": 1,
18828                    "retry_backoff_seconds": 2,
18829                    "failure_category": "activity",
18830                    "exception_type": "TransientError"
18831                }),
18832            ),
18833            history_event(
18834                "ActivityStarted",
18835                json!({
18836                    "sequence": 1,
18837                    "activity_type": "flaky",
18838                    "activity_execution_id": "act-1",
18839                    "activity_attempt_id": "attempt-2",
18840                    "attempt_number": 2
18841                }),
18842            ),
18843            history_event(
18844                "ActivityCompleted",
18845                json!({
18846                    "sequence": 1,
18847                    "activity_type": "flaky",
18848                    "activity_execution_id": "act-1",
18849                    "activity_attempt_id": "attempt-2",
18850                    "attempt_number": 2,
18851                    "payload_codec": DEFAULT_CODEC,
18852                    "result": fixture_envelope(json!({"status":"recovered"}))
18853                }),
18854            ),
18855        ]
18856    }
18857
18858    fn retry_activity_options() -> ActivityOptions {
18859        ActivityOptions::new()
18860            .task_queue("critical-activities")
18861            .retry_policy(
18862                ActivityRetryPolicy::new(3)
18863                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
18864                    .non_retryable_error_type("PermanentError"),
18865            )
18866            .start_to_close_timeout(Duration::from_secs(30))
18867            .schedule_to_start_timeout(Duration::from_secs(5))
18868            .schedule_to_close_timeout(Duration::from_secs(90))
18869            .heartbeat_timeout(Duration::from_secs(10))
18870    }
18871
18872    #[test]
18873    fn fixed_avro_value_round_trips_json_values() {
18874        let value = json!({"greeting": "hello", "count": 3, "ok": true});
18875        let envelope = PayloadEnvelope::avro(&value).expect("encode");
18876        assert_eq!(envelope.codec, DEFAULT_CODEC);
18877        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
18878    }
18879
18880    #[tokio::test]
18881    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
18882        let client = Client::new("http://127.0.0.1:8080").expect("client");
18883        let mut worker = Worker::new(client, "rust-workers");
18884        worker.register_typed_workflow(
18885            "typed.contract.workflow",
18886            |_ctx, input: TypedContract| async move { Ok(input) },
18887        );
18888        worker.register_typed_activity(
18889            "typed.contract.activity",
18890            |_ctx, input: TypedContract| async move { Ok(input) },
18891        );
18892
18893        let expected = typed_contract();
18894        let arguments = AvroValue::Array(vec![
18895            AvroValue::from_serialize(&expected).expect("typed request")
18896        ]);
18897        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
18898        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
18899        workflow.arguments = Some(envelope.clone());
18900        let commands = worker
18901            .execute_workflow_task(workflow)
18902            .expect("typed workflow task");
18903        let workflow_result: TypedContract =
18904            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
18905                .expect("workflow result envelope")
18906                .deserialize()
18907                .expect("workflow result type");
18908        assert_eq!(workflow_result, expected);
18909
18910        let activity = ActivityTask {
18911            task_id: "typed-contract-activity".to_string(),
18912            activity_attempt_id: Some("typed-contract-attempt".to_string()),
18913            attempt_id: None,
18914            activity_type: "typed.contract.activity".to_string(),
18915            payload_codec: DEFAULT_CODEC.to_string(),
18916            arguments: Some(envelope),
18917            attempt_number: 1,
18918            lease_owner: Some("rust-worker".to_string()),
18919        };
18920        let activity_result: TypedContract = worker
18921            .execute_activity_task(activity)
18922            .await
18923            .expect("typed activity task")
18924            .deserialize()
18925            .expect("activity result type");
18926        assert_eq!(activity_result, expected);
18927    }
18928
18929    #[tokio::test]
18930    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
18931        let client = Client::new("http://127.0.0.1:8080").expect("client");
18932        let mut worker = Worker::new(client, "rust-workers");
18933        worker.register_typed_workflow(
18934            "typed.shape.workflow",
18935            |_ctx, input: TypedContract| async move { Ok(input) },
18936        );
18937        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
18938            Ok(f64::NAN)
18939        });
18940
18941        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
18942        workflow.arguments = Some(
18943            encode_typed_envelope(
18944                &AvroValue::Array(vec![
18945                    AvroValue::String("first".to_string()),
18946                    AvroValue::String("second".to_string()),
18947                ]),
18948                DEFAULT_CODEC,
18949            )
18950            .expect("malformed typed arguments"),
18951        );
18952        let commands = worker
18953            .execute_workflow_task(workflow)
18954            .expect("shape mismatch becomes a workflow failure");
18955        let message = commands[0]["message"].as_str().expect("failure message");
18956        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
18957        assert!(message.contains(type_name::<TypedContract>()));
18958        assert!(message.contains("task carried 2 arguments"));
18959
18960        let activity = ActivityTask {
18961            task_id: "typed-unsupported-activity".to_string(),
18962            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
18963            attempt_id: None,
18964            activity_type: "typed.unsupported.activity".to_string(),
18965            payload_codec: DEFAULT_CODEC.to_string(),
18966            arguments: Some(
18967                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
18968                    .expect("unit arguments"),
18969            ),
18970            attempt_number: 1,
18971            lease_owner: Some("rust-worker".to_string()),
18972        };
18973        let Error::HandlerType {
18974            handler_kind,
18975            handler_name,
18976            value_kind,
18977            rust_type,
18978            message,
18979        } = worker
18980            .execute_activity_task(activity)
18981            .await
18982            .expect_err("non-finite handler output must fail")
18983        else {
18984            panic!("expected contextual handler type failure");
18985        };
18986        assert_eq!(handler_kind, HandlerKind::Activity);
18987        assert_eq!(handler_name, "typed.unsupported.activity");
18988        assert_eq!(value_kind, HandlerValueKind::Result);
18989        assert_eq!(rust_type, type_name::<f64>());
18990        assert!(message.contains("non_finite_float"));
18991    }
18992
18993    #[tokio::test]
18994    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
18995        #[derive(Clone, Default)]
18996        struct State {
18997            observed: Option<TypedContract>,
18998        }
18999
19000        let client = Client::new("http://127.0.0.1:8080").expect("client");
19001        let mut worker = Worker::new(client, "rust-workers");
19002        worker.register_typed_replayed_workflow(
19003            "typed.contract.replayed",
19004            State::default,
19005            |ctx, input: TypedContract, state| async move {
19006                let result: TypedContract =
19007                    ctx.activity_typed("typed.contract.activity", input).await?;
19008                state.update(|current| current.observed = Some(result.clone()))?;
19009                Ok(result)
19010            },
19011        );
19012        worker.register_replayed_query::<State, _, _>(
19013            "typed.contract.replayed",
19014            "observed",
19015            |_ctx, state, _args| async move {
19016                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
19017            },
19018        );
19019
19020        let expected = typed_contract();
19021        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
19022        let workflow_arguments =
19023            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
19024                .expect("workflow arguments");
19025        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
19026        let task = QueryTask {
19027            query_task_id: "typed-replay-query".to_string(),
19028            query_task_attempt: 1,
19029            lease_owner: Some("rust-worker".to_string()),
19030            workflow_id: Some("typed-replay".to_string()),
19031            run_id: Some("typed-replay-run".to_string()),
19032            workflow_type: "typed.contract.replayed".to_string(),
19033            query_name: "observed".to_string(),
19034            payload_codec: DEFAULT_CODEC.to_string(),
19035            workflow_arguments: Some(workflow_arguments),
19036            query_arguments: Some(
19037                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19038                    .expect("query arguments"),
19039            ),
19040            history_events: vec![
19041                history_event(
19042                    "ActivityScheduled",
19043                    json!({
19044                        "sequence": 1,
19045                        "activity_type": "typed.contract.activity"
19046                    }),
19047                ),
19048                history_event(
19049                    "ActivityCompleted",
19050                    json!({
19051                        "sequence": 1,
19052                        "activity_type": "typed.contract.activity",
19053                        "payload_codec": DEFAULT_CODEC,
19054                        "result": result
19055                    }),
19056                ),
19057            ],
19058            history_export: None,
19059            run_status: Some("completed".to_string()),
19060        };
19061
19062        assert_eq!(
19063            worker
19064                .execute_query_task(task)
19065                .await
19066                .expect("typed replay query")
19067                .deserialize::<i64>()
19068                .expect("query result"),
19069            expected.signed
19070        );
19071    }
19072
19073    #[tokio::test]
19074    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
19075        let client = Client::new("http://127.0.0.1:8080").expect("client");
19076        let mut worker = Worker::new(client, "rust-workers");
19077        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
19078        worker
19079            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
19080        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
19081            Ok(input)
19082        });
19083        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
19084            Ok(input)
19085        });
19086        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
19087            Ok(AvroValue::Array(
19088                ctx.wait_signal_avro_value("changed").await?,
19089            ))
19090        });
19091
19092        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
19093        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
19094
19095        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
19096        workflow.arguments = Some(envelope.clone());
19097        let commands = worker
19098            .execute_workflow_task(workflow)
19099            .expect("typed workflow task");
19100        assert_eq!(commands[0]["type"], "complete_workflow");
19101        assert_eq!(
19102            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19103                .expect("typed workflow result"),
19104            arguments
19105        );
19106
19107        let activity = ActivityTask {
19108            task_id: "activity-typed".to_string(),
19109            activity_attempt_id: Some("attempt-typed".to_string()),
19110            attempt_id: None,
19111            activity_type: "typed.activity".to_string(),
19112            payload_codec: DEFAULT_CODEC.to_string(),
19113            arguments: Some(envelope.clone()),
19114            attempt_number: 1,
19115            lease_owner: Some("rust-worker".to_string()),
19116        };
19117        assert_eq!(
19118            worker
19119                .execute_activity_task(activity)
19120                .await
19121                .expect("typed activity result"),
19122            arguments
19123        );
19124
19125        let query = QueryTask {
19126            query_task_id: "query-typed".to_string(),
19127            query_task_attempt: 1,
19128            lease_owner: Some("rust-worker".to_string()),
19129            workflow_id: Some("typed-1".to_string()),
19130            run_id: Some("run-typed".to_string()),
19131            workflow_type: "typed.echo".to_string(),
19132            query_name: "inspect".to_string(),
19133            payload_codec: DEFAULT_CODEC.to_string(),
19134            workflow_arguments: Some(
19135                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19136                    .expect("workflow input"),
19137            ),
19138            query_arguments: Some(envelope.clone()),
19139            history_events: Vec::new(),
19140            history_export: None,
19141            run_status: Some("running".to_string()),
19142        };
19143        assert_eq!(
19144            worker
19145                .execute_query_task(query)
19146                .await
19147                .expect("typed query result"),
19148            arguments
19149        );
19150
19151        let mut update = workflow_task(
19152            "typed.echo",
19153            vec![history_event(
19154                "UpdateAccepted",
19155                json!({
19156                    "update_id": "update-typed",
19157                    "update_name": "replace",
19158                    "arguments": envelope.clone(),
19159                }),
19160            )],
19161            DEFAULT_CODEC,
19162        );
19163        update.workflow_update_id = Some("update-typed".to_string());
19164        update.update_name = Some("replace".to_string());
19165        let commands = worker
19166            .execute_workflow_task(update)
19167            .expect("typed update task");
19168        assert_eq!(commands[0]["type"], "complete_update");
19169        assert_eq!(
19170            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19171                .expect("typed update result"),
19172            arguments
19173        );
19174
19175        let mut signal = workflow_task(
19176            "typed.signal",
19177            vec![history_event(
19178                "SignalReceived",
19179                json!({
19180                    "signal_id": "signal-typed",
19181                    "signal_name": "changed",
19182                    "arguments": envelope.clone(),
19183                }),
19184            )],
19185            DEFAULT_CODEC,
19186        );
19187        signal.workflow_signal_id = Some("signal-typed".to_string());
19188        signal.signal_name = Some("changed".to_string());
19189        signal.signal_arguments = Some(envelope);
19190        let commands = worker
19191            .execute_workflow_task(signal)
19192            .expect("typed signal resume");
19193        assert_eq!(
19194            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19195                .expect("typed signal result"),
19196            arguments
19197        );
19198    }
19199
19200    #[tokio::test]
19201    async fn typed_helpers_never_parse_json_inspection_projection() {
19202        let collision_values = projection_collision_probe();
19203        let expected = AvroValue::Array(collision_values.clone());
19204        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
19205
19206        let activity_context = workflow_context_with_codec(
19207            vec![history_event(
19208                "ActivityCompleted",
19209                json!({
19210                    "sequence": 1,
19211                    "activity_type": "collision.activity",
19212                    "payload_codec": DEFAULT_CODEC,
19213                    "result": envelope.clone(),
19214                }),
19215            )],
19216            DEFAULT_CODEC,
19217        );
19218        assert_eq!(
19219            activity_context
19220                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
19221                .await
19222                .expect("typed activity collision result"),
19223            expected
19224        );
19225
19226        let signal_context = workflow_context_with_codec(
19227            vec![
19228                history_event(
19229                    "SignalWaitOpened",
19230                    json!({"sequence": 1, "signal_name": "collision"}),
19231                ),
19232                history_event(
19233                    "SignalApplied",
19234                    json!({
19235                        "sequence": 1,
19236                        "signal_name": "collision",
19237                        "payload_codec": DEFAULT_CODEC,
19238                        "value": envelope.clone(),
19239                    }),
19240                ),
19241            ],
19242            DEFAULT_CODEC,
19243        );
19244        assert_eq!(
19245            signal_context
19246                .wait_signal_avro_value("collision")
19247                .await
19248                .expect("typed signal collision arguments"),
19249            collision_values
19250        );
19251
19252        let child_context = workflow_context_with_codec(
19253            vec![
19254                history_event(
19255                    "ChildWorkflowScheduled",
19256                    json!({
19257                        "sequence": 1,
19258                        "child_workflow_instance_id": "collision-child",
19259                        "child_workflow_run_id": "collision-run",
19260                        "child_workflow_type": "collision.child",
19261                    }),
19262                ),
19263                history_event(
19264                    "ChildRunCompleted",
19265                    json!({
19266                        "sequence": 1,
19267                        "child_workflow_instance_id": "collision-child",
19268                        "child_workflow_run_id": "collision-run",
19269                        "child_workflow_type": "collision.child",
19270                        "payload_codec": DEFAULT_CODEC,
19271                        "result": envelope,
19272                    }),
19273                ),
19274            ],
19275            DEFAULT_CODEC,
19276        );
19277        let child = child_context
19278            .start_child_workflow_avro_value(
19279                "collision.child",
19280                ChildWorkflowOptions::new("collision-workers"),
19281                AvroValue::Array(Vec::new()),
19282            )
19283            .await
19284            .expect("typed child collision result");
19285        assert_eq!(child.result, expected);
19286    }
19287
19288    #[tokio::test]
19289    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
19290        let client = Client::new("http://127.0.0.1:8080").expect("client");
19291        let mut worker = Worker::new(client, "rust-workers");
19292        worker.register_replayed_workflow_avro_value(
19293            "typed.replayed",
19294            || (),
19295            |_ctx, input, _state| async move { Ok(input) },
19296        );
19297        worker.register_replayed_query_avro_value::<(), _, _>(
19298            "typed.replayed",
19299            "inspect",
19300            |ctx, _state, args| async move {
19301                let mut signals = ctx.signals_avro_value("collision");
19302                let signal = signals
19303                    .pop()
19304                    .map(AvroValue::Array)
19305                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
19306                Ok(AvroValue::Array(vec![
19307                    ctx.workflow_input_avro_value().clone(),
19308                    signal,
19309                    args,
19310                ]))
19311            },
19312        );
19313        let arguments = AvroValue::Array(projection_collision_probe());
19314        let signal_arguments =
19315            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
19316        let task = QueryTask {
19317            query_task_id: "query-typed-replay".to_string(),
19318            query_task_attempt: 1,
19319            lease_owner: Some("rust-worker".to_string()),
19320            workflow_id: Some("typed-replay".to_string()),
19321            run_id: Some("run-typed-replay".to_string()),
19322            workflow_type: "typed.replayed".to_string(),
19323            query_name: "inspect".to_string(),
19324            payload_codec: DEFAULT_CODEC.to_string(),
19325            workflow_arguments: Some(
19326                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
19327            ),
19328            query_arguments: Some(
19329                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
19330            ),
19331            history_events: vec![history_event(
19332                "SignalReceived",
19333                json!({
19334                    "signal_id": "collision-signal",
19335                    "signal_name": "collision",
19336                    "workflow_sequence": 1,
19337                    "payload_codec": DEFAULT_CODEC,
19338                    "arguments": signal_arguments,
19339                }),
19340            )],
19341            history_export: None,
19342            run_status: Some("completed".to_string()),
19343        };
19344
19345        assert_eq!(
19346            worker
19347                .execute_query_task(task)
19348                .await
19349                .expect("typed replay query"),
19350            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
19351        );
19352    }
19353
19354    #[test]
19355    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
19356        let value = BTreeMap::from([(1_i32, "integer key")]);
19357        let error = PayloadEnvelope::avro(&value)
19358            .expect_err("integer map keys must fail")
19359            .to_string();
19360
19361        assert!(error.contains("invalid_map_key"));
19362    }
19363
19364    #[test]
19365    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
19366        let envelope = PayloadEnvelope {
19367            codec: "json".to_string(),
19368            blob: r#"{"greeting":"hello"}"#.to_string(),
19369        };
19370
19371        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
19372        let diagnostic = error.to_string();
19373        assert!(diagnostic.contains("unsupported_payload_codec"));
19374        assert!(diagnostic.contains("codec=\"avro\""));
19375        assert!(diagnostic.contains("HTTP document transport"));
19376    }
19377
19378    #[test]
19379    fn untagged_json_payload_value_fails_closed() {
19380        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
19381            .expect_err("untagged JSON payload values must fail");
19382        let diagnostic = error.to_string();
19383        assert!(diagnostic.contains("unsupported_payload_codec"));
19384        assert!(diagnostic.contains("untagged durable payload"));
19385        assert!(diagnostic.contains("HTTP document transport"));
19386    }
19387
19388    #[test]
19389    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
19390        let envelope = PayloadEnvelope {
19391            codec: DEFAULT_CODEC.to_string(),
19392            blob: BASE64.encode([0x01]),
19393        };
19394
19395        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
19396        assert!(error.to_string().contains("invalid_payload_framing"));
19397    }
19398
19399    #[tokio::test]
19400    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
19401        let server = MockWorkerServer::start();
19402        let client = Client::builder(server.base_url())
19403            .timeout(Duration::from_secs(2))
19404            .build()
19405            .expect("client");
19406        let invalid_commands = [
19407            json!({
19408                "type": "complete_workflow",
19409                "result": {"codec": "json", "blob": null}
19410            }),
19411            json!({
19412                "type": "schedule_activity",
19413                "arguments": {"codec": "yaml", "blob": "ignored"}
19414            }),
19415            json!({
19416                "type": "start_child_workflow",
19417                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
19418            }),
19419            json!({"type": "continue_as_new", "arguments": []}),
19420            json!({"type": "complete_update"}),
19421            json!({"type": "record_side_effect", "result": null}),
19422            json!({
19423                "type": "start_service_operation",
19424                "payload_codec": DEFAULT_CODEC,
19425                "request_payload": "raw-avro-bytes"
19426            }),
19427        ];
19428
19429        for command in invalid_commands {
19430            let error = client
19431                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
19432                .await
19433                .expect_err("invalid durable payload must fail locally");
19434            let diagnostic = error.to_string();
19435            assert!(
19436                diagnostic.contains("unsupported_payload_codec")
19437                    || diagnostic.contains("invalid_payload_envelope")
19438                    || diagnostic.contains("untagged durable payload"),
19439                "unexpected validation diagnostic: {diagnostic}"
19440            );
19441        }
19442
19443        assert_eq!(
19444            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
19445            0,
19446            "invalid command payloads must not reach HTTP transport"
19447        );
19448    }
19449
19450    #[test]
19451    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
19452        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
19453        let commands = [
19454            json!({"type": "complete_workflow", "result": envelope.clone()}),
19455            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
19456            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
19457            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
19458            json!({"type": "complete_update", "result": envelope.clone()}),
19459            json!({"type": "record_side_effect", "result": envelope.clone()}),
19460            json!({
19461                "type": "start_service_operation",
19462                "payload_codec": DEFAULT_CODEC,
19463                "request_payload": envelope.clone()
19464            }),
19465            json!({
19466                "type": "complete_workflow",
19467                "result": envelope,
19468                "metadata": {
19469                    "codec": "json",
19470                    "payload_codec": "customer-codec",
19471                    "result": {"codec": "yaml", "blob": null}
19472                }
19473            }),
19474        ];
19475
19476        validate_workflow_task_commands(&commands)
19477            .expect("customer metadata must not become a protocol codec declaration");
19478    }
19479
19480    #[test]
19481    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
19482        assert_eq!(
19483            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
19484            AvroValue::Array(Vec::new())
19485        );
19486        assert_eq!(
19487            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
19488            AvroValue::Array(Vec::new())
19489        );
19490
19491        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
19492        signal.signal_name = Some("empty-signal".to_string());
19493        signal.signal_arguments = None;
19494        let decoded = decode_resume_signal(&signal)
19495            .expect("valid Avro signal")
19496            .expect("named signal resumes the workflow");
19497        assert!(decoded.arguments.is_empty());
19498    }
19499
19500    #[tokio::test]
19501    async fn malformed_task_level_codecs_become_pre_handler_failures() {
19502        let client = Client::new("http://127.0.0.1:8080").expect("client");
19503        let mut worker = Worker::new(client, "rust-workers");
19504        let handler_calls = Arc::new(AtomicUsize::new(0));
19505
19506        let calls = Arc::clone(&handler_calls);
19507        worker.register_workflow("codec.workflow", move |_ctx, _args| {
19508            calls.fetch_add(1, Ordering::SeqCst);
19509            async move { Ok(Value::Null) }
19510        });
19511        let calls = Arc::clone(&handler_calls);
19512        worker.register_activity("codec.activity", move |_ctx, _args| {
19513            calls.fetch_add(1, Ordering::SeqCst);
19514            async move { Ok(Value::Null) }
19515        });
19516        let calls = Arc::clone(&handler_calls);
19517        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
19518            calls.fetch_add(1, Ordering::SeqCst);
19519            async move { Ok(Value::Null) }
19520        });
19521
19522        let mut failures = Vec::new();
19523        for codec_case in [
19524            InvalidTaskPayloadCodec::Missing,
19525            InvalidTaskPayloadCodec::Null,
19526            InvalidTaskPayloadCodec::NonString,
19527        ] {
19528            let mut workflow = json!({
19529                "task_id": format!("workflow-{}", codec_case.label()),
19530                "workflow_type": "codec.workflow"
19531            });
19532            codec_case.apply(&mut workflow);
19533            match serde_json::from_value::<WorkflowTask>(workflow) {
19534                Ok(task) => match worker.execute_workflow_task(task) {
19535                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
19536                    outcome => failures.push(format!(
19537                        "workflow {} codec returned {outcome:?}",
19538                        codec_case.label()
19539                    )),
19540                },
19541                Err(error) => failures.push(format!(
19542                    "workflow {} codec failed transport deserialization: {error}",
19543                    codec_case.label()
19544                )),
19545            }
19546
19547            let mut activity = json!({
19548                "task_id": format!("activity-{}", codec_case.label()),
19549                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
19550                "activity_type": "codec.activity",
19551                "attempt_number": 1
19552            });
19553            codec_case.apply(&mut activity);
19554            match serde_json::from_value::<ActivityTask>(activity) {
19555                Ok(task) => match worker.execute_activity_task(task).await {
19556                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
19557                    outcome => failures.push(format!(
19558                        "activity {} codec returned {outcome:?}",
19559                        codec_case.label()
19560                    )),
19561                },
19562                Err(error) => failures.push(format!(
19563                    "activity {} codec failed transport deserialization: {error}",
19564                    codec_case.label()
19565                )),
19566            }
19567
19568            let mut query = json!({
19569                "query_task_id": format!("query-{}", codec_case.label()),
19570                "workflow_type": "codec.workflow",
19571                "query_name": "known"
19572            });
19573            codec_case.apply(&mut query);
19574            match serde_json::from_value::<QueryTask>(query) {
19575                Ok(task) => match worker.execute_query_task(task).await {
19576                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
19577                    outcome => failures.push(format!(
19578                        "query {} codec returned {outcome:?}",
19579                        codec_case.label()
19580                    )),
19581                },
19582                Err(error) => failures.push(format!(
19583                    "query {} codec failed transport deserialization: {error}",
19584                    codec_case.label()
19585                )),
19586            }
19587        }
19588
19589        assert!(failures.is_empty(), "{}", failures.join("\n"));
19590        assert_eq!(
19591            handler_calls.load(Ordering::SeqCst),
19592            0,
19593            "invalid task codecs must not invoke a handler"
19594        );
19595    }
19596
19597    #[tokio::test]
19598    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
19599        for codec_case in [
19600            InvalidTaskPayloadCodec::Missing,
19601            InvalidTaskPayloadCodec::Null,
19602            InvalidTaskPayloadCodec::NonString,
19603        ] {
19604            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
19605            let client = Client::builder(server.base_url())
19606                .timeout(Duration::from_secs(2))
19607                .build()
19608                .expect("client");
19609            let mut worker = Worker::new(client, "rust-workers")
19610                .worker_id("codec-worker")
19611                .poll_timeout(Duration::from_millis(10));
19612            let handler_calls = Arc::new(AtomicUsize::new(0));
19613
19614            let calls = Arc::clone(&handler_calls);
19615            worker.register_workflow("codec.workflow", move |_ctx, _args| {
19616                calls.fetch_add(1, Ordering::SeqCst);
19617                async move { Ok(Value::Null) }
19618            });
19619            let calls = Arc::clone(&handler_calls);
19620            worker.register_activity("codec.activity", move |_ctx, _args| {
19621                calls.fetch_add(1, Ordering::SeqCst);
19622                async move { Ok(Value::Null) }
19623            });
19624            let calls = Arc::clone(&handler_calls);
19625            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
19626                calls.fetch_add(1, Ordering::SeqCst);
19627                async move { Ok(Value::Null) }
19628            });
19629
19630            assert_eq!(
19631                worker.run_once().await.expect("invalid tasks are settled"),
19632                3,
19633                "all {} codec tasks must be handled",
19634                codec_case.label()
19635            );
19636            assert_eq!(
19637                handler_calls.load(Ordering::SeqCst),
19638                0,
19639                "{} task codecs must fail before every handler",
19640                codec_case.label()
19641            );
19642
19643            for path in [
19644                "/api/worker/workflow-tasks/codec-workflow/fail",
19645                "/api/worker/activity-tasks/codec-activity/fail",
19646                "/api/worker/query-tasks/codec-query/fail",
19647            ] {
19648                let body = server.request_body(path);
19649                assert!(
19650                    body["failure"]["message"]
19651                        .as_str()
19652                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
19653                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
19654                    codec_case.label()
19655                );
19656            }
19657            assert_eq!(
19658                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
19659                    ["reason"],
19660                "query_payload_decode_failed"
19661            );
19662            for path in [
19663                "/api/worker/workflow-tasks/codec-workflow/complete",
19664                "/api/worker/activity-tasks/codec-activity/complete",
19665                "/api/worker/query-tasks/codec-query/complete",
19666            ] {
19667                assert_eq!(
19668                    server.request_count(path),
19669                    0,
19670                    "invalid {} codec task reached {path}",
19671                    codec_case.label()
19672                );
19673            }
19674        }
19675    }
19676
19677    #[tokio::test]
19678    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
19679        let client = Client::new("http://127.0.0.1:8080").expect("client");
19680        let mut worker = Worker::new(client, "rust-workers");
19681        let handler_calls = Arc::new(AtomicUsize::new(0));
19682
19683        let calls = Arc::clone(&handler_calls);
19684        worker.register_workflow("codec.workflow", move |_ctx, _args| {
19685            calls.fetch_add(1, Ordering::SeqCst);
19686            async move { Ok(Value::Null) }
19687        });
19688        let calls = Arc::clone(&handler_calls);
19689        worker.register_activity("codec.activity", move |_ctx, _args| {
19690            calls.fetch_add(1, Ordering::SeqCst);
19691            async move { Ok(Value::Null) }
19692        });
19693        let calls = Arc::clone(&handler_calls);
19694        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
19695            calls.fetch_add(1, Ordering::SeqCst);
19696            async move { Ok(Value::Null) }
19697        });
19698        let calls = Arc::clone(&handler_calls);
19699        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
19700            calls.fetch_add(1, Ordering::SeqCst);
19701            async move { Ok(Value::Null) }
19702        });
19703
19704        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
19705        workflow.payload_codec = "json".to_string();
19706        workflow.arguments = None;
19707        let error = worker
19708            .execute_workflow_task(workflow)
19709            .expect_err("task codec must be checked before workflow invocation");
19710        assert!(error.to_string().contains("unsupported_payload_codec"));
19711
19712        let activity = ActivityTask {
19713            task_id: "activity-invalid-codec".to_string(),
19714            activity_attempt_id: None,
19715            attempt_id: None,
19716            activity_type: "codec.activity".to_string(),
19717            payload_codec: "unknown".to_string(),
19718            arguments: None,
19719            attempt_number: 1,
19720            lease_owner: None,
19721        };
19722        let error = worker
19723            .execute_activity_task(activity)
19724            .await
19725            .expect_err("task codec must be checked before activity invocation");
19726        assert!(error.to_string().contains("unsupported_payload_codec"));
19727
19728        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
19729        update.workflow_update_id = Some("update-invalid-codec".to_string());
19730        update.update_name = Some("known".to_string());
19731        update.history_events.push(history_event(
19732            "UpdateAccepted",
19733            json!({
19734                "update_id": "update-invalid-codec",
19735                "update_name": "known",
19736                "arguments": {"codec": "json", "blob": null}
19737            }),
19738        ));
19739        let error = worker
19740            .execute_workflow_task(update)
19741            .expect_err("nested update codec must be checked before handler lookup");
19742        assert!(error.to_string().contains("unsupported_payload_codec"));
19743
19744        let query: QueryTask = serde_json::from_value(json!({
19745            "query_task_id": "query-invalid-codec",
19746            "workflow_type": "codec.workflow",
19747            "query_name": "known",
19748            "payload_codec": DEFAULT_CODEC,
19749            "workflow_arguments": null,
19750            "query_arguments": null,
19751            "history_export": {
19752                "payloads": {"codec": DEFAULT_CODEC},
19753                "signals": [{
19754                    "name": "empty",
19755                    "payload_codec": "json",
19756                    "arguments": null
19757                }]
19758            }
19759        }))
19760        .expect("query task");
19761        let failure = worker
19762            .execute_query_task(query)
19763            .await
19764            .expect_err("exported signal codec must be checked before query invocation");
19765        assert_eq!(failure.reason, "query_payload_decode_failed");
19766        assert!(failure.message.contains("unsupported_payload_codec"));
19767
19768        let exported_history: QueryTask = serde_json::from_value(json!({
19769            "query_task_id": "query-invalid-history-codec",
19770            "workflow_type": "codec.workflow",
19771            "query_name": "known",
19772            "payload_codec": DEFAULT_CODEC,
19773            "history_export": {
19774                "payloads": {"codec": DEFAULT_CODEC},
19775                "history_events": [{
19776                    "type": "ActivityCompleted",
19777                    "payload": {"payload_codec": "unknown", "result": null}
19778                }]
19779            }
19780        }))
19781        .expect("query task");
19782        let failure = worker
19783            .execute_query_task(exported_history)
19784            .await
19785            .expect_err("exported history codec must be checked before query invocation");
19786        assert_eq!(failure.reason, "query_payload_decode_failed");
19787        assert!(failure.message.contains("unsupported_payload_codec"));
19788        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
19789
19790        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
19791        unknown_workflow.arguments = None;
19792        unknown_workflow.history_events.push(history_event(
19793            "SignalReceived",
19794            json!({
19795                "signal_name": "empty",
19796                "payload_codec": "json",
19797                "arguments": null
19798            }),
19799        ));
19800        let error = worker
19801            .execute_workflow_task(unknown_workflow)
19802            .expect_err("history codec must precede unknown workflow outcome");
19803        assert!(error.to_string().contains("unsupported_payload_codec"));
19804
19805        let unknown_activity = ActivityTask {
19806            task_id: "activity-unknown".to_string(),
19807            activity_attempt_id: None,
19808            attempt_id: None,
19809            activity_type: "missing".to_string(),
19810            payload_codec: "json".to_string(),
19811            arguments: None,
19812            attempt_number: 1,
19813            lease_owner: None,
19814        };
19815        let error = worker
19816            .execute_activity_task(unknown_activity)
19817            .await
19818            .expect_err("codec must precede unknown activity outcome");
19819        assert!(error.to_string().contains("unsupported_payload_codec"));
19820
19821        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
19822        unknown_update.payload_codec = "json".to_string();
19823        unknown_update.arguments = None;
19824        unknown_update.workflow_update_id = Some("update-unknown".to_string());
19825        unknown_update.update_name = Some("missing".to_string());
19826        let error = worker
19827            .execute_workflow_task(unknown_update)
19828            .expect_err("codec must precede fail_update shortcut");
19829        assert!(error.to_string().contains("unsupported_payload_codec"));
19830
19831        let unknown_query: QueryTask = serde_json::from_value(json!({
19832            "query_task_id": "query-unknown",
19833            "workflow_type": "missing",
19834            "query_name": "missing",
19835            "payload_codec": "json",
19836            "workflow_arguments": null,
19837            "query_arguments": null
19838        }))
19839        .expect("query task");
19840        let failure = worker
19841            .execute_query_task(unknown_query)
19842            .await
19843            .expect_err("codec must precede unknown query outcome");
19844        assert_eq!(failure.reason, "query_payload_decode_failed");
19845        assert!(failure.message.contains("unsupported_payload_codec"));
19846    }
19847
19848    #[tokio::test]
19849    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
19850        let client = Client::new("http://127.0.0.1:8080").expect("client");
19851        let worker = Worker::new(client, "rust-workers");
19852
19853        for event_type in ["SignalReceived", "SignalApplied"] {
19854            for (payload_field, codec) in [
19855                ("value", "json"),
19856                ("input", "unknown"),
19857                ("arguments", "json"),
19858            ] {
19859                let payload = json!({
19860                    "signal_name": "empty",
19861                    payload_field: {"codec": codec, "blob": null}
19862                });
19863                let workflow = workflow_task(
19864                    "missing",
19865                    vec![history_event(event_type, payload.clone())],
19866                    DEFAULT_CODEC,
19867                );
19868                let error = worker
19869                    .execute_workflow_task(workflow)
19870                    .expect_err("signal payload codec must precede unknown workflow outcome");
19871                assert!(
19872                    error.to_string().contains("unsupported_payload_codec"),
19873                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
19874                );
19875
19876                let query: QueryTask = serde_json::from_value(json!({
19877                    "query_task_id": format!("query-{event_type}-{payload_field}"),
19878                    "workflow_type": "missing",
19879                    "query_name": "missing",
19880                    "payload_codec": DEFAULT_CODEC,
19881                    "workflow_arguments": null,
19882                    "query_arguments": null,
19883                    "history_events": [{
19884                        "event_type": event_type,
19885                        "payload": payload
19886                    }]
19887                }))
19888                .expect("query task");
19889                let failure = worker
19890                    .execute_query_task(query)
19891                    .await
19892                    .expect_err("signal payload codec must precede unknown query outcome");
19893                assert_eq!(
19894                    failure.reason, "query_payload_decode_failed",
19895                    "{event_type}.{payload_field} returned an unrelated query outcome"
19896                );
19897                assert!(
19898                    failure.message.contains("unsupported_payload_codec"),
19899                    "{event_type}.{payload_field} returned an unrelated query error: {}",
19900                    failure.message
19901                );
19902            }
19903        }
19904    }
19905
19906    #[test]
19907    fn workflow_context_schedules_activity_until_completion_is_in_history() {
19908        let ctx = WorkflowContext {
19909            cancellation_scope_id: "root".into(),
19910            state: Arc::new(Mutex::new(
19911                WorkflowState::new_with_identity(
19912                    Vec::new(),
19913                    Some("wf-parent".to_string()),
19914                    Some("run-parent".to_string()),
19915                    "rust-workers".to_string(),
19916                    DEFAULT_CODEC.to_string(),
19917                    None,
19918                )
19919                .expect("workflow state"),
19920            )),
19921        };
19922
19923        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
19924        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19925        assert!(matches!(
19926            call.as_mut().poll(&mut task_context),
19927            Poll::Pending
19928        ));
19929
19930        let commands = ctx.take_commands().expect("commands");
19931        assert_eq!(commands[0]["type"], "schedule_activity");
19932        assert_eq!(commands[0]["activity_type"], "hello.activity");
19933    }
19934
19935    #[test]
19936    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
19937        let ctx = workflow_context(Vec::new());
19938        let options = ActivityOptions::new()
19939            .task_queue("payments")
19940            .retry_policy(
19941                ActivityRetryPolicy::new(4)
19942                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
19943                    .non_retryable_error_type("ValidationError"),
19944            )
19945            .start_to_close_timeout(Duration::from_secs(120))
19946            .schedule_to_start_timeout(Duration::from_secs(10))
19947            .schedule_to_close_timeout(Duration::from_secs(300))
19948            .heartbeat_timeout(Duration::from_secs(15));
19949        let mut call = Box::pin(ctx.activity_with_options(
19950            "charge-card",
19951            options,
19952            json!([{"order_id": "o-1"}]),
19953        ));
19954        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19955
19956        assert!(matches!(
19957            call.as_mut().poll(&mut task_context),
19958            Poll::Pending
19959        ));
19960        assert!(matches!(
19961            call.as_mut().poll(&mut task_context),
19962            Poll::Pending
19963        ));
19964
19965        let commands = ctx.take_commands().expect("activity command");
19966        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
19967        assert_eq!(commands[0]["queue"], "payments");
19968        assert_eq!(
19969            commands[0]["retry_policy"],
19970            json!({
19971                "max_attempts": 4,
19972                "backoff_seconds": [1, 3, 9],
19973                "non_retryable_error_types": ["ValidationError"],
19974            })
19975        );
19976        assert_eq!(commands[0]["start_to_close_timeout"], 120);
19977        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
19978        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
19979        assert_eq!(commands[0]["heartbeat_timeout"], 15);
19980    }
19981
19982    #[test]
19983    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
19984        let ctx = workflow_context(Vec::new());
19985        let options = ActivityOptions::new().retry_policy(
19986            ActivityRetryPolicy::new(3)
19987                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
19988        );
19989        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
19990        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19991
19992        assert!(matches!(
19993            call.as_mut().poll(&mut task_context),
19994            Poll::Pending
19995        ));
19996        assert_eq!(
19997            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
19998            json!([1, 2])
19999        );
20000    }
20001
20002    #[test]
20003    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
20004        let cases = [
20005            (
20006                ActivityOptions::new().task_queue("  "),
20007                ActivityOptionsErrorKind::EmptyTaskQueue,
20008            ),
20009            (
20010                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
20011                ActivityOptionsErrorKind::EmptyRetryPolicy,
20012            ),
20013            (
20014                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
20015                ActivityOptionsErrorKind::InvalidMaxAttempts,
20016            ),
20017            (
20018                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
20019                    max_attempts: None,
20020                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
20021                    non_retryable_error_types: Vec::new(),
20022                }),
20023                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
20024            ),
20025            (
20026                ActivityOptions::new().retry_policy(
20027                    ActivityRetryPolicy::new(2)
20028                        .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
20029                ),
20030                ActivityOptionsErrorKind::TooManyBackoffIntervals,
20031            ),
20032            (
20033                ActivityOptions::new().retry_policy(
20034                    ActivityRetryPolicy::new(2).exponential_backoff(
20035                        Duration::from_secs(1),
20036                        0,
20037                        None,
20038                    ),
20039                ),
20040                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
20041            ),
20042            (
20043                ActivityOptions::new()
20044                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
20045                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
20046            ),
20047            (
20048                ActivityOptions::new().retry_policy(
20049                    ActivityRetryPolicy::new(10_002).exponential_backoff(
20050                        Duration::from_secs(1),
20051                        1,
20052                        None,
20053                    ),
20054                ),
20055                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
20056            ),
20057            (
20058                ActivityOptions::new().retry_policy(
20059                    ActivityRetryPolicy::new(2)
20060                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
20061                ),
20062                ActivityOptionsErrorKind::BackoffOverflow,
20063            ),
20064        ];
20065
20066        for (options, expected_kind) in cases {
20067            let ctx = workflow_context(Vec::new());
20068            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
20069            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20070            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
20071                call.as_mut().poll(&mut task_context)
20072            else {
20073                panic!("expected typed activity validation error");
20074            };
20075            assert_eq!(error.kind, expected_kind);
20076            assert!(ctx.take_commands().expect("commands").is_empty());
20077        }
20078    }
20079
20080    #[test]
20081    fn activity_options_validate_positive_and_ordered_timeouts() {
20082        let zero_timeout_cases = [
20083            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
20084            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
20085            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
20086            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
20087        ];
20088        for options in zero_timeout_cases {
20089            assert_eq!(
20090                options.validate().expect_err("zero timeout").kind,
20091                ActivityOptionsErrorKind::TimeoutNotPositive
20092            );
20093        }
20094
20095        let ordering_cases = [
20096            ActivityOptions::new()
20097                .heartbeat_timeout(Duration::from_secs(11))
20098                .start_to_close_timeout(Duration::from_secs(10)),
20099            ActivityOptions::new()
20100                .start_to_close_timeout(Duration::from_secs(31))
20101                .schedule_to_close_timeout(Duration::from_secs(30)),
20102            ActivityOptions::new()
20103                .schedule_to_start_timeout(Duration::from_secs(31))
20104                .schedule_to_close_timeout(Duration::from_secs(30)),
20105        ];
20106        for options in ordering_cases {
20107            assert_eq!(
20108                options.validate().expect_err("timeout order").kind,
20109                ActivityOptionsErrorKind::TimeoutOrder
20110            );
20111        }
20112
20113        assert_eq!(
20114            ActivityOptions::new()
20115                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
20116                .validate()
20117                .expect_err("protocol integer overflow")
20118                .kind,
20119            ActivityOptionsErrorKind::TimeoutOverflow
20120        );
20121    }
20122
20123    #[test]
20124    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
20125        let ctx = workflow_context(completed_retry_activity_history());
20126        let mut call =
20127            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20128        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20129
20130        assert!(matches!(
20131            call.as_mut().poll(&mut task_context),
20132            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20133        ));
20134        assert!(ctx.take_commands().expect("commands").is_empty());
20135        ctx.ensure_history_consumed().expect("history consumed");
20136    }
20137
20138    #[test]
20139    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
20140        let mut options = retry_activity_options();
20141        options
20142            .retry_policy
20143            .as_mut()
20144            .expect("retry policy")
20145            .non_retryable_error_types
20146            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
20147
20148        let new_ctx = workflow_context(Vec::new());
20149        let mut new_call =
20150            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
20151        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20152        assert!(matches!(
20153            new_call.as_mut().poll(&mut task_context),
20154            Poll::Pending
20155        ));
20156        let commands = new_ctx.take_commands().expect("commands");
20157        assert_eq!(commands.len(), 1);
20158        assert_eq!(
20159            commands[0]["retry_policy"]["non_retryable_error_types"],
20160            json!(["PermanentError"])
20161        );
20162
20163        let replay_ctx = workflow_context(completed_retry_activity_history());
20164        let mut replay_call =
20165            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
20166        assert!(matches!(
20167            replay_call.as_mut().poll(&mut task_context),
20168            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20169        ));
20170        assert!(replay_ctx.take_commands().expect("commands").is_empty());
20171        replay_ctx
20172            .ensure_history_consumed()
20173            .expect("history consumed");
20174    }
20175
20176    #[test]
20177    fn replayed_intermediate_retry_remains_pending_across_restarts() {
20178        let history = completed_retry_activity_history()
20179            .into_iter()
20180            .take(3)
20181            .collect::<Vec<_>>();
20182
20183        for _restart in 0..2 {
20184            let ctx = workflow_context(history.clone());
20185            let mut call =
20186                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20187            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20188            assert!(matches!(
20189                call.as_mut().poll(&mut task_context),
20190                Poll::Pending
20191            ));
20192            assert!(ctx.take_commands().expect("commands").is_empty());
20193        }
20194    }
20195
20196    #[test]
20197    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
20198        let mut changed_queue = retry_activity_options();
20199        changed_queue.task_queue = Some("different-queue".to_string());
20200
20201        let mut changed_max_attempts = retry_activity_options();
20202        let retry_policy = changed_max_attempts
20203            .retry_policy
20204            .as_mut()
20205            .expect("retry policy");
20206        retry_policy.max_attempts = Some(4);
20207
20208        let mut changed_backoff = retry_activity_options();
20209        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
20210        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
20211            Duration::from_secs(3),
20212            Duration::from_secs(4),
20213        ]));
20214
20215        let mut changed_non_retryable_types = retry_activity_options();
20216        let retry_policy = changed_non_retryable_types
20217            .retry_policy
20218            .as_mut()
20219            .expect("retry policy");
20220        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
20221
20222        let mut changed_start_to_close = retry_activity_options();
20223        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
20224        let mut changed_schedule_to_start = retry_activity_options();
20225        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
20226        let mut changed_schedule_to_close = retry_activity_options();
20227        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
20228        let mut changed_heartbeat = retry_activity_options();
20229        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
20230
20231        let cases = [
20232            (changed_queue, "activity_task_queue_mismatch"),
20233            (changed_max_attempts, "activity_retry_policy_mismatch"),
20234            (changed_backoff, "activity_retry_policy_mismatch"),
20235            (
20236                changed_non_retryable_types,
20237                "activity_retry_policy_mismatch",
20238            ),
20239            (changed_start_to_close, "activity_retry_policy_mismatch"),
20240            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
20241            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
20242            (changed_heartbeat, "activity_retry_policy_mismatch"),
20243        ];
20244
20245        for (options, expected_reason) in cases {
20246            let ctx = workflow_context(completed_retry_activity_history());
20247            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
20248            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20249            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20250                call.as_mut().poll(&mut task_context)
20251            else {
20252                panic!("changed activity options must fail replay");
20253            };
20254            assert_eq!(failure.reason, expected_reason);
20255            assert_eq!(failure.sequence, Some(1));
20256            assert!(ctx.take_commands().expect("commands").is_empty());
20257        }
20258    }
20259
20260    #[test]
20261    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
20262        let cases = [
20263            (
20264                "execution_mode",
20265                json!("local"),
20266                "activity_execution_mode_mismatch",
20267            ),
20268            (
20269                "snapshot_version",
20270                json!(2),
20271                "activity_retry_policy_mismatch",
20272            ),
20273        ];
20274
20275        for (field, value, expected_reason) in cases {
20276            let mut history = completed_retry_activity_history();
20277            let activity = history[0].payload["activity"]
20278                .as_object_mut()
20279                .expect("activity snapshot");
20280            if field == "execution_mode" {
20281                activity.insert(field.to_string(), value);
20282            } else {
20283                activity["retry_policy"]
20284                    .as_object_mut()
20285                    .expect("retry snapshot")
20286                    .insert(field.to_string(), value);
20287            }
20288
20289            let ctx = workflow_context(history);
20290            let mut call =
20291                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20292            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20293            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20294                call.as_mut().poll(&mut task_context)
20295            else {
20296                panic!("changed {field} must fail replay");
20297            };
20298            assert_eq!(failure.reason, expected_reason);
20299            assert_eq!(failure.sequence, Some(1));
20300            assert!(ctx.take_commands().expect("commands").is_empty());
20301        }
20302    }
20303
20304    #[test]
20305    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
20306        let mut history = completed_retry_activity_history();
20307        let activity = history[0].payload["activity"]
20308            .as_object_mut()
20309            .expect("activity snapshot");
20310        activity.remove("execution_mode");
20311        activity.remove("retry_policy");
20312
20313        let mut current = retry_activity_options();
20314        current.start_to_close_timeout = Some(Duration::from_secs(45));
20315        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
20316        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
20317        current.heartbeat_timeout = Some(Duration::from_secs(12));
20318
20319        let ctx = workflow_context(history);
20320        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
20321        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20322        assert!(matches!(
20323            call.as_mut().poll(&mut task_context),
20324            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20325        ));
20326        assert!(ctx.take_commands().expect("commands").is_empty());
20327        ctx.ensure_history_consumed().expect("history consumed");
20328    }
20329
20330    #[test]
20331    fn terminal_activity_failed_after_start_returns_typed_failure() {
20332        let history = vec![
20333            history_event(
20334                "ActivityScheduled",
20335                json!({
20336                    "sequence": 1,
20337                    "activity_type": "flaky",
20338                    "activity_execution_id": "act-terminal",
20339                    "activity": {
20340                        "id": "act-terminal",
20341                        "sequence": 1,
20342                        "type": "flaky",
20343                        "queue": "critical-activities",
20344                        "retry_policy": {
20345                            "snapshot_version": 1,
20346                            "max_attempts": 3,
20347                            "backoff_seconds": [2, 4],
20348                            "non_retryable_error_types": ["PermanentError"]
20349                        }
20350                    }
20351                }),
20352            ),
20353            history_event(
20354                "ActivityStarted",
20355                json!({
20356                    "sequence": 1,
20357                    "activity_type": "flaky",
20358                    "activity_execution_id": "act-terminal",
20359                    "activity_attempt_id": "attempt-1",
20360                    "attempt_number": 1
20361                }),
20362            ),
20363            history_event(
20364                "ActivityFailed",
20365                json!({
20366                    "sequence": 1,
20367                    "activity_type": "flaky",
20368                    "activity_execution_id": "act-terminal",
20369                    "activity_attempt_id": "attempt-1",
20370                    "attempt_number": 1,
20371                    "failure_id": "failure-terminal",
20372                    "failure_category": "activity",
20373                    "exception_type": "PermanentError",
20374                    "message": "cannot retry",
20375                    "non_retryable": true
20376                }),
20377            ),
20378        ];
20379        let ctx = workflow_context(history);
20380        let mut call =
20381            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20382        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20383
20384        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
20385            call.as_mut().poll(&mut task_context)
20386        else {
20387            panic!("terminal ActivityFailed must settle the activity future");
20388        };
20389        assert_eq!(failure.kind, ActivityFailureKind::Failed);
20390        assert_eq!(
20391            failure.activity_execution_id.as_deref(),
20392            Some("act-terminal")
20393        );
20394        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
20395        assert!(failure.non_retryable);
20396        assert!(ctx.take_commands().expect("commands").is_empty());
20397        ctx.ensure_history_consumed().expect("history consumed");
20398    }
20399
20400    #[test]
20401    fn activity_terminal_events_return_machine_readable_failures() {
20402        let cases = [
20403            (
20404                "ActivityFailed",
20405                json!({
20406                    "sequence": 1,
20407                    "activity_type": "charge-card",
20408                    "activity_execution_id": "act-1",
20409                    "activity_attempt_id": "attempt-2",
20410                    "attempt_number": 2,
20411                    "failure_id": "failure-1",
20412                    "failure_category": "activity",
20413                    "exception_type": "PaymentDeclined",
20414                    "exception_class": "payments.PaymentDeclined",
20415                    "message": "card declined",
20416                    "non_retryable": true
20417                }),
20418                ActivityFailureKind::Failed,
20419                "activity",
20420            ),
20421            (
20422                "ActivityCancelled",
20423                json!({
20424                    "sequence": 1,
20425                    "activity_type": "charge-card",
20426                    "activity_execution_id": "act-1",
20427                    "activity_attempt_id": "attempt-1"
20428                }),
20429                ActivityFailureKind::Cancelled,
20430                "cancelled",
20431            ),
20432        ];
20433
20434        for (event_type, payload, expected_kind, expected_reason) in cases {
20435            let ctx = workflow_context(vec![history_event(event_type, payload)]);
20436            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
20437            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20438            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
20439                call.as_mut().poll(&mut task_context)
20440            else {
20441                panic!("expected terminal activity failure");
20442            };
20443            assert_eq!(failure.kind, expected_kind);
20444            assert_eq!(failure.reason, expected_reason);
20445            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
20446            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
20447        }
20448    }
20449
20450    #[test]
20451    fn every_activity_timeout_class_is_typed() {
20452        for timeout_kind in [
20453            "start_to_close",
20454            "schedule_to_start",
20455            "schedule_to_close",
20456            "heartbeat",
20457        ] {
20458            let ctx = workflow_context(vec![history_event(
20459                "ActivityTimedOut",
20460                json!({
20461                    "sequence": 1,
20462                    "activity_type": "slow",
20463                    "activity_execution_id": "act-timeout",
20464                    "activity_attempt_id": "attempt-timeout",
20465                    "failure_category": "timeout",
20466                    "timeout_kind": timeout_kind,
20467                    "message": "deadline expired"
20468                }),
20469            )]);
20470            let mut call = Box::pin(ctx.activity("slow", json!([])));
20471            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20472            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
20473                call.as_mut().poll(&mut task_context)
20474            else {
20475                panic!("expected timeout failure");
20476            };
20477            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
20478            assert_eq!(failure.reason, timeout_kind);
20479            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
20480            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
20481        }
20482    }
20483
20484    #[test]
20485    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
20486        let ctx = workflow_context(Vec::new());
20487        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
20488        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20489
20490        assert!(matches!(
20491            sleep.as_mut().poll(&mut task_context),
20492            Poll::Pending
20493        ));
20494        assert!(matches!(
20495            sleep.as_mut().poll(&mut task_context),
20496            Poll::Pending
20497        ));
20498
20499        let commands = ctx.take_commands().expect("timer command");
20500        assert_eq!(
20501            commands,
20502            vec![json!({
20503                "type": "start_timer",
20504                "delay_seconds": 2,
20505            })]
20506        );
20507    }
20508
20509    #[test]
20510    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
20511        let history = vec![
20512            history_event(
20513                "TimerScheduled",
20514                json!({
20515                    "sequence": 1,
20516                    "timer_id": "timer-1",
20517                    "delay_seconds": 5,
20518                    "fire_at": "2026-07-11T12:00:05Z",
20519                }),
20520            ),
20521            history_event(
20522                "TimerFired",
20523                json!({
20524                    "sequence": 1,
20525                    "timer_id": "timer-1",
20526                    "delay_seconds": 5,
20527                    "fire_at": "2026-07-11T12:00:05Z",
20528                    "fired_at": "2026-07-11T12:00:05Z",
20529                }),
20530            ),
20531        ];
20532
20533        for _restart in 0..2 {
20534            let ctx = workflow_context(history.clone());
20535            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
20536            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20537            assert!(matches!(
20538                sleep.as_mut().poll(&mut task_context),
20539                Poll::Ready(Ok(()))
20540            ));
20541            assert!(ctx.take_commands().expect("commands").is_empty());
20542            ctx.ensure_history_consumed().expect("history consumed");
20543        }
20544    }
20545
20546    #[test]
20547    fn workflow_sleep_rejects_changed_delay_during_replay() {
20548        let ctx = workflow_context(vec![
20549            history_event(
20550                "TimerScheduled",
20551                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
20552            ),
20553            history_event(
20554                "TimerFired",
20555                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
20556            ),
20557        ]);
20558        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
20559        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20560
20561        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20562            sleep.as_mut().poll(&mut task_context)
20563        else {
20564            panic!("changed timer delay must be rejected");
20565        };
20566        assert_eq!(failure.reason, "timer_delay_mismatch");
20567        assert_eq!(failure.sequence, Some(1));
20568    }
20569
20570    #[test]
20571    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
20572        let ctx = workflow_context(Vec::new());
20573        let mut wait = Box::pin(
20574            ctx.wait_condition(
20575                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
20576                    .timeout(Duration::from_millis(60_001)),
20577                || Ok(false),
20578            ),
20579        );
20580        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20581
20582        assert!(matches!(
20583            wait.as_mut().poll(&mut task_context),
20584            Poll::Pending
20585        ));
20586        assert!(matches!(
20587            wait.as_mut().poll(&mut task_context),
20588            Poll::Pending
20589        ));
20590        assert_eq!(
20591            ctx.take_commands().expect("condition command"),
20592            vec![json!({
20593                "type": "open_condition_wait",
20594                "condition_wait_occurrence_id": "rust:condition-wait:0",
20595                "condition_key": "approval.ready",
20596                "condition_definition_fingerprint": "sha256:approval-v1",
20597                "timeout_seconds": 61,
20598            })]
20599        );
20600    }
20601
20602    #[test]
20603    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
20604        let ctx = workflow_context(Vec::new());
20605        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
20606        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20607        assert!(matches!(
20608            satisfied.as_mut().poll(&mut task_context),
20609            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
20610        ));
20611
20612        let mut timed_out = Box::pin(wait_condition!(
20613            ctx,
20614            "no-wait",
20615            timeout: Duration::ZERO,
20616            || Ok(false),
20617        ));
20618        assert!(matches!(
20619            timed_out.as_mut().poll(&mut task_context),
20620            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
20621        ));
20622        assert!(ctx.take_commands().expect("commands").is_empty());
20623    }
20624
20625    #[test]
20626    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
20627        let signal_history = vec![
20628            history_event(
20629                "ConditionWaitOpened",
20630                json!({
20631                    "sequence": 4,
20632                    "condition_wait_id": "condition:4",
20633                    "condition_wait_occurrence_id": "rust:condition-wait:0",
20634                    "condition_key": "approval",
20635                    "condition_definition_fingerprint": "sha256:approval-v1",
20636                    "timeout_seconds": 30,
20637                }),
20638            ),
20639            history_event(
20640                "SignalReceived",
20641                json!({
20642                    "workflow_sequence": 4,
20643                    "signal_name": "approve",
20644                    "arguments": fixture_envelope(json!(["Ada"])),
20645                }),
20646            ),
20647        ];
20648        for _worker_before_or_after_restart in 0..2 {
20649            let ctx = workflow_context(signal_history.clone());
20650            let predicate_ctx = ctx.clone();
20651            let mut wait = Box::pin(
20652                ctx.wait_condition(
20653                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
20654                        .timeout(Duration::from_secs(30)),
20655                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
20656                ),
20657            );
20658            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20659            assert!(matches!(
20660                wait.as_mut().poll(&mut task_context),
20661                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
20662            ));
20663            assert!(ctx.take_commands().expect("commands").is_empty());
20664            ctx.ensure_history_consumed().expect("condition consumed");
20665        }
20666
20667        let update_history = vec![
20668            history_event(
20669                "ConditionWaitOpened",
20670                json!({
20671                    "sequence": 7,
20672                    "condition_wait_id": "condition:7",
20673                    "condition_wait_occurrence_id": "rust:condition-wait:0",
20674                    "condition_key": "update-approval",
20675                    "condition_definition_fingerprint": "sha256:update-approval-v1",
20676                }),
20677            ),
20678            history_event(
20679                "UpdateApplied",
20680                json!({
20681                    "sequence": 7,
20682                    "update_id": "update-1",
20683                    "update_name": "approve",
20684                    "arguments": fixture_envelope(json!([true])),
20685                }),
20686            ),
20687        ];
20688        let ctx = workflow_context(update_history);
20689        let predicate_ctx = ctx.clone();
20690        let mut wait = Box::pin(ctx.wait_condition(
20691            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
20692            move || {
20693                Ok(predicate_ctx
20694                    .updates("approve")?
20695                    .first()
20696                    .and_then(|arguments| arguments.first())
20697                    .and_then(Value::as_bool)
20698                    == Some(true))
20699            },
20700        ));
20701        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20702        assert!(matches!(
20703            wait.as_mut().poll(&mut task_context),
20704            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
20705        ));
20706        assert!(ctx.take_commands().expect("commands").is_empty());
20707        ctx.ensure_history_consumed().expect("condition consumed");
20708    }
20709
20710    #[test]
20711    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
20712        let open_history = vec![
20713            history_event(
20714                "ConditionWaitOpened",
20715                json!({
20716                    "sequence": 3,
20717                    "condition_wait_id": "condition:3",
20718                    "condition_wait_occurrence_id": "rust:condition-wait:0",
20719                    "condition_key": "two-votes",
20720                    "condition_definition_fingerprint": "sha256:two-votes-v1",
20721                    "timeout_seconds": 120,
20722                }),
20723            ),
20724            history_event(
20725                "SignalReceived",
20726                json!({
20727                    "workflow_sequence": 3,
20728                    "signal_name": "vote",
20729                    "arguments": fixture_envelope(json!(["first"])),
20730                }),
20731            ),
20732        ];
20733        for _worker_before_or_after_restart in 0..2 {
20734            let ctx = workflow_context(open_history.clone());
20735            let predicate_ctx = ctx.clone();
20736            let mut wait = Box::pin(
20737                ctx.wait_condition(
20738                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
20739                        .timeout(Duration::from_secs(120)),
20740                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
20741                ),
20742            );
20743            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20744            assert!(matches!(
20745                wait.as_mut().poll(&mut task_context),
20746                Poll::Pending
20747            ));
20748            assert_eq!(
20749                ctx.take_commands().expect("reopened condition"),
20750                vec![json!({
20751                    "type": "open_condition_wait",
20752                    "condition_wait_occurrence_id": "rust:condition-wait:0",
20753                    "condition_key": "two-votes",
20754                    "condition_definition_fingerprint": "sha256:two-votes-v1",
20755                    "timeout_seconds": 120,
20756                })]
20757            );
20758        }
20759
20760        let satisfied_ctx = workflow_context(vec![
20761            history_event(
20762                "ConditionWaitOpened",
20763                json!({
20764                    "sequence": 5,
20765                    "condition_wait_id": "condition:5",
20766                    "condition_wait_occurrence_id": "rust:condition-wait:0",
20767                    "condition_key": "approval",
20768                    "condition_definition_fingerprint": "sha256:approval-v1",
20769                }),
20770            ),
20771            history_event(
20772                "ConditionWaitSatisfied",
20773                json!({
20774                    "sequence": 5,
20775                    "condition_wait_id": "condition:5",
20776                    "condition_wait_occurrence_id": "rust:condition-wait:0",
20777                    "condition_key": "approval",
20778                    "condition_definition_fingerprint": "sha256:approval-v1",
20779                }),
20780            ),
20781        ]);
20782        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
20783            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
20784            || Ok(false),
20785        ));
20786        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20787        assert!(matches!(
20788            satisfied.as_mut().poll(&mut task_context),
20789            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
20790        ));
20791
20792        let timed_out_ctx = workflow_context(vec![
20793            history_event(
20794                "ConditionWaitOpened",
20795                json!({
20796                    "sequence": 8,
20797                    "condition_wait_id": "condition:8",
20798                    "condition_wait_occurrence_id": "rust:condition-wait:0",
20799                    "condition_key": "approval-timeout",
20800                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
20801                    "timeout_seconds": 5,
20802                }),
20803            ),
20804            history_event(
20805                "TimerScheduled",
20806                json!({
20807                    "sequence": 9,
20808                    "timer_id": "condition-timer:9",
20809                    "timer_kind": "condition_timeout",
20810                    "condition_wait_id": "condition:8",
20811                    "delay_seconds": 5,
20812                }),
20813            ),
20814            history_event(
20815                "TimerFired",
20816                json!({
20817                    "sequence": 9,
20818                    "timer_id": "condition-timer:9",
20819                    "timer_kind": "condition_timeout",
20820                    "condition_wait_id": "condition:8",
20821                    "delay_seconds": 5,
20822                }),
20823            ),
20824        ]);
20825        let mut timed_out = Box::pin(
20826            timed_out_ctx.wait_condition(
20827                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
20828                    .timeout(Duration::from_secs(5)),
20829                || Ok(true),
20830            ),
20831        );
20832        assert!(matches!(
20833            timed_out.as_mut().poll(&mut task_context),
20834            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
20835        ));
20836    }
20837
20838    #[test]
20839    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
20840        let ctx = workflow_context(reopened_selection_condition_history());
20841        {
20842            let state = ctx.state.lock().unwrap();
20843            assert!(matches!(
20844                selection_member_recorded_command(&state, 2),
20845                Some(RecordedCommand::ConditionWait {
20846                    sequence: 3,
20847                    result: None,
20848                    ..
20849                })
20850            ));
20851        }
20852        let mut selected = Box::pin(ctx.select_keyed(vec![
20853            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
20854            (
20855                "votes",
20856                ParallelOperation::condition(
20857                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
20858                    || Ok(true),
20859                ),
20860            ),
20861        ]));
20862        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20863        assert!(selected.as_mut().poll(&mut task_context).is_pending());
20864        assert!(
20865            ctx.take_commands().unwrap().is_empty(),
20866            "true predicate must not reopen the recorded wait"
20867        );
20868        ctx.ensure_history_consumed()
20869            .expect("physical reopens are consumed while canonical selection is pending");
20870    }
20871
20872    #[test]
20873    fn reopened_selection_condition_replays_its_latest_physical_winner() {
20874        for (terminal_type, acknowledge_timeout) in [
20875            ("ConditionWaitSatisfied", false),
20876            ("ConditionWaitTimedOut", false),
20877            ("TimerFired", false),
20878            ("TimerFired", true),
20879        ] {
20880            let mut history = reopened_selection_condition_history();
20881            let original_identity = history[1].payload["condition_wait_id"].clone();
20882            let uses_timer = terminal_type == "TimerFired";
20883            let mut resolution_payload = history[3].payload.clone();
20884            if uses_timer {
20885                for event in &mut history[1..] {
20886                    event.payload["timeout_seconds"] = json!(3);
20887                }
20888                resolution_payload = history[3].payload.clone();
20889                resolution_payload["timer_kind"] = json!("condition_timeout");
20890                resolution_payload["timer_id"] = json!("condition-timeout-3");
20891                resolution_payload["delay_seconds"] = json!(3);
20892                history.push(history_event("TimerScheduled", resolution_payload.clone()));
20893            }
20894            let mut resolution = history_event(terminal_type, resolution_payload.clone());
20895            resolution
20896                .raw
20897                .insert("id".into(), json!("latest-condition-resolution"));
20898            history.push(resolution);
20899            history.push(history_event(
20900                "SelectionResolved",
20901                json!({
20902                    "selection_group_id": "select-calls:1:2",
20903                    "selection_group_base_sequence": 1,
20904                    "selection_group_size": 2,
20905                    "member_key": "votes",
20906                    "member_index": 1,
20907                    "member_base_sequence": 2,
20908                    "member_size": 1,
20909                    "operation_kind": "condition",
20910                    "operation_identity": original_identity,
20911                    "outcome": "completed",
20912                    "resolution_event_id": "latest-condition-resolution",
20913                    "resolution_event_type": terminal_type,
20914                }),
20915            ));
20916            if acknowledge_timeout {
20917                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
20918            }
20919            let ctx = workflow_context(history);
20920            let mut selected = Box::pin(ctx.select_keyed(vec![
20921                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
20922                (
20923                    "votes",
20924                    ParallelOperation::condition(
20925                        if uses_timer {
20926                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
20927                                .timeout(Duration::from_secs(3))
20928                        } else {
20929                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
20930                        },
20931                        || Ok(true),
20932                    ),
20933                ),
20934            ]));
20935            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20936            match selected.as_mut().poll(&mut task_context) {
20937                Poll::Ready(Ok(result)) => {
20938                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
20939                    let expected = if terminal_type == "ConditionWaitSatisfied" {
20940                        ConditionWaitResult::Satisfied
20941                    } else {
20942                        ConditionWaitResult::TimedOut
20943                    };
20944                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
20945                }
20946                other => panic!("latest physical winner must replay: {other:?}"),
20947            }
20948            assert!(ctx.take_commands().unwrap().is_empty());
20949            ctx.ensure_history_consumed()
20950                .expect("winner history consumed");
20951        }
20952    }
20953
20954    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
20955        let fixture: Value = serde_json::from_str(include_str!(
20956            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
20957        ))
20958        .expect("grouped condition fixture");
20959        fixture["history"]
20960            .as_array()
20961            .unwrap()
20962            .iter()
20963            .map(|event| {
20964                let mut payload = event["payload"].clone();
20965                let index = payload["parallel_group_index"].as_u64().unwrap();
20966                payload["parallel_group_id"] = json!("select-calls:1:2");
20967                payload["parallel_group_mode"] = json!("select");
20968                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
20969                payload["selection_member_index"] = json!(index);
20970                payload["selection_member_base_sequence"] = json!(index + 1);
20971                payload["selection_member_size"] = json!(1);
20972                payload["selection_member_kind"] =
20973                    json!(if index == 0 { "timer" } else { "condition" });
20974                history_event(event["event_type"].as_str().unwrap(), payload)
20975            })
20976            .collect()
20977    }
20978
20979    #[test]
20980    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
20981        let fixture: Value = serde_json::from_str(include_str!(
20982            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
20983        ))
20984        .expect("grouped condition fixture");
20985        let original = fixture["history"].as_array().expect("fixture history");
20986        let decode = |events: &[Value]| {
20987            let history = events
20988                .iter()
20989                .map(|event| {
20990                    history_event(
20991                        event["event_type"].as_str().unwrap(),
20992                        event["payload"].clone(),
20993                    )
20994                })
20995                .collect::<Vec<_>>();
20996            recorded_commands(
20997                &history,
20998                DEFAULT_CODEC,
20999                WorkflowIdentity {
21000                    workflow_id: None,
21001                    run_id: None,
21002                },
21003            )
21004        };
21005        assert!(decode(original).is_ok());
21006        for field in [
21007            "condition_wait_occurrence_id",
21008            "condition_key",
21009            "condition_definition_fingerprint",
21010            "timeout_seconds",
21011            "parallel_group_id",
21012            "parallel_group_size",
21013            "parallel_group_index",
21014        ] {
21015            let mut changed = original.clone();
21016            changed[3]["payload"][field] = match field {
21017                "timeout_seconds" | "parallel_group_size" => json!(30),
21018                "parallel_group_index" => json!(0),
21019                _ => json!("changed"),
21020            };
21021            assert!(
21022                decode(&changed).is_err(),
21023                "reopen must reject changed {field}"
21024            );
21025        }
21026        let mut unsettled = original.clone();
21027        unsettled.remove(2);
21028        assert!(
21029            decode(&unsettled).is_err(),
21030            "physical predecessor must be resolved"
21031        );
21032        let mut timed_out = original.clone();
21033        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
21034        assert!(decode(&timed_out).is_err(), "timeout is terminal");
21035        let mut late_resolution = original.clone();
21036        late_resolution.swap(2, 3);
21037        assert!(
21038            decode(&late_resolution).is_err(),
21039            "later history cannot authorize a reopen"
21040        );
21041    }
21042
21043    #[test]
21044    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
21045        let history = vec![
21046            history_event(
21047                "ConditionWaitOpened",
21048                json!({
21049                    "sequence": 3,
21050                    "condition_wait_id": "condition:3",
21051                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21052                    "condition_key": "two-votes",
21053                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21054                }),
21055            ),
21056            history_event(
21057                "SignalReceived",
21058                json!({
21059                    "workflow_sequence": 3,
21060                    "signal_name": "vote",
21061                    "arguments": fixture_envelope(json!(["first"])),
21062                }),
21063            ),
21064            history_event(
21065                "ConditionWaitSatisfied",
21066                json!({
21067                    "sequence": 3,
21068                    "condition_wait_id": "condition:3",
21069                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21070                    "condition_key": "two-votes",
21071                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21072                }),
21073            ),
21074            history_event(
21075                "ConditionWaitOpened",
21076                json!({
21077                    "sequence": 5,
21078                    "condition_wait_id": "condition:5",
21079                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21080                    "condition_key": "two-votes",
21081                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21082                }),
21083            ),
21084            history_event(
21085                "SignalReceived",
21086                json!({
21087                    "workflow_sequence": 5,
21088                    "signal_name": "vote",
21089                    "arguments": fixture_envelope(json!(["second"])),
21090                }),
21091            ),
21092            history_event(
21093                "ConditionWaitSatisfied",
21094                json!({
21095                    "sequence": 5,
21096                    "condition_wait_id": "condition:5",
21097                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21098                    "condition_key": "two-votes",
21099                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21100                }),
21101            ),
21102        ];
21103        for _cold_worker_or_restart in 0..2 {
21104            let ctx = workflow_context(history.clone());
21105            let predicate_ctx = ctx.clone();
21106            let mut wait = Box::pin(ctx.wait_condition(
21107                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
21108                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
21109            ));
21110            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21111
21112            assert!(matches!(
21113                wait.as_mut().poll(&mut task_context),
21114                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21115            ));
21116            assert!(ctx.take_commands().expect("commands").is_empty());
21117            ctx.ensure_history_consumed()
21118                .expect("every physical wait-open is consumed");
21119        }
21120    }
21121
21122    #[test]
21123    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
21124        let history = vec![
21125            history_event(
21126                "ConditionWaitOpened",
21127                json!({
21128                    "sequence": 3,
21129                    "condition_wait_id": "condition:3",
21130                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21131                    "condition_key": "approved",
21132                    "condition_definition_fingerprint": "sha256:approved-v1",
21133                }),
21134            ),
21135            history_event(
21136                "UpdateApplied",
21137                json!({
21138                    "sequence": 3,
21139                    "update_id": "update-1",
21140                    "update_name": "approve",
21141                    "arguments": fixture_envelope(json!([false])),
21142                }),
21143            ),
21144            history_event(
21145                "ConditionWaitOpened",
21146                json!({
21147                    "sequence": 5,
21148                    "condition_wait_id": "condition:5",
21149                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21150                    "condition_key": "approved",
21151                    "condition_definition_fingerprint": "sha256:approved-v1",
21152                }),
21153            ),
21154            history_event(
21155                "UpdateApplied",
21156                json!({
21157                    "sequence": 5,
21158                    "update_id": "update-2",
21159                    "update_name": "approve",
21160                    "arguments": fixture_envelope(json!([true])),
21161                }),
21162            ),
21163        ];
21164
21165        for _cold_worker_or_restart in 0..2 {
21166            let ctx = workflow_context(history.clone());
21167            let predicate_ctx = ctx.clone();
21168            let mut wait = Box::pin(ctx.wait_condition(
21169                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
21170                move || {
21171                    Ok(predicate_ctx
21172                        .updates("approve")?
21173                        .last()
21174                        .and_then(|arguments| arguments.first())
21175                        .and_then(Value::as_bool)
21176                        == Some(true))
21177                },
21178            ));
21179            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21180
21181            assert!(matches!(
21182                wait.as_mut().poll(&mut task_context),
21183                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21184            ));
21185            assert!(ctx.take_commands().expect("commands").is_empty());
21186            ctx.ensure_history_consumed()
21187                .expect("every update-driven reopen is consumed");
21188        }
21189    }
21190
21191    #[test]
21192    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
21193        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
21194            ("shared", "sha256:first", "shared", "sha256:second"),
21195            ("first", "sha256:shared", "second", "sha256:shared"),
21196            ("shared", "sha256:shared", "shared", "sha256:shared"),
21197            ("first", "sha256:first", "second", "sha256:second"),
21198        ] {
21199            let history = vec![
21200                history_event(
21201                    "ConditionWaitOpened",
21202                    json!({
21203                        "sequence": 3,
21204                        "condition_wait_id": "condition:3",
21205                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21206                        "condition_key": first_key,
21207                        "condition_definition_fingerprint": first_fingerprint,
21208                    }),
21209                ),
21210                history_event(
21211                    "ConditionWaitSatisfied",
21212                    json!({
21213                        "sequence": 3,
21214                        "condition_wait_id": "condition:3",
21215                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21216                        "condition_key": first_key,
21217                        "condition_definition_fingerprint": first_fingerprint,
21218                    }),
21219                ),
21220                history_event(
21221                    "ConditionWaitOpened",
21222                    json!({
21223                        "sequence": 4,
21224                        "condition_wait_id": "condition:4",
21225                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21226                        "condition_key": second_key,
21227                        "condition_definition_fingerprint": second_fingerprint,
21228                    }),
21229                ),
21230                history_event(
21231                    "ConditionWaitSatisfied",
21232                    json!({
21233                        "sequence": 4,
21234                        "condition_wait_id": "condition:4",
21235                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21236                        "condition_key": second_key,
21237                        "condition_definition_fingerprint": second_fingerprint,
21238                    }),
21239                ),
21240            ];
21241            for _cold_worker_or_restart in 0..2 {
21242                let ctx = workflow_context(history.clone());
21243                let mut task_context = TaskContext::from_waker(noop_waker_ref());
21244                let mut first = Box::pin(ctx.wait_condition(
21245                    ConditionWaitOptions::new(first_key, first_fingerprint),
21246                    || Ok(false),
21247                ));
21248                assert!(matches!(
21249                    first.as_mut().poll(&mut task_context),
21250                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21251                ));
21252
21253                let mut second = Box::pin(ctx.wait_condition(
21254                    ConditionWaitOptions::new(second_key, second_fingerprint),
21255                    || Ok(false),
21256                ));
21257                assert!(matches!(
21258                    second.as_mut().poll(&mut task_context),
21259                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21260                ));
21261                assert!(ctx.take_commands().expect("commands").is_empty());
21262                ctx.ensure_history_consumed()
21263                    .expect("each authored wait consumes one occurrence");
21264            }
21265        }
21266    }
21267
21268    #[test]
21269    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
21270        fn worker() -> Worker {
21271            let client = Client::new("http://127.0.0.1:8080").expect("client");
21272            let mut worker = Worker::new(client, "rust-workers");
21273            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
21274                let mut outcomes = Vec::new();
21275                for _ in 0..2 {
21276                    outcomes.push(
21277                        ctx.wait_condition(
21278                            ConditionWaitOptions::new("shared", "sha256:shared"),
21279                            || Ok(false),
21280                        )
21281                        .await?,
21282                    );
21283                }
21284                Ok(json!(outcomes))
21285            });
21286            worker
21287        }
21288
21289        let task = workflow_task(
21290            "rust.condition-loop",
21291            vec![
21292                history_event(
21293                    "ConditionWaitOpened",
21294                    json!({
21295                        "sequence": 1,
21296                        "condition_wait_id": "condition:1",
21297                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21298                        "condition_key": "shared",
21299                        "condition_definition_fingerprint": "sha256:shared",
21300                    }),
21301                ),
21302                history_event(
21303                    "ConditionWaitSatisfied",
21304                    json!({
21305                        "sequence": 1,
21306                        "condition_wait_id": "condition:1",
21307                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21308                        "condition_key": "shared",
21309                        "condition_definition_fingerprint": "sha256:shared",
21310                    }),
21311                ),
21312                history_event(
21313                    "ConditionWaitOpened",
21314                    json!({
21315                        "sequence": 2,
21316                        "condition_wait_id": "condition:2",
21317                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21318                        "condition_key": "shared",
21319                        "condition_definition_fingerprint": "sha256:shared",
21320                    }),
21321                ),
21322                history_event(
21323                    "ConditionWaitSatisfied",
21324                    json!({
21325                        "sequence": 2,
21326                        "condition_wait_id": "condition:2",
21327                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21328                        "condition_key": "shared",
21329                        "condition_definition_fingerprint": "sha256:shared",
21330                    }),
21331                ),
21332            ],
21333            DEFAULT_CODEC,
21334        );
21335
21336        for _cold_worker_or_restart in 0..2 {
21337            let commands = worker()
21338                .execute_workflow_task(task.clone())
21339                .expect("adjacent loop waits replay deterministically");
21340            assert_eq!(commands.len(), 1);
21341            assert_eq!(commands[0]["type"], "complete_workflow");
21342            assert_eq!(
21343                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
21344                json!(["satisfied", "satisfied"])
21345            );
21346        }
21347    }
21348
21349    #[test]
21350    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
21351        let history = vec![history_event(
21352            "ConditionWaitOpened",
21353            json!({
21354                "sequence": 12,
21355                "condition_wait_id": "condition:12",
21356                "condition_wait_occurrence_id": "rust:condition-wait:0",
21357                "condition_key": "approval",
21358                "condition_definition_fingerprint": "sha256:approval-v1",
21359                "timeout_seconds": 30,
21360            }),
21361        )];
21362        for (options, expected_reason) in [
21363            (
21364                ConditionWaitOptions::new("changed", "sha256:approval-v1")
21365                    .timeout(Duration::from_secs(30)),
21366                "condition_wait_key_mismatch",
21367            ),
21368            (
21369                ConditionWaitOptions::new("approval", "sha256:approval-v2")
21370                    .timeout(Duration::from_secs(30)),
21371                "condition_wait_predicate_mismatch",
21372            ),
21373            (
21374                ConditionWaitOptions::new("approval", "sha256:approval-v1")
21375                    .timeout(Duration::from_secs(29)),
21376                "condition_wait_timeout_mismatch",
21377            ),
21378        ] {
21379            let ctx = workflow_context(history.clone());
21380            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
21381            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21382            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21383                wait.as_mut().poll(&mut task_context)
21384            else {
21385                panic!("changed condition definition must fail replay");
21386            };
21387            assert_eq!(failure.reason, expected_reason);
21388            assert_eq!(failure.sequence, Some(12));
21389        }
21390    }
21391
21392    #[test]
21393    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
21394        let error = WorkflowState::new(
21395            vec![history_event(
21396                "ConditionWaitOpened",
21397                json!({
21398                    "sequence": 12,
21399                    "condition_wait_id": "condition:12",
21400                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21401                    "condition_key": "approval",
21402                }),
21403            )],
21404            "rust-workers".to_string(),
21405            DEFAULT_CODEC.to_string(),
21406            None,
21407        )
21408        .expect_err("condition history without a predicate fingerprint must fail");
21409
21410        assert!(matches!(
21411            error,
21412            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21413                if reason == "condition_wait_predicate_fingerprint_missing"
21414        ));
21415    }
21416
21417    #[test]
21418    fn condition_wait_history_requires_authored_occurrence_identity() {
21419        let error = WorkflowState::new(
21420            vec![history_event(
21421                "ConditionWaitOpened",
21422                json!({
21423                    "sequence": 12,
21424                    "condition_wait_id": "condition:12",
21425                    "condition_key": "approval",
21426                    "condition_definition_fingerprint": "sha256:approval-v1",
21427                }),
21428            )],
21429            "rust-workers".to_string(),
21430            DEFAULT_CODEC.to_string(),
21431            None,
21432        )
21433        .expect_err("condition history without occurrence identity must fail");
21434
21435        assert!(matches!(
21436            error,
21437            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21438                if reason == "condition_wait_occurrence_id_missing"
21439        ));
21440    }
21441
21442    #[test]
21443    fn typed_search_attribute_updates_validate_emit_and_replay() {
21444        let update = SearchAttributeUpdate::new()
21445            .keyword("OrderStatus", " waiting ")
21446            .expect("keyword")
21447            .int("Attempt", 3)
21448            .expect("int")
21449            .bool("Escalated", false)
21450            .expect("bool")
21451            .keyword_list("Regions", ["us-east", "eu-west"])
21452            .expect("list")
21453            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
21454            .expect("datetime")
21455            .delete("LegacyStatus")
21456            .expect("delete");
21457        let ctx = workflow_context(Vec::new());
21458        ctx.upsert_search_attributes(update.clone())
21459            .expect("typed update");
21460        assert_eq!(
21461            ctx.take_commands().expect("search-attribute command"),
21462            vec![json!({
21463                "type": "upsert_search_attributes",
21464                "attributes": {
21465                    "Attempt": 3,
21466                    "Escalated": false,
21467                    "LegacyStatus": null,
21468                    "OrderStatus": "waiting",
21469                    "Regions": ["us-east", "eu-west"],
21470                    "UpdatedAt": "2026-08-22T04:00:00Z",
21471                },
21472                "attribute_types": {
21473                    "Attempt": "int",
21474                    "Escalated": "bool",
21475                    "OrderStatus": "keyword",
21476                    "Regions": "keyword_list",
21477                    "UpdatedAt": "datetime",
21478                },
21479            })]
21480        );
21481
21482        let replay = workflow_context(vec![history_event(
21483            "SearchAttributesUpserted",
21484            json!({
21485                "sequence": 6,
21486                "attributes": {
21487                    "Attempt": 3,
21488                    "Escalated": false,
21489                    "LegacyStatus": null,
21490                    "OrderStatus": "waiting",
21491                    "Regions": ["us-east", "eu-west"],
21492                    "UpdatedAt": "2026-08-22T04:00:00Z",
21493                },
21494                "attribute_types": {
21495                    "Attempt": "int",
21496                    "Escalated": "bool",
21497                    "OrderStatus": "keyword",
21498                    "Regions": "keyword_list",
21499                    "UpdatedAt": "datetime",
21500                },
21501                "merged": {},
21502            }),
21503        )]);
21504        replay
21505            .upsert_search_attributes(update)
21506            .expect("matching update replays");
21507        assert!(replay.take_commands().expect("commands").is_empty());
21508        replay.ensure_history_consumed().expect("history consumed");
21509
21510        let type_drift = workflow_context(vec![history_event(
21511            "SearchAttributesUpserted",
21512            json!({
21513                "sequence": 7,
21514                "attributes": {"OrderStatus": "waiting"},
21515                "attribute_types": {"OrderStatus": "keyword"},
21516                "merged": {"OrderStatus": "waiting"},
21517            }),
21518        )]);
21519        let error = type_drift
21520            .upsert_search_attributes(
21521                SearchAttributeUpdate::new()
21522                    .string("OrderStatus", "waiting")
21523                    .expect("string update"),
21524            )
21525            .expect_err("same JSON value with a changed type must fail replay");
21526        assert!(matches!(
21527            error,
21528            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21529                if reason == "search_attribute_type_mismatch"
21530        ));
21531
21532        let malformed_types = WorkflowState::new(
21533            vec![history_event(
21534                "SearchAttributesUpserted",
21535                json!({
21536                    "sequence": 8,
21537                    "attributes": {"OrderStatus": "waiting"},
21538                    "attribute_types": {"OrderStatus": "unsupported"},
21539                    "merged": {"OrderStatus": "waiting"},
21540                }),
21541            )],
21542            "rust-workers".to_string(),
21543            DEFAULT_CODEC.to_string(),
21544            None,
21545        )
21546        .expect_err("unsupported search-attribute type metadata must fail");
21547        assert!(matches!(
21548            malformed_types,
21549            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21550                if reason == "search_attribute_types_malformed"
21551        ));
21552
21553        assert!(matches!(
21554            SearchAttributeUpdate::new().keyword("bad key", "value"),
21555            Err(SearchAttributeUpdateError::InvalidKey(_))
21556        ));
21557        assert!(matches!(
21558            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
21559            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
21560        ));
21561        assert!(matches!(
21562            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
21563            Err(SearchAttributeUpdateError::ValueTooLong { .. })
21564        ));
21565        assert!(matches!(
21566            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
21567            Err(SearchAttributeUpdateError::InvalidDateTime(_))
21568        ));
21569        assert!(matches!(
21570            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
21571            Err(Error::InvalidSearchAttributeUpdate(
21572                SearchAttributeUpdateError::Empty
21573            ))
21574        ));
21575    }
21576
21577    #[test]
21578    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
21579        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
21580        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
21581
21582        assert!(SearchAttributeUpdate::new()
21583            .string("AsciiDescription", ascii)
21584            .is_ok());
21585        assert!(SearchAttributeUpdate::new()
21586            .string("Utf8Description", utf8)
21587            .is_ok());
21588        assert!(matches!(
21589            SearchAttributeUpdate::new().string(
21590                "TooLongDescription",
21591                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
21592            ),
21593            Err(SearchAttributeUpdateError::ValueTooLong {
21594                kind: "string",
21595                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
21596                ..
21597            })
21598        ));
21599    }
21600
21601    #[test]
21602    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
21603        let lone_fire = WorkflowState::new(
21604            vec![history_event(
21605                "TimerFired",
21606                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21607            )],
21608            "rust-workers".to_string(),
21609            DEFAULT_CODEC.to_string(),
21610            None,
21611        )
21612        .expect_err("TimerFired requires TimerScheduled");
21613        assert!(matches!(
21614            lone_fire,
21615            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21616                if reason == "timer_schedule_missing_or_duplicate"
21617        ));
21618
21619        let wrong_identity = WorkflowState::new(
21620            vec![
21621                history_event(
21622                    "TimerScheduled",
21623                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21624                ),
21625                history_event(
21626                    "TimerFired",
21627                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
21628                ),
21629            ],
21630            "rust-workers".to_string(),
21631            DEFAULT_CODEC.to_string(),
21632            None,
21633        )
21634        .expect_err("fire must match scheduled timer identity");
21635        assert!(matches!(
21636            wrong_identity,
21637            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21638                if reason == "timer_identity_mismatch"
21639        ));
21640
21641        let duplicate_fire = WorkflowState::new(
21642            vec![
21643                history_event(
21644                    "TimerScheduled",
21645                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21646                ),
21647                history_event(
21648                    "TimerFired",
21649                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21650                ),
21651                history_event(
21652                    "TimerFired",
21653                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21654                ),
21655            ],
21656            "rust-workers".to_string(),
21657            DEFAULT_CODEC.to_string(),
21658            None,
21659        )
21660        .expect_err("a durable timer cannot fire twice");
21661        assert!(matches!(
21662            duplicate_fire,
21663            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21664                if reason == "duplicate_timer_fire"
21665        ));
21666
21667        let wrong_fired_delay = WorkflowState::new(
21668            vec![
21669                history_event(
21670                    "TimerScheduled",
21671                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21672                ),
21673                history_event(
21674                    "TimerFired",
21675                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
21676                ),
21677            ],
21678            "rust-workers".to_string(),
21679            DEFAULT_CODEC.to_string(),
21680            None,
21681        )
21682        .expect_err("timer schedule and fire delays must agree");
21683        assert!(matches!(
21684            wrong_fired_delay,
21685            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21686                if reason == "timer_history_delay_mismatch"
21687        ));
21688    }
21689
21690    #[test]
21691    fn replay_rejects_activity_moved_before_recorded_timer() {
21692        let ctx = workflow_context(vec![
21693            history_event(
21694                "TimerScheduled",
21695                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21696            ),
21697            history_event(
21698                "TimerFired",
21699                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21700            ),
21701            history_event(
21702                "ActivityCompleted",
21703                json!({
21704                    "sequence": 2,
21705                    "activity_type": "after-timer",
21706                    "payload_codec": DEFAULT_CODEC,
21707                    "result": fixture_envelope(json!("done")),
21708                }),
21709            ),
21710        ]);
21711        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
21712        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21713
21714        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21715            activity.as_mut().poll(&mut task_context)
21716        else {
21717            panic!("reordered durable command must be rejected");
21718        };
21719        assert_eq!(failure.reason, "recorded_command_mismatch");
21720        assert_eq!(failure.sequence, Some(1));
21721        assert_eq!(failure.expected.as_deref(), Some("timer"));
21722        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
21723    }
21724
21725    #[test]
21726    fn workflow_context_emits_a_typed_named_signal_wait() {
21727        let ctx = workflow_context(Vec::new());
21728        let mut signal = Box::pin(ctx.wait_signal("finish"));
21729        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21730
21731        assert!(matches!(
21732            signal.as_mut().poll(&mut task_context),
21733            Poll::Pending
21734        ));
21735        assert_eq!(
21736            ctx.take_commands().expect("signal-wait command"),
21737            vec![json!({
21738                "type": "open_signal_wait",
21739                "signal_name": "finish",
21740            })]
21741        );
21742    }
21743
21744    #[test]
21745    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
21746        let ctx = workflow_context(Vec::new());
21747        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
21748        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21749
21750        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
21751        else {
21752            panic!("runtime-reserved signal should be rejected");
21753        };
21754        assert!(message.contains("reserved by the workflow runtime"));
21755        assert!(ctx.take_commands().expect("commands").is_empty());
21756    }
21757
21758    #[tokio::test]
21759    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
21760        let client = Client::builder("http://127.0.0.1:9")
21761            .build()
21762            .expect("client");
21763        let error = client
21764            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
21765            .await
21766            .expect_err("runtime-reserved signal should be rejected before transport");
21767
21768        assert!(
21769            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
21770        );
21771    }
21772
21773    #[test]
21774    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
21775        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
21776            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
21777                value.to_string(),
21778            )]))
21779            .expect("message payload");
21780            json!({
21781                "schema": MESSAGE_STREAM_SCHEMA,
21782                "stream_name": "orders",
21783                "message_id": message_id,
21784                "position": position,
21785                "payload_envelope": payload,
21786            })
21787        }
21788
21789        fn opened(sequence: u64) -> HistoryEvent {
21790            history_event(
21791                "SignalWaitOpened",
21792                json!({
21793                    "sequence": sequence,
21794                    "signal_name": MESSAGE_STREAM_SIGNAL,
21795                }),
21796            )
21797        }
21798
21799        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
21800            history_event(
21801                "SignalApplied",
21802                json!({
21803                    "sequence": sequence,
21804                    "signal_name": MESSAGE_STREAM_SIGNAL,
21805                    "value": fixture_envelope(json!([delivery])),
21806                }),
21807            )
21808        }
21809
21810        fn received(delivery: Value) -> HistoryEvent {
21811            history_event(
21812                "SignalReceived",
21813                json!({
21814                    "signal_name": MESSAGE_STREAM_SIGNAL,
21815                    "arguments": fixture_envelope(json!([delivery])),
21816                    "payload_codec": DEFAULT_CODEC,
21817                }),
21818            )
21819        }
21820
21821        let client = Client::new("http://127.0.0.1:8080").expect("client");
21822        let mut worker = Worker::new(client, "rust-workers");
21823        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
21824            let messages = ctx.message_stream("orders")?.receive(2).await?;
21825            Ok(json!(messages
21826                .into_iter()
21827                .map(|message| message.message_id)
21828                .collect::<Vec<_>>()))
21829        });
21830
21831        let first = delivery("message-1", 1, "one");
21832        let second = delivery("message-2", 2, "two");
21833        let batch = worker
21834            .execute_workflow_task_decision(workflow_task(
21835                "rust.message-stream-batch",
21836                vec![
21837                    opened(1),
21838                    received(first.clone()),
21839                    applied(1, first.clone()),
21840                    received(first.clone()),
21841                    received(second),
21842                ],
21843                DEFAULT_CODEC,
21844            ))
21845            .expect("worker task consumes the available batch");
21846
21847        assert_eq!(batch.commands.len(), 1);
21848        assert_eq!(batch.commands[0]["type"], "complete_workflow");
21849        assert_eq!(
21850            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
21851                .expect("workflow result"),
21852            json!(["message-1", "message-2"])
21853        );
21854        assert_eq!(
21855            batch.message_stream_cursors,
21856            vec![json!({"stream_name": "orders", "through_position": 2})]
21857        );
21858        assert!(batch.message_stream_waits.is_empty());
21859
21860        let partial = worker
21861            .execute_workflow_task_decision(workflow_task(
21862                "rust.message-stream-batch",
21863                vec![opened(1), received(first.clone()), applied(1, first)],
21864                DEFAULT_CODEC,
21865            ))
21866            .expect("worker task returns without waiting for a missing second item");
21867        assert_eq!(partial.commands.len(), 1);
21868        assert_eq!(partial.commands[0]["type"], "complete_workflow");
21869        assert_eq!(
21870            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
21871                .expect("workflow result"),
21872            json!(["message-1"])
21873        );
21874        assert_eq!(
21875            partial.message_stream_cursors,
21876            vec![json!({"stream_name": "orders", "through_position": 1})]
21877        );
21878        assert!(partial.message_stream_waits.is_empty());
21879    }
21880
21881    #[test]
21882    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
21883        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
21884            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
21885                value.to_string(),
21886            )]))
21887            .expect("message payload");
21888            json!({
21889                "schema": MESSAGE_STREAM_SCHEMA,
21890                "stream_name": "orders",
21891                "message_id": message_id,
21892                "position": position,
21893                "payload_envelope": payload,
21894            })
21895        }
21896
21897        fn opened(sequence: u64) -> HistoryEvent {
21898            history_event(
21899                "SignalWaitOpened",
21900                json!({
21901                    "sequence": sequence,
21902                    "signal_name": MESSAGE_STREAM_SIGNAL,
21903                }),
21904            )
21905        }
21906
21907        fn received(delivery: Value) -> HistoryEvent {
21908            history_event(
21909                "SignalReceived",
21910                json!({
21911                    "signal_name": MESSAGE_STREAM_SIGNAL,
21912                    "arguments": fixture_envelope(json!([delivery])),
21913                    "payload_codec": DEFAULT_CODEC,
21914                }),
21915            )
21916        }
21917
21918        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
21919            history_event(
21920                "SignalApplied",
21921                json!({
21922                    "sequence": sequence,
21923                    "signal_name": MESSAGE_STREAM_SIGNAL,
21924                    "value": fixture_envelope(json!([delivery])),
21925                }),
21926            )
21927        }
21928
21929        let client = Client::new("http://127.0.0.1:8080").expect("client");
21930        let mut worker = Worker::new(client, "rust-workers");
21931        worker.register_workflow(
21932            "rust.message-stream-partial-batches",
21933            |ctx, _input| async move {
21934                let stream = ctx.message_stream("orders")?;
21935                let first = stream.receive(10).await?;
21936                let second = stream.receive(10).await?;
21937                Ok(json!([
21938                    first
21939                        .into_iter()
21940                        .map(|message| message.message_id)
21941                        .collect::<Vec<_>>(),
21942                    second
21943                        .into_iter()
21944                        .map(|message| message.message_id)
21945                        .collect::<Vec<_>>(),
21946                ]))
21947            },
21948        );
21949
21950        let first = delivery("message-1", 1, "one");
21951        let second = delivery("message-2", 2, "two");
21952        let decision = worker
21953            .execute_workflow_task_decision(workflow_task(
21954                "rust.message-stream-partial-batches",
21955                vec![
21956                    opened(1),
21957                    received(first.clone()),
21958                    applied(1, first),
21959                    opened(2),
21960                    received(second.clone()),
21961                    applied(2, second),
21962                ],
21963                DEFAULT_CODEC,
21964            ))
21965            .expect("cold replay preserves both authored receive boundaries");
21966
21967        assert_eq!(decision.commands.len(), 1);
21968        assert_eq!(decision.commands[0]["type"], "complete_workflow");
21969        assert_eq!(
21970            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
21971                .expect("workflow result"),
21972            json!([["message-1"], ["message-2"]])
21973        );
21974        assert_eq!(
21975            decision.message_stream_cursors,
21976            vec![json!({"stream_name": "orders", "through_position": 2})]
21977        );
21978        assert!(decision.message_stream_waits.is_empty());
21979    }
21980
21981    #[test]
21982    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
21983        let ctx = workflow_context(Vec::new());
21984        let stream = ctx.message_stream("orders").expect("message stream");
21985        let mut receive = Box::pin(stream.receive(10));
21986        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21987
21988        assert!(matches!(
21989            receive.as_mut().poll(&mut task_context),
21990            Poll::Pending
21991        ));
21992        assert_eq!(
21993            ctx.take_commands().expect("message-stream wait command"),
21994            vec![json!({
21995                "type": "open_signal_wait",
21996                "signal_name": MESSAGE_STREAM_SIGNAL,
21997            })]
21998        );
21999        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
22000        assert!(cursors.is_empty());
22001        assert_eq!(
22002            waits,
22003            vec![json!({"stream_name": "orders", "after_position": 0})]
22004        );
22005    }
22006
22007    #[test]
22008    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
22009        let ctx = workflow_context(vec![history_event(
22010            "SignalReceived",
22011            json!({
22012                "signal_name": MESSAGE_STREAM_SIGNAL,
22013                "arguments": fixture_envelope(json!([{
22014                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
22015                    "stream_name": "orders",
22016                    "through_position": 2,
22017                }])),
22018                "payload_codec": DEFAULT_CODEC,
22019            }),
22020        )]);
22021        let stream = ctx.message_stream("orders").expect("message stream");
22022        let mut receive = Box::pin(stream.receive(10));
22023        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22024
22025        assert!(matches!(
22026            receive.as_mut().poll(&mut task_context),
22027            Poll::Pending
22028        ));
22029        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
22030        assert_eq!(
22031            cursors,
22032            vec![json!({"stream_name": "orders", "through_position": 2})]
22033        );
22034        assert_eq!(
22035            waits,
22036            vec![json!({"stream_name": "orders", "after_position": 2})]
22037        );
22038    }
22039
22040    #[test]
22041    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
22042        let mut empty_map = BTreeMap::new();
22043        let mut nested = BTreeMap::new();
22044        nested.insert(
22045            "value".to_string(),
22046            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
22047        );
22048        let values = vec![
22049            AvroValue::Bytes(vec![0, 255]),
22050            AvroValue::Long(1),
22051            AvroValue::Double(1.0),
22052            AvroValue::Array(Vec::new()),
22053            AvroValue::Map(std::mem::take(&mut empty_map)),
22054            AvroValue::Map(nested),
22055        ];
22056        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
22057        let transport = vec![json!({
22058            "schema": MESSAGE_STREAM_SCHEMA,
22059            "stream_name": "orders",
22060            "message_id": "message-1",
22061            "position": 1,
22062            "payload_envelope": payload,
22063        })];
22064
22065        for _ in 0..2 {
22066            let Some(MessageStreamDelivery::Message(message)) =
22067                decode_message_stream_delivery(transport.clone()).expect("delivery")
22068            else {
22069                panic!("message delivery expected");
22070            };
22071            assert_eq!(message.arguments, values);
22072            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
22073            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
22074        }
22075    }
22076
22077    #[test]
22078    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
22079        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22080            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22081                value.to_string(),
22082            )]))
22083            .expect("message payload");
22084            json!({
22085                "schema": MESSAGE_STREAM_SCHEMA,
22086                "stream_name": "orders",
22087                "message_id": message_id,
22088                "position": position,
22089                "payload_envelope": payload,
22090            })
22091        }
22092
22093        fn opened(sequence: u64) -> HistoryEvent {
22094            history_event(
22095                "SignalWaitOpened",
22096                json!({
22097                    "sequence": sequence,
22098                    "signal_name": MESSAGE_STREAM_SIGNAL,
22099                }),
22100            )
22101        }
22102
22103        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22104            history_event(
22105                "SignalApplied",
22106                json!({
22107                    "sequence": sequence,
22108                    "signal_name": MESSAGE_STREAM_SIGNAL,
22109                    "value": fixture_envelope(json!([delivery])),
22110                }),
22111            )
22112        }
22113
22114        fn worker() -> Worker {
22115            let client = Client::new("http://127.0.0.1:8080").expect("client");
22116            let mut worker = Worker::new(client, "rust-workers");
22117            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
22118                let stream = ctx.message_stream("orders")?;
22119                let first = stream.receive_one().await?;
22120                let second = stream.receive_one().await?;
22121                Ok(json!([first.message_id, second.message_id]))
22122            });
22123            worker
22124        }
22125
22126        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
22127            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
22128            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
22129            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
22130            task
22131        }
22132
22133        let waiting = worker()
22134            .execute_workflow_task_decision(workflow_task(
22135                "rust.message-stream",
22136                Vec::new(),
22137                DEFAULT_CODEC,
22138            ))
22139            .expect("first worker opens the stream wait");
22140        assert_eq!(
22141            waiting.commands,
22142            vec![json!({
22143                "type": "open_signal_wait",
22144                "signal_name": MESSAGE_STREAM_SIGNAL,
22145            })]
22146        );
22147        assert!(waiting.message_stream_cursors.is_empty());
22148        assert_eq!(
22149            waiting.message_stream_waits,
22150            vec![json!({"stream_name": "orders", "after_position": 0})]
22151        );
22152
22153        let first_delivery = delivery("message-1", 1, "one");
22154        let first_arrival = worker()
22155            .execute_workflow_task_decision(task_with_resume(
22156                vec![opened(1)],
22157                first_delivery.clone(),
22158            ))
22159            .expect("replacement worker consumes the first arrival");
22160        assert_eq!(
22161            first_arrival.commands,
22162            vec![json!({
22163                "type": "open_signal_wait",
22164                "signal_name": MESSAGE_STREAM_SIGNAL,
22165            })]
22166        );
22167        assert_eq!(
22168            first_arrival.message_stream_cursors,
22169            vec![json!({"stream_name": "orders", "through_position": 1})]
22170        );
22171        assert_eq!(
22172            first_arrival.message_stream_waits,
22173            vec![json!({"stream_name": "orders", "after_position": 1})]
22174        );
22175
22176        let second_delivery = delivery("message-2", 2, "two");
22177        let first_applied = applied(1, first_delivery);
22178        let completed = worker()
22179            .execute_workflow_task_decision(task_with_resume(
22180                vec![opened(1), first_applied.clone(), opened(2)],
22181                second_delivery.clone(),
22182            ))
22183            .expect("next replacement worker consumes the second arrival");
22184        assert_eq!(completed.commands.len(), 1);
22185        assert_eq!(completed.commands[0]["type"], "complete_workflow");
22186        assert_eq!(
22187            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
22188                .expect("workflow result"),
22189            json!(["message-1", "message-2"])
22190        );
22191        assert_eq!(
22192            completed.message_stream_cursors,
22193            vec![json!({"stream_name": "orders", "through_position": 2})]
22194        );
22195        assert!(completed.message_stream_waits.is_empty());
22196
22197        let replay_history = vec![
22198            opened(1),
22199            first_applied,
22200            opened(2),
22201            applied(2, second_delivery),
22202        ];
22203        for _cold_worker_or_restart in 0..2 {
22204            let replayed = worker()
22205                .execute_workflow_task_decision(workflow_task(
22206                    "rust.message-stream",
22207                    replay_history.clone(),
22208                    DEFAULT_CODEC,
22209                ))
22210                .expect("cold worker replays each logical message exactly once");
22211            assert_eq!(replayed.commands.len(), 1);
22212            assert_eq!(
22213                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
22214                    .expect("replayed workflow result"),
22215                json!(["message-1", "message-2"])
22216            );
22217            assert_eq!(
22218                replayed.message_stream_cursors,
22219                vec![json!({"stream_name": "orders", "through_position": 2})]
22220            );
22221            assert!(replayed.message_stream_waits.is_empty());
22222        }
22223    }
22224
22225    #[test]
22226    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
22227        assert!(!worker_protocol_supports_message_streams("1.14"));
22228        assert!(worker_protocol_supports_message_streams("1.15"));
22229        assert!(worker_protocol_supports_message_streams("1.16"));
22230        assert!(worker_protocol_supports_message_streams(
22231            WORKER_PROTOCOL_VERSION
22232        ));
22233        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
22234    }
22235
22236    #[test]
22237    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
22238        let ctx = workflow_context(vec![
22239            history_event(
22240                "ConditionWaitOpened",
22241                json!({
22242                    "sequence": 1,
22243                    "condition_wait_id": "condition:1",
22244                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22245                    "condition_key": "signal:finish",
22246                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
22247                }),
22248            ),
22249            history_event(
22250                "ConditionWaitSatisfied",
22251                json!({
22252                    "sequence": 1,
22253                    "condition_wait_id": "condition:1",
22254                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22255                    "condition_key": "signal:finish",
22256                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
22257                }),
22258            ),
22259            history_event(
22260                "SignalReceived",
22261                json!({"signal_name": "finish", "arguments": []}),
22262            ),
22263        ]);
22264        let mut signal = Box::pin(ctx.wait_signal("finish"));
22265        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22266
22267        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22268            signal.as_mut().poll(&mut task_context)
22269        else {
22270            panic!("condition history must not resolve as a typed signal wait");
22271        };
22272        assert_eq!(failure.reason, "recorded_command_mismatch");
22273        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
22274    }
22275
22276    #[test]
22277    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
22278        let signal_then_timer = vec![
22279            history_event(
22280                "SignalWaitOpened",
22281                json!({"sequence": 1, "signal_name": "go"}),
22282            ),
22283            history_event(
22284                "SignalApplied",
22285                json!({
22286                    "sequence": 1,
22287                    "signal_name": "go",
22288                    "value": fixture_envelope(json!(["now"])),
22289                }),
22290            ),
22291            history_event(
22292                "TimerScheduled",
22293                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
22294            ),
22295            history_event(
22296                "TimerFired",
22297                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
22298            ),
22299        ];
22300
22301        let ctx = workflow_context(signal_then_timer.clone());
22302        let mut signal = Box::pin(ctx.wait_signal("go"));
22303        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22304        assert!(matches!(
22305            signal.as_mut().poll(&mut task_context),
22306            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
22307        ));
22308        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
22309        assert!(matches!(
22310            timer.as_mut().poll(&mut task_context),
22311            Poll::Ready(Ok(()))
22312        ));
22313        ctx.ensure_history_consumed()
22314            .expect("signal and timer history consumed in order");
22315
22316        let reordered = workflow_context(signal_then_timer);
22317        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
22318        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22319            timer_first.as_mut().poll(&mut task_context)
22320        else {
22321            panic!("timer cannot consume signal-wait-first history");
22322        };
22323        assert_eq!(failure.reason, "recorded_command_mismatch");
22324        assert_eq!(failure.sequence, Some(1));
22325        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
22326
22327        let timer_then_signal = vec![
22328            history_event(
22329                "TimerScheduled",
22330                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22331            ),
22332            history_event(
22333                "TimerFired",
22334                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22335            ),
22336            history_event(
22337                "SignalWaitOpened",
22338                json!({"sequence": 2, "signal_name": "go"}),
22339            ),
22340            history_event(
22341                "SignalApplied",
22342                json!({
22343                    "sequence": 2,
22344                    "signal_name": "go",
22345                    "value": fixture_envelope(json!([])),
22346                }),
22347            ),
22348        ];
22349        let reordered = workflow_context(timer_then_signal);
22350        let mut signal_first = Box::pin(reordered.wait_signal("go"));
22351        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22352            signal_first.as_mut().poll(&mut task_context)
22353        else {
22354            panic!("signal wait cannot consume timer-first history");
22355        };
22356        assert_eq!(failure.reason, "recorded_command_mismatch");
22357        assert_eq!(failure.sequence, Some(1));
22358        assert_eq!(failure.expected.as_deref(), Some("timer"));
22359    }
22360
22361    #[test]
22362    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
22363        let duplicate_timer = WorkflowState::new(
22364            vec![
22365                history_event(
22366                    "TimerScheduled",
22367                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22368                ),
22369                history_event(
22370                    "TimerScheduled",
22371                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
22372                ),
22373            ],
22374            "rust-workers".to_string(),
22375            DEFAULT_CODEC.to_string(),
22376            None,
22377        )
22378        .expect_err("one workflow sequence cannot schedule two timers");
22379        assert!(matches!(
22380            duplicate_timer,
22381            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22382                if reason == "timer_schedule_missing_or_duplicate"
22383        ));
22384
22385        let colliding_kinds = WorkflowState::new(
22386            vec![
22387                history_event(
22388                    "TimerScheduled",
22389                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22390                ),
22391                history_event(
22392                    "ActivityCompleted",
22393                    json!({"sequence": 1, "activity_type": "same-sequence"}),
22394                ),
22395            ],
22396            "rust-workers".to_string(),
22397            DEFAULT_CODEC.to_string(),
22398            None,
22399        )
22400        .expect_err("one workflow sequence cannot identify two command kinds");
22401        assert!(matches!(
22402            colliding_kinds,
22403            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22404                if reason == "durable_command_sequence_collision"
22405        ));
22406
22407        let duplicate_signal_wait = WorkflowState::new(
22408            vec![
22409                history_event(
22410                    "SignalWaitOpened",
22411                    json!({"sequence": 1, "signal_name": "go"}),
22412                ),
22413                history_event(
22414                    "SignalWaitOpened",
22415                    json!({"sequence": 1, "signal_name": "go"}),
22416                ),
22417            ],
22418            "rust-workers".to_string(),
22419            DEFAULT_CODEC.to_string(),
22420            None,
22421        )
22422        .expect_err("one workflow sequence cannot open two signal waits");
22423        assert!(matches!(
22424            duplicate_signal_wait,
22425            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22426                if reason == "signal_wait_open_missing_or_duplicate"
22427        ));
22428    }
22429
22430    #[test]
22431    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
22432        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
22433            .expect("side-effect result");
22434        let ctx = workflow_context(vec![history_event(
22435            "SideEffectRecorded",
22436            json!({"sequence": 99, "result": result}),
22437        )]);
22438
22439        let replayed: Value = ctx
22440            .side_effect(|| panic!("recorded side effect must not run"))
22441            .expect("positive global workflow sequence is valid");
22442        assert_eq!(replayed, json!({"captured": true}));
22443        ctx.ensure_history_consumed().expect("history consumed");
22444    }
22445
22446    #[test]
22447    fn workflow_history_rejects_zero_and_descending_command_sequences() {
22448        let result =
22449            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
22450        let zero = WorkflowState::new(
22451            vec![history_event(
22452                "SideEffectRecorded",
22453                json!({"sequence": 0, "result": result.clone()}),
22454            )],
22455            "rust-workers".to_string(),
22456            DEFAULT_CODEC.to_string(),
22457            None,
22458        )
22459        .expect_err("durable command sequences must be positive");
22460        assert!(matches!(
22461            zero,
22462            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22463                if reason == "durable_command_sequence_invalid"
22464        ));
22465
22466        let descending = WorkflowState::new(
22467            vec![
22468                history_event(
22469                    "SideEffectRecorded",
22470                    json!({"sequence": 3, "result": result}),
22471                ),
22472                history_event(
22473                    "VersionMarkerRecorded",
22474                    json!({
22475                        "sequence": 2,
22476                        "change_id": "descending-marker",
22477                        "version": 1,
22478                        "min_supported": 1,
22479                        "max_supported": 1,
22480                    }),
22481                ),
22482            ],
22483            "rust-workers".to_string(),
22484            DEFAULT_CODEC.to_string(),
22485            None,
22486        )
22487        .expect_err("new durable commands must remain strictly ordered");
22488        let Error::NonDeterministicReplay(failure) = descending else {
22489            panic!("expected typed replay failure");
22490        };
22491        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
22492        assert_eq!(failure.sequence, Some(2));
22493        assert_eq!(
22494            failure.expected.as_deref(),
22495            Some("workflow sequence greater than 3")
22496        );
22497        assert_eq!(failure.actual.as_deref(), Some("2"));
22498    }
22499
22500    #[test]
22501    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
22502        fn worker() -> Worker {
22503            let client = Client::new("http://127.0.0.1:8080").expect("client");
22504            let mut worker = Worker::new(client, "rust-workers");
22505            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
22506                ctx.wait_signal("finish").await?;
22507                let marker: String =
22508                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
22509                assert_eq!(marker, "after-finish");
22510                Ok(json!("finished"))
22511            });
22512            worker
22513        }
22514
22515        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
22516            .expect("side-effect result");
22517        let task = workflow_task(
22518            "rust.finish-after-gaps",
22519            vec![
22520                history_event(
22521                    "SignalWaitOpened",
22522                    json!({"sequence": 1, "signal_name": "finish"}),
22523                ),
22524                history_event(
22525                    "SignalReceived",
22526                    json!({
22527                        "signal_id": "increment-3",
22528                        "signal_name": "increment",
22529                        "workflow_sequence": 2,
22530                        "payload_codec": DEFAULT_CODEC,
22531                        "arguments": fixture_envelope(json!([3])),
22532                    }),
22533                ),
22534                history_event(
22535                    "SignalReceived",
22536                    json!({
22537                        "signal_id": "increment-5",
22538                        "signal_name": "increment",
22539                        "workflow_sequence": 3,
22540                        "payload_codec": DEFAULT_CODEC,
22541                        "arguments": fixture_envelope(json!([5])),
22542                    }),
22543                ),
22544                history_event(
22545                    "SignalReceived",
22546                    json!({
22547                        "signal_id": "finish",
22548                        "signal_name": "finish",
22549                        "workflow_sequence": 4,
22550                        "payload_codec": DEFAULT_CODEC,
22551                        "arguments": fixture_envelope(json!([])),
22552                    }),
22553                ),
22554                history_event(
22555                    "SignalApplied",
22556                    json!({
22557                        "sequence": 1,
22558                        "signal_id": "finish",
22559                        "signal_name": "finish",
22560                        "payload_codec": DEFAULT_CODEC,
22561                        "value": fixture_envelope(json!([])),
22562                    }),
22563                ),
22564                history_event(
22565                    "SideEffectRecorded",
22566                    json!({"sequence": 5, "result": marker}),
22567                ),
22568            ],
22569            DEFAULT_CODEC,
22570        );
22571
22572        for _original_or_cold_worker in 0..2 {
22573            let commands = worker()
22574                .execute_workflow_task(task.clone())
22575                .expect("signal gaps preserve deterministic replay");
22576            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
22577            assert_eq!(commands[0]["type"], "complete_workflow");
22578            assert_eq!(
22579                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
22580                json!("finished")
22581            );
22582        }
22583    }
22584
22585    #[test]
22586    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
22587        let ctx = workflow_context(Vec::new());
22588        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
22589        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22590        assert!(matches!(
22591            sleep.as_mut().poll(&mut task_context),
22592            Poll::Ready(Err(Error::TimerDurationOverflow))
22593        ));
22594        assert!(ctx.take_commands().expect("commands").is_empty());
22595    }
22596
22597    #[test]
22598    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
22599        let entries = AvroValue::Map(BTreeMap::from([
22600            ("text".to_string(), AvroValue::String("same".to_string())),
22601            (
22602                "nested".to_string(),
22603                AvroValue::Map(BTreeMap::from([
22604                    ("beta".to_string(), AvroValue::Long(2)),
22605                    ("alpha".to_string(), AvroValue::Long(1)),
22606                ])),
22607            ),
22608            ("long".to_string(), AvroValue::Long(7)),
22609            ("double".to_string(), AvroValue::Double(7.0)),
22610            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
22611        ]));
22612        let ctx = workflow_context(Vec::new());
22613        ctx.upsert_memo(entries.clone()).expect("valid memo update");
22614        let commands = ctx.take_commands().expect("commands");
22615
22616        assert_eq!(commands.len(), 1);
22617        assert_eq!(commands[0]["type"], "upsert_memo");
22618        let server_entries = json!({
22619            "codec": "avro",
22620            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
22621        });
22622        assert_eq!(
22623            commands[0]["entries"]
22624                .as_object()
22625                .expect("entries envelope")
22626                .keys()
22627                .collect::<Vec<_>>(),
22628            vec!["blob", "codec"]
22629        );
22630        assert_eq!(commands[0]["entries"], server_entries);
22631        let wire_entries =
22632            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
22633        assert_eq!(wire_entries, entries);
22634
22635        let history = vec![history_event(
22636            "MemoUpserted",
22637            json!({
22638                "sequence": 1,
22639                "entries": server_entries.clone(),
22640                "merged": server_entries,
22641            }),
22642        )];
22643        let replay = workflow_context(history.clone());
22644        replay
22645            .upsert_memo(entries.clone())
22646            .expect("matching replay identity");
22647        assert!(replay.take_commands().expect("replay commands").is_empty());
22648
22649        let changed_types = AvroValue::Map(BTreeMap::from([
22650            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
22651            (
22652                "nested".to_string(),
22653                AvroValue::Map(BTreeMap::from([
22654                    ("alpha".to_string(), AvroValue::Long(1)),
22655                    ("beta".to_string(), AvroValue::Long(2)),
22656                ])),
22657            ),
22658            ("long".to_string(), AvroValue::Double(7.0)),
22659            ("double".to_string(), AvroValue::Long(7)),
22660            ("binary".to_string(), AvroValue::String("same".to_string())),
22661        ]));
22662        let error = workflow_context(history)
22663            .upsert_memo(changed_types)
22664            .expect_err("memo replay identity must preserve Avro value types");
22665        assert!(matches!(
22666            error,
22667            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
22668        ));
22669    }
22670
22671    #[test]
22672    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
22673        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
22674            .expect("memo envelope");
22675        let replay = workflow_context(vec![history_event(
22676            "MemoUpserted",
22677            json!({
22678                "sequence": 1,
22679                "entries": original.clone(),
22680                "merged": original
22681            }),
22682        )]);
22683        let error = replay
22684            .upsert_memo(json!({"stage": "changed"}))
22685            .expect_err("changed memo update must fail replay");
22686        assert!(matches!(
22687            error,
22688            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
22689        ));
22690
22691        let invalid = workflow_context(Vec::new())
22692            .upsert_memo(
22693                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
22694            )
22695            .expect_err("oversized key");
22696        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
22697    }
22698
22699    #[test]
22700    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
22701        let negative_zero = AvroValue::Map(BTreeMap::from([(
22702            "reading".to_string(),
22703            AvroValue::Double(-0.0),
22704        )]));
22705        let negative_zero_envelope =
22706            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
22707        let history = vec![history_event(
22708            "MemoUpserted",
22709            json!({
22710                "sequence": 1,
22711                "entries": negative_zero_envelope.clone(),
22712                "merged": negative_zero_envelope,
22713            }),
22714        )];
22715
22716        workflow_context(history.clone())
22717            .upsert_memo(negative_zero)
22718            .expect("matching negative-zero history identity");
22719
22720        let error = workflow_context(history)
22721            .upsert_memo(AvroValue::Map(BTreeMap::from([(
22722                "reading".to_string(),
22723                AvroValue::Double(0.0),
22724            )])))
22725            .expect_err("positive zero must not consume negative-zero memo history");
22726        assert!(matches!(
22727            error,
22728            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
22729        ));
22730    }
22731
22732    #[test]
22733    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
22734        let supported = json!({
22735            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
22736            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
22737        });
22738        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
22739        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
22740            "workflow_memo_updates": {"supported": false},
22741            "supported_workflow_task_commands": ["upsert_memo"]
22742        }))));
22743        assert!(commands_use_workflow_memo_updates(&[json!({
22744            "type": "upsert_memo",
22745            "entries": {"stage": "processing"}
22746        })]));
22747    }
22748
22749    #[test]
22750    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
22751        let client = Client::new("http://127.0.0.1:8080").expect("client");
22752        let mut worker = Worker::new(client, "rust-workers");
22753        worker.register_workflow("rust.timer", |ctx, _input| async move {
22754            ctx.sleep(Duration::from_secs(5)).await?;
22755            ctx.activity("after-timer", json!([])).await
22756        });
22757
22758        let task = |history_events| WorkflowTask {
22759            task_id: "wft-rust-timer-1".to_string(),
22760            workflow_command_id: None,
22761            workflow_id: Some("wf-rust-timer".to_string()),
22762            run_id: Some("run-rust-timer".to_string()),
22763            workflow_type: "rust.timer".to_string(),
22764            cancel_requested: false,
22765            payload_codec: DEFAULT_CODEC.to_string(),
22766            arguments: Some(
22767                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
22768            ),
22769            history_events,
22770            total_history_events: None,
22771            history_size_bytes: None,
22772            continue_as_new_recommended: None,
22773            history_budget_pressure: None,
22774            next_history_page_token: None,
22775            workflow_task_attempt: 1,
22776            workflow_signal_id: None,
22777            signal_name: None,
22778            signal_arguments: None,
22779            workflow_update_id: None,
22780            update_name: None,
22781            lease_owner: Some("rust-worker".to_string()),
22782        };
22783
22784        let initial = worker
22785            .execute_workflow_task(task(Vec::new()))
22786            .expect("initial timer task");
22787        assert_eq!(
22788            initial,
22789            vec![json!({"type": "start_timer", "delay_seconds": 5})]
22790        );
22791
22792        let activity_result =
22793            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
22794        let replayed = worker
22795            .execute_workflow_task(task(vec![
22796                history_event(
22797                    "TimerScheduled",
22798                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22799                ),
22800                history_event(
22801                    "TimerFired",
22802                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22803                ),
22804                history_event(
22805                    "ActivityCompleted",
22806                    json!({
22807                        "sequence": 2,
22808                        "activity_type": "after-timer",
22809                        "payload_codec": DEFAULT_CODEC,
22810                        "result": activity_result,
22811                    }),
22812                ),
22813            ]))
22814            .expect("replayed workflow task");
22815        assert_eq!(replayed.len(), 1);
22816        assert_eq!(replayed[0]["type"], "complete_workflow");
22817        assert_eq!(
22818            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
22819            json!("done")
22820        );
22821    }
22822
22823    #[test]
22824    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
22825        let client = Client::new("http://127.0.0.1:8080").expect("client");
22826        let mut worker = Worker::new(client, "rust-workers");
22827        worker.register_workflow("rust.continue", |ctx, _input| async move {
22828            ctx.continue_as_new_with_options(
22829                ContinueAsNewOptions::new()
22830                    .workflow_type("rust.next")
22831                    .task_queue("next-workers"),
22832                json!([2, {"cursor": "next"}]),
22833            )
22834        });
22835
22836        let commands = worker
22837            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
22838            .expect("continue-as-new command");
22839
22840        assert_eq!(commands.len(), 1);
22841        assert_eq!(commands[0]["type"], "continue_as_new");
22842        assert_eq!(commands[0]["workflow_type"], "rust.next");
22843        assert_eq!(commands[0]["queue"], "next-workers");
22844        assert_eq!(
22845            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
22846                .expect("continue-as-new arguments"),
22847            json!([2, {"cursor": "next"}])
22848        );
22849    }
22850
22851    #[test]
22852    fn continue_as_new_preserves_typed_arguments() {
22853        let client = Client::new("http://127.0.0.1:8080").expect("client");
22854        let mut worker = Worker::new(client, "rust-workers");
22855        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
22856            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
22857            unreachable!("continue-as-new returns a control-flow error")
22858        });
22859
22860        let commands = worker
22861            .execute_workflow_task(workflow_task(
22862                "rust.typed-continue",
22863                Vec::new(),
22864                DEFAULT_CODEC,
22865            ))
22866            .expect("typed continue-as-new command");
22867
22868        assert_eq!(commands[0]["type"], "continue_as_new");
22869        assert_eq!(
22870            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
22871                .expect("typed continue arguments"),
22872            AvroValue::Array(vec![typed_fidelity_probe()])
22873        );
22874    }
22875
22876    #[test]
22877    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
22878        let client = Client::new("http://127.0.0.1:8080").expect("client");
22879        let mut worker = Worker::new(client, "rust-workers");
22880        worker.register_workflow("rust.continue", |ctx, _input| async move {
22881            ctx.continue_as_new(json!([2]))
22882        });
22883        let task = workflow_task(
22884            "rust.continue",
22885            vec![history_event(
22886                "WorkflowContinuedAsNew",
22887                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
22888            )],
22889            DEFAULT_CODEC,
22890        );
22891
22892        for _worker_restart_or_redelivery in 0..2 {
22893            let commands = worker
22894                .execute_workflow_task(task.clone())
22895                .expect("recorded transition replays");
22896            assert!(
22897                commands.is_empty(),
22898                "replay must not emit another successor"
22899            );
22900        }
22901    }
22902
22903    #[test]
22904    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
22905        let ctx = workflow_context(Vec::new());
22906        let error = ctx
22907            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
22908            .expect_err("blank queue must be rejected");
22909
22910        let Error::InvalidContinueAsNewOptions(error) = error else {
22911            panic!("expected typed continue-as-new validation error");
22912        };
22913        assert_eq!(error.field, "task_queue");
22914        assert!(ctx.take_commands().expect("commands").is_empty());
22915    }
22916
22917    #[test]
22918    fn workflow_context_exposes_server_history_budget() {
22919        let client = Client::new("http://127.0.0.1:8080").expect("client");
22920        let mut worker = Worker::new(client, "rust-workers");
22921        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
22922            let budget = ctx.history_budget()?;
22923            Ok(json!({
22924                "events": budget.event_count,
22925                "bytes": budget.size_bytes,
22926                "recommended": budget.continue_as_new_recommended,
22927                "pressure": budget.pressure,
22928            }))
22929        });
22930        let task: WorkflowTask = serde_json::from_value(json!({
22931            "task_id": "task-history-budget",
22932            "workflow_type": "rust.history-budget",
22933            "payload_codec": DEFAULT_CODEC,
22934            "history_events": [],
22935            "total_history_events": 480,
22936            "history_size_bytes": 1_048_576,
22937            "continue_as_new_recommended": true,
22938            "history_budget_pressure": "continue_as_new_recommended",
22939        }))
22940        .expect("published workflow task");
22941
22942        let commands = worker
22943            .execute_workflow_task(task)
22944            .expect("history-budget workflow");
22945        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
22946        assert_eq!(result["events"], 480);
22947        assert_eq!(result["bytes"], 1_048_576);
22948        assert_eq!(result["recommended"], true);
22949        assert_eq!(result["pressure"], "continue_as_new_recommended");
22950    }
22951
22952    #[test]
22953    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
22954        let client = Client::new("http://127.0.0.1:8080").expect("client");
22955        let mut worker = Worker::new(client, "rust-workers");
22956        worker.register_workflow("rust.failing", |_ctx, _input| async move {
22957            Err(Error::Codec("rust_conformance_failure".to_string()))
22958        });
22959        let task = WorkflowTask {
22960            task_id: "wft-rust-failing-1".to_string(),
22961            workflow_command_id: None,
22962            workflow_id: Some("wf-rust-failing".to_string()),
22963            run_id: Some("run-rust-failing".to_string()),
22964            workflow_type: "rust.failing".to_string(),
22965            cancel_requested: false,
22966            payload_codec: DEFAULT_CODEC.to_string(),
22967            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
22968            history_events: Vec::new(),
22969            total_history_events: Some(0),
22970            history_size_bytes: None,
22971            continue_as_new_recommended: None,
22972            history_budget_pressure: None,
22973            next_history_page_token: None,
22974            workflow_task_attempt: 1,
22975            workflow_signal_id: None,
22976            signal_name: None,
22977            signal_arguments: None,
22978            workflow_update_id: None,
22979            update_name: None,
22980            lease_owner: Some("rust-worker".to_string()),
22981        };
22982
22983        let commands = worker
22984            .execute_workflow_task(task)
22985            .expect("handler failure becomes a workflow command");
22986
22987        assert_eq!(commands.len(), 1);
22988        assert_eq!(commands[0]["type"], "fail_workflow");
22989        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
22990        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
22991        assert_eq!(commands[0]["non_retryable"], false);
22992        assert_eq!(
22993            commands[0]["message"],
22994            "codec error: rust_conformance_failure"
22995        );
22996        assert_eq!(
22997            commands[0]["exception"]["message"],
22998            "codec error: rust_conformance_failure"
22999        );
23000    }
23001
23002    #[test]
23003    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
23004        let client = Client::new("http://127.0.0.1:8080").expect("client");
23005        let mut worker = Worker::new(client, "rust-workers");
23006        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
23007            let _: String = ctx.side_effect(|| "captured".to_string())?;
23008            Err(Error::WorkerLoop("application failure".to_string()))
23009        });
23010
23011        let commands = worker
23012            .execute_workflow_task(workflow_task(
23013                "rust.failing-after-side-effect",
23014                Vec::new(),
23015                DEFAULT_CODEC,
23016            ))
23017            .expect("ordinary failure remains a workflow decision");
23018
23019        assert_eq!(commands.len(), 2);
23020        assert_eq!(commands[0]["type"], "record_side_effect");
23021        assert_eq!(commands[1]["type"], "fail_workflow");
23022    }
23023
23024    #[test]
23025    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
23026        let client = Client::new("http://127.0.0.1:8080").expect("client");
23027        let mut worker = Worker::new(client, "rust-workers");
23028        worker.register_workflow("rust.redrive", |ctx, _input| async move {
23029            ctx.activity("greet", json!([])).await?;
23030            Ok(Value::Null)
23031        });
23032        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
23033            match ctx.activity("greet", json!([])).await {
23034                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
23035                result => result,
23036            }
23037        });
23038
23039        let failed = history_event(
23040            "ActivityFailed",
23041            json!({
23042                "sequence": 1,
23043                "activity_type": "greet",
23044                "activity_execution_id": "activity-1",
23045                "message": "failed"
23046            }),
23047        );
23048        let commands = worker
23049            .execute_workflow_task(workflow_task(
23050                "rust.redrive",
23051                vec![failed.clone()],
23052                DEFAULT_CODEC,
23053            ))
23054            .expect("recorded failure becomes a workflow command");
23055        assert_eq!(commands[0]["type"], "fail_workflow");
23056        assert_eq!(commands[0]["failed_step_sequence"], 1);
23057        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
23058
23059        let translated = worker
23060            .execute_workflow_task(workflow_task(
23061                "rust.redrive-translated",
23062                vec![failed],
23063                DEFAULT_CODEC,
23064            ))
23065            .expect("translated failure becomes a workflow command");
23066        assert_eq!(translated[0]["type"], "fail_workflow");
23067        assert!(translated[0].get("failed_step_sequence").is_none());
23068        assert!(translated[0].get("failed_activity_execution_id").is_none());
23069
23070        let without_identity = worker
23071            .execute_workflow_task(workflow_task(
23072                "rust.redrive",
23073                vec![history_event(
23074                    "ActivityFailed",
23075                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
23076                )],
23077                DEFAULT_CODEC,
23078            ))
23079            .expect("incomplete identity still fails the workflow");
23080        assert!(without_identity[0].get("failed_step_sequence").is_none());
23081
23082        let timed_out = worker
23083            .execute_workflow_task(workflow_task(
23084                "rust.redrive",
23085                vec![history_event(
23086                    "ActivityTimedOut",
23087                    json!({
23088                        "sequence": 1,
23089                        "activity_type": "greet",
23090                        "activity_execution_id": "activity-timeout",
23091                    }),
23092                )],
23093                DEFAULT_CODEC,
23094            ))
23095            .expect("timeout still fails the workflow");
23096        assert!(timed_out[0].get("failed_step_sequence").is_none());
23097    }
23098
23099    #[test]
23100    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
23101        let client = Client::new("http://127.0.0.1:8080").expect("client");
23102        let mut worker = Worker::new(client, "rust-workers");
23103        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
23104            let first = ctx.activity("first", json!([])).await?;
23105            let second = ctx.activity("second", json!([first.clone()])).await?;
23106            Ok(json!({"first": first, "second": second}))
23107        });
23108        let first = history_event(
23109            "ActivityCompleted",
23110            json!({
23111                "sequence": 1,
23112                "activity_type": "first",
23113                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
23114                "payload_codec": DEFAULT_CODEC,
23115                "reused_from_run_id": "failed-run",
23116                "reused_activity_execution_id": "original-first",
23117            }),
23118        );
23119
23120        let retry = worker
23121            .execute_workflow_task(workflow_task(
23122                "rust.redrive-successor",
23123                vec![first.clone()],
23124                DEFAULT_CODEC,
23125            ))
23126            .expect("reused result replays before failed step");
23127        assert_eq!(retry.len(), 1);
23128        assert_eq!(retry[0]["type"], "schedule_activity");
23129        assert_eq!(retry[0]["activity_type"], "second");
23130        assert_eq!(
23131            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
23132            json!(["recorded"]),
23133        );
23134
23135        let second = history_event(
23136            "ActivityCompleted",
23137            json!({
23138                "sequence": 2,
23139                "activity_type": "second",
23140                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
23141                "payload_codec": DEFAULT_CODEC,
23142            }),
23143        );
23144        let completed = worker
23145            .execute_workflow_task(workflow_task(
23146                "rust.redrive-successor",
23147                vec![first, second],
23148                DEFAULT_CODEC,
23149            ))
23150            .expect("retried step completes the successor");
23151        assert_eq!(completed.len(), 1);
23152        assert_eq!(completed[0]["type"], "complete_workflow");
23153        assert_eq!(
23154            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
23155            json!({"first": "recorded", "second": "retried"}),
23156        );
23157    }
23158
23159    #[test]
23160    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
23161        let client = Client::new("http://127.0.0.1:8080").expect("client");
23162        let mut worker = Worker::new(client, "rust-workers");
23163        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
23164            Err(Error::WorkerLoop("application failure".to_string()))
23165        });
23166        let result =
23167            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
23168
23169        let error = worker
23170            .execute_workflow_task(workflow_task(
23171                "rust.removed-side-effect",
23172                vec![history_event(
23173                    "SideEffectRecorded",
23174                    json!({"sequence": 1, "result": result}),
23175                )],
23176                DEFAULT_CODEC,
23177            ))
23178            .expect_err("removed committed history must not become fail_workflow");
23179
23180        let Error::NonDeterministicReplay(failure) = error else {
23181            panic!("expected typed replay failure");
23182        };
23183        assert_eq!(failure.reason, "recorded_commands_unconsumed");
23184        assert_eq!(failure.sequence, Some(1));
23185        assert_eq!(failure.expected.as_deref(), Some("side effect"));
23186    }
23187
23188    #[test]
23189    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
23190        let client = Client::new("http://127.0.0.1:8080").expect("client");
23191        let mut worker = Worker::new(client, "rust-workers");
23192        worker.register_workflow(
23193            "rust.side-effect-before-marker-error",
23194            |ctx, _input| async move {
23195                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
23196                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
23197                ctx.get_version("restart-safe", 2, 2)?;
23198                Ok(Value::Null)
23199            },
23200        );
23201
23202        let error = worker
23203            .execute_workflow_task(workflow_task(
23204                "rust.side-effect-before-marker-error",
23205                vec![history_event(
23206                    "VersionMarkerRecorded",
23207                    json!({
23208                        "sequence": 1,
23209                        "change_id": "restart-safe",
23210                        "version": 1,
23211                        "min_supported": 1,
23212                        "max_supported": 1,
23213                    }),
23214                )],
23215                DEFAULT_CODEC,
23216            ))
23217            .expect_err("replay error must return no queued workflow commands");
23218
23219        let Error::NonDeterministicReplay(failure) = error else {
23220            panic!("expected typed replay failure");
23221        };
23222        assert_eq!(failure.reason, "version_marker_incompatible_range");
23223        assert_eq!(failure.sequence, Some(1));
23224    }
23225
23226    #[test]
23227    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
23228        let client = Client::new("http://127.0.0.1:8080").expect("client");
23229        let mut worker = Worker::new(client, "rust-workers");
23230        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
23231            ctx.sleep(Duration::from_secs(5)).await?;
23232            Ok(json!({"status": "timer fired"}))
23233        });
23234
23235        let task = WorkflowTask {
23236            task_id: "wft-rust-timer-pending".to_string(),
23237            workflow_command_id: None,
23238            workflow_id: Some("wf-rust-timer".to_string()),
23239            run_id: Some("run-rust-timer".to_string()),
23240            workflow_type: "rust.timer.pending".to_string(),
23241            cancel_requested: false,
23242            payload_codec: DEFAULT_CODEC.to_string(),
23243            arguments: Some(
23244                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23245            ),
23246            history_events: vec![history_event(
23247                "TimerScheduled",
23248                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23249            )],
23250            total_history_events: Some(1),
23251            history_size_bytes: None,
23252            continue_as_new_recommended: None,
23253            history_budget_pressure: None,
23254            next_history_page_token: None,
23255            workflow_task_attempt: 1,
23256            workflow_signal_id: None,
23257            signal_name: None,
23258            signal_arguments: None,
23259            workflow_update_id: None,
23260            update_name: None,
23261            lease_owner: Some("rust-worker".to_string()),
23262        };
23263
23264        for _redelivery_or_restart in 0..2 {
23265            let commands = worker
23266                .execute_workflow_task(task.clone())
23267                .expect("recorded timer remains pending");
23268            assert!(
23269                commands.is_empty(),
23270                "recorded timer must not be rescheduled"
23271            );
23272        }
23273    }
23274
23275    #[test]
23276    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
23277        let client = Client::new("http://127.0.0.1:8080").expect("client");
23278        let mut worker = Worker::new(client, "rust-workers");
23279        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
23280            Ok(json!({"status": "completed"}))
23281        });
23282        let task = WorkflowTask {
23283            task_id: "wft-rust-timer-removed".to_string(),
23284            workflow_command_id: None,
23285            workflow_id: Some("wf-rust-timer".to_string()),
23286            run_id: Some("run-rust-timer".to_string()),
23287            workflow_type: "rust.timer.removed".to_string(),
23288            cancel_requested: false,
23289            payload_codec: DEFAULT_CODEC.to_string(),
23290            arguments: Some(
23291                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23292            ),
23293            history_events: vec![
23294                history_event(
23295                    "TimerScheduled",
23296                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23297                ),
23298                history_event(
23299                    "TimerFired",
23300                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23301                ),
23302            ],
23303            total_history_events: Some(2),
23304            history_size_bytes: None,
23305            continue_as_new_recommended: None,
23306            history_budget_pressure: None,
23307            next_history_page_token: None,
23308            workflow_task_attempt: 1,
23309            workflow_signal_id: None,
23310            signal_name: None,
23311            signal_arguments: None,
23312            workflow_update_id: None,
23313            update_name: None,
23314            lease_owner: Some("rust-worker".to_string()),
23315        };
23316
23317        let Error::NonDeterministicReplay(failure) = worker
23318            .execute_workflow_task(task)
23319            .expect_err("removed timer must fail replay")
23320        else {
23321            panic!("expected typed replay failure");
23322        };
23323        assert_eq!(failure.reason, "recorded_commands_unconsumed");
23324        assert_eq!(failure.sequence, Some(1));
23325    }
23326
23327    #[test]
23328    fn workflow_context_emits_explicit_child_workflow_contract() {
23329        let ctx = WorkflowContext {
23330            cancellation_scope_id: "root".into(),
23331            state: Arc::new(Mutex::new(
23332                WorkflowState::new_with_identity(
23333                    Vec::new(),
23334                    Some("wf-parent".to_string()),
23335                    Some("run-parent".to_string()),
23336                    "parent-workers".to_string(),
23337                    DEFAULT_CODEC.to_string(),
23338                    None,
23339                )
23340                .expect("workflow state"),
23341            )),
23342        };
23343        let options = ChildWorkflowOptions::new("python-workers")
23344            .parent_close_policy(ParentClosePolicy::RequestCancel)
23345            .retry_policy(ChildWorkflowRetryPolicy {
23346                max_attempts: Some(3),
23347                backoff_seconds: vec![1, 5],
23348                non_retryable_error_types: vec!["ValidationError".to_string()],
23349            })
23350            .execution_timeout_seconds(600)
23351            .run_timeout_seconds(120);
23352        let mut call = Box::pin(ctx.start_child_workflow(
23353            "python.fulfil-order",
23354            options,
23355            json!([{"order_id": "order-42"}]),
23356        ));
23357        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23358
23359        assert!(matches!(
23360            call.as_mut().poll(&mut task_context),
23361            Poll::Pending
23362        ));
23363        let commands = ctx.take_commands().expect("commands");
23364        assert_eq!(commands.len(), 1);
23365        let command = &commands[0];
23366        assert_eq!(command["type"], "start_child_workflow");
23367        assert_eq!(command["workflow_type"], "python.fulfil-order");
23368        assert_eq!(command["queue"], "python-workers");
23369        assert_eq!(command["parent_close_policy"], "request_cancel");
23370        assert_eq!(command["retry_policy"]["max_attempts"], 3);
23371        assert_eq!(command["execution_timeout_seconds"], 600);
23372        assert_eq!(command["run_timeout_seconds"], 120);
23373        assert_eq!(
23374            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
23375            json!([{"order_id": "order-42"}])
23376        );
23377    }
23378
23379    fn child_parent_worker() -> Worker {
23380        let client = Client::new("http://127.0.0.1:8080").expect("client");
23381        let mut worker = Worker::new(client, "rust-parent-workers");
23382        worker.register_workflow("rust.parent", |ctx, _input| async move {
23383            let child = ctx
23384                .start_child_workflow(
23385                    "python.child",
23386                    ChildWorkflowOptions::new("python-child-workers")
23387                        .parent_close_policy(ParentClosePolicy::Terminate),
23388                    json!([{"codec_probe": [1, true, "rust"]}]),
23389                )
23390                .await?;
23391            Ok(json!({
23392                "parent_workflow_id": child.parent.workflow_id,
23393                "parent_run_id": child.parent.run_id,
23394                "child_workflow_id": child.child.workflow_id,
23395                "child_run_id": child.child.run_id,
23396                "child_workflow_type": child.child_workflow_type,
23397                "result": child.result,
23398            }))
23399        });
23400        worker
23401    }
23402
23403    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
23404        WorkflowTask {
23405            task_id: "wft-child-parent".to_string(),
23406            workflow_command_id: None,
23407            workflow_id: Some("wf-parent".to_string()),
23408            run_id: Some("run-parent".to_string()),
23409            workflow_type: "rust.parent".to_string(),
23410            cancel_requested: false,
23411            payload_codec: DEFAULT_CODEC.to_string(),
23412            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
23413            history_events: vec![
23414                HistoryEvent {
23415                    event_type: "ChildWorkflowScheduled".to_string(),
23416                    payload: json!({
23417                        "sequence": 1,
23418                        "child_call_id": "call-child",
23419                        "child_workflow_instance_id": "wf-child",
23420                        "child_workflow_run_id": "run-child",
23421                        "child_workflow_type": "python.child",
23422                        "parent_close_policy": "terminate",
23423                    }),
23424                    raw: HashMap::new(),
23425                },
23426                HistoryEvent {
23427                    event_type: event_type.to_string(),
23428                    payload,
23429                    raw: HashMap::new(),
23430                },
23431            ],
23432            total_history_events: Some(2),
23433            history_size_bytes: None,
23434            continue_as_new_recommended: None,
23435            history_budget_pressure: None,
23436            next_history_page_token: None,
23437            workflow_task_attempt: 1,
23438            workflow_signal_id: None,
23439            signal_name: None,
23440            signal_arguments: None,
23441            workflow_update_id: None,
23442            update_name: None,
23443            lease_owner: Some("rust-worker".to_string()),
23444        }
23445    }
23446
23447    #[test]
23448    fn committed_child_result_replays_without_starting_a_duplicate() {
23449        let worker = child_parent_worker();
23450        let task = child_parent_task(
23451            "ChildRunCompleted",
23452            json!({
23453                "sequence": 1,
23454                "child_call_id": "call-child",
23455                "child_workflow_instance_id": "wf-child",
23456                "child_workflow_run_id": "run-child",
23457                "child_workflow_type": "python.child",
23458                "payload_codec": DEFAULT_CODEC,
23459                "result": fixture_envelope(json!({"from":"python","ok":true})),
23460            }),
23461        );
23462
23463        for _restart in 0..2 {
23464            let commands = worker
23465                .execute_workflow_task(task.clone())
23466                .expect("replayed parent task");
23467            assert_eq!(commands.len(), 1);
23468            assert_eq!(commands[0]["type"], "complete_workflow");
23469            assert!(!commands
23470                .iter()
23471                .any(|command| command["type"] == "start_child_workflow"));
23472            let output =
23473                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
23474            assert_eq!(output["parent_workflow_id"], "wf-parent");
23475            assert_eq!(output["parent_run_id"], "run-parent");
23476            assert_eq!(output["child_workflow_id"], "wf-child");
23477            assert_eq!(output["child_run_id"], "run-child");
23478            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
23479        }
23480    }
23481
23482    #[test]
23483    fn typed_child_arguments_and_results_survive_replay() {
23484        let client = Client::new("http://127.0.0.1:8080").expect("client");
23485        let mut worker = Worker::new(client, "rust-parent-workers");
23486        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
23487            let child = ctx
23488                .start_child_workflow_avro_value(
23489                    "python.typed-child",
23490                    ChildWorkflowOptions::new("python-workers"),
23491                    AvroValue::Array(vec![typed_fidelity_probe()]),
23492                )
23493                .await?;
23494            Ok(child.result)
23495        });
23496
23497        let initial = worker
23498            .execute_workflow_task(workflow_task(
23499                "rust.typed-parent",
23500                Vec::new(),
23501                DEFAULT_CODEC,
23502            ))
23503            .expect("typed child start");
23504        assert_eq!(initial[0]["type"], "start_child_workflow");
23505        assert_eq!(
23506            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
23507                .expect("typed child arguments"),
23508            AvroValue::Array(vec![typed_fidelity_probe()])
23509        );
23510
23511        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
23512            .expect("typed child result");
23513        let task = workflow_task(
23514            "rust.typed-parent",
23515            vec![
23516                history_event(
23517                    "ChildWorkflowScheduled",
23518                    json!({
23519                        "sequence": 1,
23520                        "child_call_id": "call-typed",
23521                        "child_workflow_instance_id": "wf-child",
23522                        "child_workflow_run_id": "run-child",
23523                        "child_workflow_type": "python.typed-child",
23524                    }),
23525                ),
23526                history_event(
23527                    "ChildRunCompleted",
23528                    json!({
23529                        "sequence": 1,
23530                        "child_call_id": "call-typed",
23531                        "child_workflow_instance_id": "wf-child",
23532                        "child_workflow_run_id": "run-child",
23533                        "child_workflow_type": "python.typed-child",
23534                        "payload_codec": DEFAULT_CODEC,
23535                        "result": result,
23536                    }),
23537                ),
23538            ],
23539            DEFAULT_CODEC,
23540        );
23541
23542        let commands = worker
23543            .execute_workflow_task(task)
23544            .expect("typed child replay");
23545        assert_eq!(commands[0]["type"], "complete_workflow");
23546        assert_eq!(
23547            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
23548                .expect("typed parent result"),
23549            typed_fidelity_probe()
23550        );
23551    }
23552
23553    #[test]
23554    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
23555        let worker = child_parent_worker();
23556        let mut task = child_parent_task("unused", Value::Null);
23557        task.history_events.truncate(1);
23558        task.total_history_events = Some(1);
23559
23560        for _redelivery_or_restart in 0..2 {
23561            let commands = worker
23562                .execute_workflow_task(task.clone())
23563                .expect("recorded child remains pending");
23564            assert!(
23565                commands.is_empty(),
23566                "recorded pending child must not be started again"
23567            );
23568        }
23569    }
23570
23571    #[test]
23572    fn child_cancellation_becomes_stable_parent_failure_command() {
23573        let worker = child_parent_worker();
23574        let task = child_parent_task(
23575            "ChildRunCancelled",
23576            json!({
23577                "sequence": 1,
23578                "child_workflow_instance_id": "wf-child",
23579                "child_workflow_run_id": "run-child",
23580                "child_workflow_type": "python.child",
23581                "failure_id": "failure-child",
23582                "failure_category": "cancelled",
23583                "message": "cancelled by parent-close policy",
23584            }),
23585        );
23586
23587        let commands = worker
23588            .execute_workflow_task(task)
23589            .expect("parent settlement");
23590        assert_eq!(commands.len(), 1);
23591        assert_eq!(commands[0]["type"], "fail_workflow");
23592        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
23593        assert_eq!(
23594            commands[0]["exception"]["properties"]["reason"],
23595            "cancelled"
23596        );
23597        assert_eq!(
23598            commands[0]["exception"]["properties"]["child_workflow_run_id"],
23599            "run-child"
23600        );
23601    }
23602
23603    #[test]
23604    fn workflow_can_handle_typed_child_failure() {
23605        let client = Client::new("http://127.0.0.1:8080").expect("client");
23606        let mut worker = Worker::new(client, "rust-parent-workers");
23607        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
23608            match ctx
23609                .start_child_workflow(
23610                    "python.child",
23611                    ChildWorkflowOptions::new("python-child-workers"),
23612                    json!([]),
23613                )
23614                .await
23615            {
23616                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
23617                    "reason": failure.reason,
23618                    "failure_id": failure.failure_id,
23619                    "exception_class": failure.exception_class,
23620                    "child_run_id": failure.child_workflow_run_id,
23621                })),
23622                Err(error) => Err(error),
23623                Ok(_) => Err(Error::WorkerLoop(
23624                    "child unexpectedly succeeded".to_string(),
23625                )),
23626            }
23627        });
23628        let mut task = child_parent_task(
23629            "ChildRunFailed",
23630            json!({
23631                "sequence": 1,
23632                "child_workflow_instance_id": "wf-child",
23633                "child_workflow_run_id": "run-child",
23634                "child_workflow_type": "python.child",
23635                "failure_id": "failure-child",
23636                "failure_category": "child_workflow",
23637                "message": "payment rejected",
23638                "exception": {
23639                    "type": "PaymentRejected",
23640                    "class": "payments.PaymentRejected",
23641                    "message": "payment rejected"
23642                }
23643            }),
23644        );
23645        task.workflow_type = "rust.handled-parent".to_string();
23646        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
23647
23648        let commands = worker.execute_workflow_task(task).expect("handled failure");
23649        assert_eq!(commands[0]["type"], "complete_workflow");
23650        let output =
23651            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
23652        assert_eq!(output["reason"], "child_workflow");
23653        assert_eq!(output["failure_id"], "failure-child");
23654        assert_eq!(output["exception_class"], "payments.PaymentRejected");
23655        assert_eq!(output["child_run_id"], "run-child");
23656    }
23657
23658    #[test]
23659    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
23660        let client = Client::new("http://127.0.0.1:8080").expect("client");
23661        let mut worker = Worker::new(client, "rust-workers");
23662
23663        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
23664            let signal = ctx.wait_signal("start").await?;
23665            let name = signal
23666                .first()
23667                .and_then(|value| value.as_str())
23668                .unwrap_or("world");
23669            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
23670            Ok(json!({
23671                "greeting": greeting,
23672                "language": "rust"
23673            }))
23674        });
23675
23676        let signal_arguments =
23677            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
23678        let task = WorkflowTask {
23679            task_id: "wft-rust-signal-1".to_string(),
23680            workflow_command_id: None,
23681            workflow_id: Some("wf-rust-hello".to_string()),
23682            run_id: Some("run-rust-hello".to_string()),
23683            workflow_type: "rust.hello_workflow".to_string(),
23684            cancel_requested: false,
23685            payload_codec: DEFAULT_CODEC.to_string(),
23686            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
23687            history_events: vec![HistoryEvent {
23688                event_type: "SignalReceived".to_string(),
23689                payload: json!({
23690                    "signal_id": "sig-rust-1",
23691                    "signal_name": "start"
23692                }),
23693                raw: HashMap::new(),
23694            }],
23695            total_history_events: Some(1),
23696            history_size_bytes: None,
23697            continue_as_new_recommended: None,
23698            history_budget_pressure: None,
23699            next_history_page_token: None,
23700            workflow_task_attempt: 1,
23701            workflow_signal_id: Some("sig-rust-1".to_string()),
23702            signal_name: Some("start".to_string()),
23703            signal_arguments: Some(signal_arguments),
23704            workflow_update_id: None,
23705            update_name: None,
23706            lease_owner: Some("rust-worker".to_string()),
23707        };
23708
23709        let commands = worker.execute_workflow_task(task).expect("workflow task");
23710
23711        assert_eq!(commands.len(), 1);
23712        assert_eq!(commands[0]["type"], "schedule_activity");
23713        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
23714        assert_eq!(
23715            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
23716            json!(["Rust"])
23717        );
23718    }
23719
23720    #[test]
23721    fn workflow_task_appends_paginated_history_events() {
23722        let mut task = WorkflowTask {
23723            task_id: "wft-rust-pages-1".to_string(),
23724            workflow_command_id: None,
23725            workflow_id: Some("wf-rust-pages".to_string()),
23726            run_id: Some("run-rust-pages".to_string()),
23727            workflow_type: "rust.hello_workflow".to_string(),
23728            cancel_requested: false,
23729            payload_codec: DEFAULT_CODEC.to_string(),
23730            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
23731            history_events: vec![HistoryEvent {
23732                event_type: "WorkflowStarted".to_string(),
23733                payload: json!({}),
23734                raw: HashMap::new(),
23735            }],
23736            total_history_events: Some(3),
23737            history_size_bytes: None,
23738            continue_as_new_recommended: None,
23739            history_budget_pressure: None,
23740            next_history_page_token: Some("MQ==".to_string()),
23741            workflow_task_attempt: 1,
23742            workflow_signal_id: None,
23743            signal_name: None,
23744            signal_arguments: None,
23745            workflow_update_id: None,
23746            update_name: None,
23747            lease_owner: Some("rust-worker".to_string()),
23748        };
23749
23750        task.append_history_page(WorkflowTaskHistoryPage {
23751            history_events: vec![
23752                HistoryEvent {
23753                    event_type: "SignalReceived".to_string(),
23754                    payload: json!({
23755                        "signal_id": "sig-rust-1",
23756                        "signal_name": "start",
23757                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
23758                            .expect("signal arguments")
23759                    }),
23760                    raw: HashMap::new(),
23761                },
23762                HistoryEvent {
23763                    event_type: "MarkerRecorded".to_string(),
23764                    payload: json!({"sequence": 3}),
23765                    raw: HashMap::new(),
23766                },
23767            ],
23768            total_history_events: Some(3),
23769            next_history_page_token: None,
23770        });
23771
23772        assert_eq!(task.history_events.len(), 3);
23773        assert_eq!(task.total_history_events, Some(3));
23774        assert_eq!(task.next_history_page_token, None);
23775
23776        let signal = task
23777            .history_events
23778            .iter()
23779            .find(|event| event.event_type == "SignalReceived")
23780            .expect("signal event");
23781        assert_eq!(
23782            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
23783            vec![AvroValue::String("Rust".to_string())]
23784        );
23785    }
23786
23787    #[tokio::test]
23788    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
23789        let client = Client::new("http://127.0.0.1:8080").expect("client");
23790        let mut worker = Worker::new(client, "rust-workers");
23791        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
23792        worker.register_query("counter", "current", |ctx, _args| async move {
23793            let mut count = 0_i64;
23794            for signal in ctx.signal_events() {
23795                let value = signal
23796                    .arguments
23797                    .first()
23798                    .and_then(Value::as_i64)
23799                    .unwrap_or_default();
23800                match signal.name.as_str() {
23801                    "increment" => count += value,
23802                    "set" => count = value,
23803                    _ => {}
23804                }
23805            }
23806            Ok(json!(count))
23807        });
23808
23809        let task = QueryTask {
23810            query_task_id: "query-rust-counter".to_string(),
23811            query_task_attempt: 1,
23812            lease_owner: Some("rust-worker".to_string()),
23813            workflow_id: Some("counter-1".to_string()),
23814            run_id: Some("run-counter-1".to_string()),
23815            workflow_type: "counter".to_string(),
23816            query_name: "current".to_string(),
23817            payload_codec: DEFAULT_CODEC.to_string(),
23818            workflow_arguments: Some(
23819                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23820            ),
23821            query_arguments: Some(
23822                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
23823            ),
23824            history_events: vec![
23825                HistoryEvent {
23826                    event_type: "SignalReceived".to_string(),
23827                    payload: json!({
23828                        "signal_id": "php-signal-1",
23829                        "signal_name": "increment",
23830                        "workflow_sequence": 1,
23831                        "payload_codec": DEFAULT_CODEC,
23832                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
23833                    }),
23834                    raw: HashMap::new(),
23835                },
23836                HistoryEvent {
23837                    event_type: "SignalReceived".to_string(),
23838                    payload: json!({
23839                        "signal_id": "python-signal-2",
23840                        "signal_name": "increment",
23841                        "workflow_sequence": 2,
23842                        "payload_codec": DEFAULT_CODEC,
23843                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
23844                    }),
23845                    raw: HashMap::new(),
23846                },
23847                HistoryEvent {
23848                    event_type: "SignalReceived".to_string(),
23849                    payload: json!({
23850                        "signal_id": "rust-signal-3",
23851                        "signal_name": "set",
23852                        "workflow_sequence": 3,
23853                        "payload_codec": DEFAULT_CODEC,
23854                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
23855                    }),
23856                    raw: HashMap::new(),
23857                },
23858            ],
23859            history_export: None,
23860            run_status: Some("completed".to_string()),
23861        };
23862
23863        let result = worker.execute_query_task(task).await.expect("query result");
23864        assert_eq!(result.into_json().expect("query projection"), json!(0));
23865    }
23866
23867    #[tokio::test]
23868    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
23869        let worker = replay_counter_worker();
23870        let running_history = json!([
23871            {
23872                "type": "ActivityCompleted",
23873                "payload": {
23874                    "sequence": 1,
23875                    "activity_type": "load-counter",
23876                    "payload_codec": DEFAULT_CODEC,
23877                    "result": fixture_envelope(json!("loaded"))
23878                }
23879            },
23880            {
23881                "type": "SignalWaitOpened",
23882                "payload": {
23883                    "sequence": 3,
23884                    "signal_name": "increment"
23885                }
23886            },
23887            {
23888                "type": "SignalReceived",
23889                "payload": {
23890                    "signal_id": "signal-3",
23891                    "signal_name": "increment",
23892                    "workflow_sequence": 2,
23893                    "payload_codec": DEFAULT_CODEC,
23894                    "arguments": fixture_envelope(json!([3]))
23895                }
23896            },
23897            {
23898                "type": "SignalApplied",
23899                "payload": {
23900                    "sequence": 3,
23901                    "signal_id": "signal-3",
23902                    "signal_name": "increment",
23903                    "payload_codec": DEFAULT_CODEC,
23904                    "value": fixture_envelope(json!([3]))
23905                }
23906            }
23907        ]);
23908
23909        let running = worker
23910            .execute_query_task(replay_counter_query(
23911                "current",
23912                running_history.clone(),
23913                "running",
23914            ))
23915            .await
23916            .expect("running replay query");
23917        assert_eq!(
23918            running.clone().into_json().expect("query projection"),
23919            json!({"loaded": "loaded", "count": 3, "finished": false})
23920        );
23921
23922        let detached = worker
23923            .execute_query_task(replay_counter_query(
23924                "detached-mutation",
23925                running_history.clone(),
23926                "running",
23927            ))
23928            .await
23929            .expect("query mutates only its detached state clone");
23930        assert_eq!(detached.into_json().expect("query projection"), json!(999));
23931        let failed = worker
23932            .execute_query_task(replay_counter_query(
23933                "failed-mutation",
23934                running_history.clone(),
23935                "running",
23936            ))
23937            .await
23938            .expect_err("failed query");
23939        assert_eq!(failed.reason, "query_rejected");
23940        let unchanged = worker
23941            .execute_query_task(replay_counter_query("current", running_history, "running"))
23942            .await
23943            .expect("later query reconstructs unchanged state");
23944        assert_eq!(unchanged, running);
23945
23946        let restarted_worker = replay_counter_worker();
23947        let empty_arguments = fixture_envelope(json!([]));
23948        let loaded_result = fixture_envelope(json!("loaded"));
23949        let signal_three = fixture_blob(json!([3]));
23950        let signal_five = fixture_blob(json!([5]));
23951        let restarted_task: QueryTask = serde_json::from_value(json!({
23952            "query_task_id": "query-after-restart",
23953            "workflow_id": "counter-1",
23954            "run_id": "run-counter-1",
23955            "workflow_type": "replay-counter",
23956            "query_name": "current",
23957            "payload_codec": DEFAULT_CODEC,
23958            "workflow_arguments": empty_arguments.clone(),
23959            "query_arguments": empty_arguments,
23960            "history_events": [],
23961            "history_export": {
23962                "payloads": {"codec": DEFAULT_CODEC},
23963                "history_events": [
23964                    {
23965                        "type": "ActivityCompleted",
23966                        "payload": {
23967                            "sequence": 1,
23968                            "activity_type": "load-counter",
23969                            "payload_codec": DEFAULT_CODEC,
23970                            "result": null
23971                        }
23972                    },
23973                    {
23974                        "type": "SignalWaitOpened",
23975                        "payload": {
23976                            "sequence": 3,
23977                            "signal_name": "increment"
23978                        }
23979                    },
23980                    {
23981                        "type": "SignalReceived",
23982                        "payload": {
23983                            "signal_id": "signal-3",
23984                            "signal_name": "increment",
23985                            "workflow_sequence": 2
23986                        }
23987                    },
23988                    {
23989                        "type": "SignalApplied",
23990                        "payload": {
23991                            "sequence": 3,
23992                            "signal_id": "signal-3",
23993                            "signal_name": "increment"
23994                        }
23995                    },
23996                    {
23997                        "type": "SignalWaitOpened",
23998                        "payload": {
23999                            "sequence": 5,
24000                            "signal_name": "increment"
24001                        }
24002                    },
24003                    {
24004                        "type": "SignalReceived",
24005                        "payload": {
24006                            "signal_id": "signal-5",
24007                            "signal_name": "increment",
24008                            "workflow_sequence": 4
24009                        }
24010                    },
24011                    {
24012                        "type": "SignalApplied",
24013                        "payload": {
24014                            "sequence": 5,
24015                            "signal_id": "signal-5",
24016                            "signal_name": "increment"
24017                        }
24018                    }
24019                ],
24020                "activities": [{
24021                    "sequence": 1,
24022                    "activity_type": "load-counter",
24023                    "payload_codec": DEFAULT_CODEC,
24024                    "result": loaded_result
24025                }],
24026                "signals": [
24027                    {
24028                        "id": "signal-3",
24029                        "name": "increment",
24030                        "workflow_sequence": 2,
24031                        "payload_codec": DEFAULT_CODEC,
24032                        "arguments": signal_three
24033                    },
24034                    {
24035                        "id": "signal-5",
24036                        "name": "increment",
24037                        "workflow_sequence": 4,
24038                        "payload_codec": DEFAULT_CODEC,
24039                        "arguments": signal_five
24040                    }
24041                ]
24042            },
24043            "run_status": "completed"
24044        }))
24045        .expect("cold replay query task");
24046        let completed = restarted_worker
24047            .execute_query_task(restarted_task)
24048            .await
24049            .expect("completed cold replay query");
24050        assert_eq!(
24051            completed.into_json().expect("query projection"),
24052            json!({"loaded": "loaded", "count": 8, "finished": true})
24053        );
24054    }
24055
24056    #[tokio::test]
24057    async fn replayed_query_replay_failures_are_machine_readable() {
24058        let worker = replay_counter_worker();
24059        let task = replay_counter_query(
24060            "current",
24061            json!([{
24062                "type": "ActivityCompleted",
24063                "payload": {
24064                    "sequence": 1,
24065                    "payload_codec": DEFAULT_CODEC,
24066                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
24067                }
24068            }]),
24069            "running",
24070        );
24071        let failure = worker
24072            .execute_query_task(task)
24073            .await
24074            .expect_err("invalid replay history payload");
24075        assert_eq!(failure.reason, "query_payload_decode_failed");
24076        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
24077        assert!(failure.message.contains("invalid_payload_framing"));
24078    }
24079
24080    #[tokio::test]
24081    async fn query_task_restores_compact_history_from_export() {
24082        let client = Client::new("http://127.0.0.1:8080").expect("client");
24083        let mut worker = Worker::new(client, "rust-workers");
24084        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24085        worker.register_query("counter", "current", |ctx, _args| async move {
24086            Ok(json!(ctx.signals("increment")[0][0]))
24087        });
24088        let empty_arguments = fixture_envelope(json!([]));
24089        let exported_signal = fixture_blob(json!([9]));
24090        let task: QueryTask = serde_json::from_value(json!({
24091            "query_task_id": "query-export",
24092            "workflow_type": "counter",
24093            "query_name": "current",
24094            "payload_codec": DEFAULT_CODEC,
24095            "workflow_arguments": empty_arguments.clone(),
24096            "query_arguments": empty_arguments,
24097            "history_events": [],
24098            "history_export": {
24099                "payloads": {"codec": DEFAULT_CODEC},
24100                "history_events": [{
24101                    "type": "SignalReceived",
24102                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
24103                }],
24104                "signals": [{
24105                    "id": "signal-export",
24106                    "name": "increment",
24107                    "status": "applied",
24108                    "workflow_sequence": 1,
24109                    "payload_codec": DEFAULT_CODEC,
24110                    "arguments": exported_signal
24111                }]
24112            }
24113        }))
24114        .expect("query task");
24115
24116        let result = worker.execute_query_task(task).await.expect("query result");
24117        assert_eq!(result.into_json().expect("query projection"), json!(9));
24118    }
24119
24120    #[tokio::test]
24121    async fn query_task_failures_have_stable_reasons() {
24122        let client = Client::new("http://127.0.0.1:8080").expect("client");
24123        let mut worker = Worker::new(client, "rust-workers");
24124        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24125        worker.register_query(
24126            "counter",
24127            "current",
24128            |_ctx, _args| async move { Ok(json!(0)) },
24129        );
24130
24131        let base_task = QueryTask {
24132            query_task_id: "query-errors".to_string(),
24133            query_task_attempt: 1,
24134            lease_owner: None,
24135            workflow_id: Some("counter-errors".to_string()),
24136            run_id: Some("run-errors".to_string()),
24137            workflow_type: "counter".to_string(),
24138            query_name: "missing".to_string(),
24139            payload_codec: DEFAULT_CODEC.to_string(),
24140            workflow_arguments: Some(fixture_envelope(json!([]))),
24141            query_arguments: Some(fixture_envelope(json!([]))),
24142            history_events: Vec::new(),
24143            history_export: None,
24144            run_status: Some("running".to_string()),
24145        };
24146
24147        let unknown = worker
24148            .execute_query_task(base_task.clone())
24149            .await
24150            .expect_err("unknown query");
24151        assert_eq!(unknown.reason, "rejected_unknown_query");
24152
24153        let mut malformed = base_task;
24154        malformed.query_name = "current".to_string();
24155        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
24156        let malformed = worker
24157            .execute_query_task(malformed)
24158            .await
24159            .expect_err("malformed payload");
24160        assert_eq!(malformed.reason, "query_payload_decode_failed");
24161
24162        let client = Client::new("http://127.0.0.1:8080").expect("client");
24163        let mut unavailable_worker = Worker::new(client, "rust-workers");
24164        unavailable_worker
24165            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24166        let empty_arguments = fixture_envelope(json!([]));
24167        let unavailable_task: QueryTask = serde_json::from_value(json!({
24168            "query_task_id": "query-unavailable",
24169            "workflow_type": "counter",
24170            "query_name": "current",
24171            "payload_codec": DEFAULT_CODEC,
24172            "workflow_arguments": empty_arguments.clone(),
24173            "query_arguments": empty_arguments
24174        }))
24175        .expect("query task");
24176        let unavailable = unavailable_worker
24177            .execute_query_task(unavailable_task)
24178            .await
24179            .expect_err("query handler unavailable");
24180        assert_eq!(unavailable.reason, "query_handler_unavailable");
24181    }
24182
24183    #[tokio::test]
24184    async fn client_query_decodes_result_and_typed_failure() {
24185        let server = MockWorkerServer::start();
24186        let client = Client::builder(server.base_url())
24187            .timeout(Duration::from_secs(2))
24188            .build()
24189            .expect("client");
24190
24191        let result = client
24192            .query_workflow("counter-1", "current", json!([]))
24193            .await
24194            .expect("query result");
24195        assert_eq!(result, json!({"count": 8}));
24196
24197        let error = client
24198            .query_workflow("counter-1", "missing", json!([]))
24199            .await
24200            .expect_err("unknown query");
24201        let Error::QueryFailed(failure) = error else {
24202            panic!("expected typed query failure");
24203        };
24204        assert_eq!(failure.status, 404);
24205        assert_eq!(failure.reason, "rejected_unknown_query");
24206    }
24207
24208    #[tokio::test]
24209    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
24210        let server = MockWorkerServer::start();
24211        let client = Client::builder(server.base_url())
24212            .timeout(Duration::from_secs(2))
24213            .build()
24214            .expect("client");
24215        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
24216
24217        client
24218            .start_workflow(
24219                "typed.echo",
24220                "rust-workers",
24221                "typed-start",
24222                arguments.clone(),
24223            )
24224            .await
24225            .expect("typed workflow start");
24226        assert_eq!(
24227            decode_wire_avro_value(
24228                &server.request_body("/api/workflows")["input"],
24229                DEFAULT_CODEC,
24230            )
24231            .expect("typed start input"),
24232            arguments
24233        );
24234
24235        client
24236            .signal_workflow("typed-1", "changed", arguments.clone())
24237            .await
24238            .expect("typed signal");
24239        assert_eq!(
24240            decode_wire_avro_value(
24241                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
24242                DEFAULT_CODEC,
24243            )
24244            .expect("typed signal input"),
24245            arguments
24246        );
24247
24248        assert_eq!(
24249            client
24250                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
24251                .await
24252                .expect("typed query"),
24253            typed_fidelity_probe()
24254        );
24255        assert_eq!(
24256            decode_wire_avro_value(
24257                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
24258                DEFAULT_CODEC,
24259            )
24260            .expect("typed query input"),
24261            arguments
24262        );
24263
24264        assert_eq!(
24265            client
24266                .update_workflow_avro_value(
24267                    "typed-1",
24268                    "replace",
24269                    arguments.clone(),
24270                    Some("typed-request"),
24271                )
24272                .await
24273                .expect("typed update"),
24274            typed_fidelity_probe()
24275        );
24276        let update = server.request_body("/api/workflows/typed-1/update/replace");
24277        assert_eq!(update["request_id"], "typed-request");
24278        assert_eq!(
24279            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
24280            arguments
24281        );
24282
24283        let handle = WorkflowHandle {
24284            client: client.clone(),
24285            workflow_id: "typed-1".to_string(),
24286            run_id: Some("run-typed-1".to_string()),
24287            workflow_type: "typed.echo".to_string(),
24288        };
24289        assert_eq!(
24290            handle
24291                .result_avro_value(WorkflowResultOptions::default())
24292                .await
24293                .expect("typed workflow result"),
24294            typed_fidelity_probe()
24295        );
24296
24297        client
24298            .complete_activity_task(
24299                "activity-typed",
24300                "attempt-typed",
24301                "rust-worker",
24302                typed_fidelity_probe(),
24303                DEFAULT_CODEC,
24304            )
24305            .await
24306            .expect("typed activity completion");
24307        assert_eq!(
24308            decode_wire_avro_value(
24309                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
24310                    ["result"],
24311                DEFAULT_CODEC,
24312            )
24313            .expect("typed activity result"),
24314            typed_fidelity_probe()
24315        );
24316        client
24317            .fail_activity_task(
24318                "activity-typed",
24319                "attempt-typed",
24320                "rust-worker",
24321                "typed failure",
24322                true,
24323            )
24324            .await
24325            .expect("activity failure");
24326    }
24327
24328    #[tokio::test]
24329    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
24330        let server = MockWorkerServer::start();
24331        let client = Client::builder(server.base_url())
24332            .timeout(Duration::from_secs(2))
24333            .build()
24334            .expect("client");
24335
24336        let options = WorkflowCommandOptions::new()
24337            .reason("cleanup requested")
24338            .request_id("cancel-17");
24339        let cancelled = client
24340            .cancel_workflow("wf-lifecycle", options)
24341            .await
24342            .expect("instance cancellation");
24343        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
24344        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
24345        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
24346        assert_eq!(
24347            server.request_body("/api/workflows/wf-lifecycle/cancel"),
24348            json!({"reason":"cleanup requested","request_id":"cancel-17"})
24349        );
24350
24351        let terminated = client
24352            .terminate_workflow(
24353                "wf-lifecycle",
24354                WorkflowCommandOptions::new().reason("forced stop"),
24355            )
24356            .await
24357            .expect("instance termination");
24358        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
24359        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
24360
24361        client
24362            .cancel_workflow_run(
24363                "wf-lifecycle",
24364                "run-current",
24365                WorkflowCommandOptions::default(),
24366            )
24367            .await
24368            .expect("selected run cancellation");
24369        client
24370            .terminate_workflow_run(
24371                "wf-lifecycle",
24372                "run-current",
24373                WorkflowCommandOptions::default(),
24374            )
24375            .await
24376            .expect("selected run termination");
24377
24378        for (command, error) in [
24379            (
24380                WorkflowCommandKind::Cancel,
24381                client
24382                    .cancel_workflow_run(
24383                        "wf-lifecycle",
24384                        "run-stale",
24385                        WorkflowCommandOptions::default(),
24386                    )
24387                    .await
24388                    .expect_err("stale cancellation must be rejected"),
24389            ),
24390            (
24391                WorkflowCommandKind::Terminate,
24392                client
24393                    .terminate_workflow_run(
24394                        "wf-lifecycle",
24395                        "run-stale",
24396                        WorkflowCommandOptions::default(),
24397                    )
24398                    .await
24399                    .expect_err("stale termination must be rejected"),
24400            ),
24401        ] {
24402            let Error::WorkflowCommandRejected(rejection) = error else {
24403                panic!("expected typed command rejection");
24404            };
24405            assert_eq!(rejection.command, command);
24406            assert_eq!(rejection.status, 409);
24407            assert_eq!(rejection.reason, "historical_run_command_rejected");
24408            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
24409            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
24410        }
24411    }
24412
24413    #[tokio::test]
24414    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
24415        let server = MockWorkerServer::start();
24416        let client = Client::builder(server.base_url())
24417            .timeout(Duration::from_secs(2))
24418            .build()
24419            .expect("client");
24420
24421        let result = client
24422            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
24423            .await
24424            .expect("redrive accepted");
24425        assert_eq!(result.workflow_id, "wf-lifecycle");
24426        assert_eq!(result.source_run_id, "run-failed");
24427        assert_eq!(result.run_id, "run-successor");
24428        assert_eq!(result.resume_step_sequence, 2);
24429        assert_eq!(
24430            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
24431            json!({"request_id":"retry-1"})
24432        );
24433
24434        let repeated = client
24435            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
24436            .await
24437            .expect("idempotent redrive response accepted");
24438        assert_eq!(repeated.run_id, "run-successor");
24439
24440        let error = client
24441            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
24442            .await
24443            .expect_err("completed run must be rejected");
24444        let Error::Http { status, body } = error else {
24445            panic!("expected HTTP redrive rejection");
24446        };
24447        assert_eq!(status.as_u16(), 409);
24448        assert!(body.contains("run_not_failed"));
24449        assert_eq!(
24450            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
24451            json!({})
24452        );
24453
24454        let handle = WorkflowHandle {
24455            client: client.clone(),
24456            workflow_id: "wf-lifecycle".to_string(),
24457            run_id: Some("run-failed".to_string()),
24458            workflow_type: "test".to_string(),
24459        };
24460        assert_eq!(
24461            handle.redrive(None).await.expect("handle redrive").run_id,
24462            "run-successor"
24463        );
24464        let missing_run = WorkflowHandle {
24465            run_id: None,
24466            ..handle
24467        };
24468        assert!(matches!(
24469            missing_run.redrive(None).await,
24470            Err(Error::Codec(_))
24471        ));
24472    }
24473
24474    #[tokio::test]
24475    async fn workflow_start_options_send_server_enforced_deadlines() {
24476        let server = MockWorkerServer::start();
24477        let client = Client::builder(server.base_url())
24478            .timeout(Duration::from_secs(2))
24479            .build()
24480            .expect("client");
24481
24482        let handle = client
24483            .start_workflow_with_options(
24484                "rust.timeout",
24485                "rust-timeouts",
24486                "wf-start-options",
24487                WorkflowStartOptions::new()
24488                    .execution_timeout_seconds(30)
24489                    .run_timeout_seconds(1),
24490                json!([]),
24491            )
24492            .await
24493            .expect("workflow start");
24494
24495        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
24496        let body = server.request_body("/api/workflows");
24497        assert_eq!(body["execution_timeout_seconds"], 30);
24498        assert_eq!(body["run_timeout_seconds"], 1);
24499
24500        let invalid = client
24501            .start_workflow_with_options(
24502                "rust.timeout",
24503                "rust-timeouts",
24504                "wf-invalid-options",
24505                WorkflowStartOptions::new()
24506                    .execution_timeout_seconds(1)
24507                    .run_timeout_seconds(2),
24508                json!([]),
24509            )
24510            .await
24511            .expect_err("invalid deadline ordering");
24512        assert!(invalid
24513            .to_string()
24514            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
24515    }
24516
24517    #[tokio::test]
24518    async fn workflow_result_returns_each_typed_terminal_outcome() {
24519        let server = MockWorkerServer::start();
24520        let client = Client::builder(server.base_url())
24521            .timeout(Duration::from_secs(2))
24522            .build()
24523            .expect("client");
24524        let options = WorkflowResultOptions {
24525            poll_interval: Duration::ZERO,
24526            timeout: Duration::from_secs(1),
24527        };
24528
24529        let failed = WorkflowHandle {
24530            client: client.clone(),
24531            workflow_id: "wf-failed".to_string(),
24532            run_id: Some("run-failed".to_string()),
24533            workflow_type: "failure".to_string(),
24534        }
24535        .result(options)
24536        .await
24537        .expect_err("failed outcome");
24538        let Error::WorkflowFailed(failure) = failed else {
24539            panic!("expected WorkflowFailed");
24540        };
24541        assert_eq!(failure.workflow_id, "wf-failed");
24542        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
24543        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
24544        assert_eq!(failure.failure_category.as_deref(), Some("application"));
24545        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
24546        assert_eq!(
24547            failure.exception_class.as_deref(),
24548            Some("billing::PaymentError")
24549        );
24550        assert_eq!(failure.non_retryable, Some(true));
24551
24552        for (workflow_id, expected_kind, expected_reason) in [
24553            (
24554                "wf-cancelled",
24555                WorkflowTerminalKind::Cancelled,
24556                "cleanup requested",
24557            ),
24558            (
24559                "wf-terminated",
24560                WorkflowTerminalKind::Terminated,
24561                "forced stop",
24562            ),
24563            (
24564                "wf-timed-out",
24565                WorkflowTerminalKind::TimedOut,
24566                "run_timeout",
24567            ),
24568        ] {
24569            let error = WorkflowHandle {
24570                client: client.clone(),
24571                workflow_id: workflow_id.to_string(),
24572                run_id: None,
24573                workflow_type: "terminal".to_string(),
24574            }
24575            .result(options)
24576            .await
24577            .expect_err("typed terminal outcome");
24578            let outcome = match error {
24579                Error::WorkflowCancelled(outcome) => outcome,
24580                Error::WorkflowTerminated(outcome) => outcome,
24581                Error::WorkflowTimedOut(outcome) => outcome,
24582                other => panic!("unexpected terminal error: {other}"),
24583            };
24584            assert_eq!(outcome.kind, expected_kind);
24585            assert_eq!(outcome.workflow_id, workflow_id);
24586            assert_eq!(outcome.reason, expected_reason);
24587        }
24588
24589        let wait_timeout = WorkflowHandle {
24590            client,
24591            workflow_id: "wf-waiting".to_string(),
24592            run_id: Some("run-waiting".to_string()),
24593            workflow_type: "waiting".to_string(),
24594        }
24595        .result(WorkflowResultOptions {
24596            poll_interval: Duration::ZERO,
24597            timeout: Duration::ZERO,
24598        })
24599        .await
24600        .expect_err("client wait timeout");
24601        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
24602            panic!("expected typed client timeout");
24603        };
24604        assert_eq!(timeout.reason, "result_wait_timeout");
24605        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
24606        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
24607    }
24608
24609    #[tokio::test]
24610    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
24611        let server = MockWorkerServer::start();
24612        let client = Client::builder(server.base_url())
24613            .timeout(Duration::from_secs(2))
24614            .build()
24615            .expect("client");
24616
24617        let handle = WorkflowHandle {
24618            client,
24619            workflow_id: "wf-selected".to_string(),
24620            run_id: Some("run-selected".to_string()),
24621            workflow_type: "selected".to_string(),
24622        };
24623        let options = WorkflowResultOptions {
24624            poll_interval: Duration::ZERO,
24625            timeout: Duration::from_secs(1),
24626        };
24627
24628        let current = handle
24629            .result(options)
24630            .await
24631            .expect("instance result follows the current run");
24632        assert_eq!(current, json!("current run output"));
24633
24634        let error = handle
24635            .result_selected_run(options)
24636            .await
24637            .expect_err("the selected run is cancelled even though the current run completed");
24638
24639        let Error::WorkflowCancelled(outcome) = error else {
24640            panic!("expected selected run cancellation");
24641        };
24642        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
24643        assert_eq!(outcome.reason, "selected run cancelled");
24644        assert_eq!(
24645            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
24646            1
24647        );
24648        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
24649    }
24650
24651    #[tokio::test]
24652    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
24653        let server = MockWorkerServer::draining_polls();
24654        let client = Client::builder(server.base_url())
24655            .timeout(Duration::from_secs(2))
24656            .build()
24657            .expect("client");
24658
24659        let workflow = client
24660            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
24661            .await
24662            .expect("workflow drain response");
24663        let activity = client
24664            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
24665            .await
24666            .expect("activity drain response");
24667        let query = client
24668            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
24669            .await
24670            .expect("query drain response");
24671
24672        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
24673            assert_eq!(
24674                outcome,
24675                WorkerPollOutcome::Stop {
24676                    poll_status: Some("draining".to_string()),
24677                    reason: Some("worker_draining".to_string()),
24678                }
24679            );
24680        }
24681
24682        assert!(client
24683            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
24684            .await
24685            .expect("compatibility poll")
24686            .is_none());
24687    }
24688
24689    #[tokio::test]
24690    async fn managed_worker_honors_drain_stop_for_every_task_family() {
24691        let server = MockWorkerServer::draining_polls();
24692        let client = Client::builder(server.base_url())
24693            .timeout(Duration::from_secs(2))
24694            .build()
24695            .expect("client");
24696
24697        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
24698            .worker_id("draining-workflow-worker")
24699            .poll_timeout(Duration::ZERO);
24700        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
24701        workflow_worker
24702            .run()
24703            .await
24704            .expect("workflow drain is a clean stop");
24705
24706        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
24707            .worker_id("draining-activity-worker")
24708            .poll_timeout(Duration::ZERO);
24709        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
24710        activity_worker
24711            .run()
24712            .await
24713            .expect("activity drain is a clean stop");
24714
24715        let mut query_worker = Worker::new(client, "rust-workers")
24716            .worker_id("draining-query-worker")
24717            .poll_timeout(Duration::ZERO);
24718        query_worker.register_query("counter", "current", |_ctx, _args| async {
24719            Ok(Value::Null)
24720        });
24721        query_worker
24722            .run()
24723            .await
24724            .expect("query drain is a clean stop");
24725    }
24726
24727    #[tokio::test]
24728    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
24729        let server = MockWorkerServer::start();
24730        let client = Client::builder(server.base_url())
24731            .timeout(Duration::from_secs(2))
24732            .build()
24733            .expect("client");
24734
24735        let heartbeat = client
24736            .heartbeat_activity_task(
24737                "activity-cancel",
24738                "attempt-cancel",
24739                "rust-worker",
24740                typed_fidelity_probe(),
24741            )
24742            .await
24743            .expect("cancellation heartbeat");
24744        assert!(heartbeat.cancel_requested);
24745        assert!(heartbeat.should_stop());
24746        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
24747        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
24748        let heartbeat_body =
24749            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
24750        assert_eq!(heartbeat_body["details"]["codec"], DEFAULT_CODEC);
24751        assert_eq!(
24752            decode_wire_avro_value(&heartbeat_body["details"], DEFAULT_CODEC)
24753                .expect("typed heartbeat details"),
24754            typed_fidelity_probe()
24755        );
24756
24757        let error = client
24758            .complete_activity_task(
24759                "activity-cancel",
24760                "attempt-cancel",
24761                "rust-worker",
24762                json!({"late":true}),
24763                DEFAULT_CODEC,
24764            )
24765            .await
24766            .expect_err("late completion must be refused");
24767        assert!(activity_task_rejection_is_final(&error));
24768        let Error::ActivityTaskRejected(rejection) = error else {
24769            panic!("expected typed activity rejection");
24770        };
24771        assert_eq!(rejection.status, 409);
24772        assert_eq!(rejection.reason, "run_cancelled");
24773        assert!(rejection.cancel_requested);
24774        assert_eq!(rejection.can_continue, Some(false));
24775    }
24776
24777    #[tokio::test]
24778    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
24779        let server = MockWorkerServer::cancelled_activity();
24780        let client = Client::builder(server.base_url())
24781            .timeout(Duration::from_secs(2))
24782            .build()
24783            .expect("client");
24784        let cancellation_observed = Arc::new(AtomicBool::new(false));
24785        let observed = Arc::clone(&cancellation_observed);
24786        let mut worker = Worker::new(client.clone(), "rust-workers")
24787            .worker_id("rust-cancel-worker")
24788            .poll_timeout(Duration::from_millis(10));
24789        worker.register_activity("cancel-aware", move |ctx, _args| {
24790            let observed = Arc::clone(&observed);
24791            async move {
24792                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
24793                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
24794                Ok(json!({"late":"completion"}))
24795            }
24796        });
24797
24798        assert_eq!(
24799            worker.run_once().await.expect("cancelled attempt handled"),
24800            1
24801        );
24802        assert!(cancellation_observed.load(Ordering::SeqCst));
24803        assert_eq!(
24804            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
24805            1
24806        );
24807
24808        let mut restarted = Worker::new(client, "rust-workers")
24809            .worker_id("rust-cancel-worker-restarted")
24810            .poll_timeout(Duration::from_millis(10));
24811        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
24812        assert_eq!(
24813            restarted
24814                .run_once()
24815                .await
24816                .expect("replacement worker continues polling"),
24817            0
24818        );
24819    }
24820
24821    #[tokio::test]
24822    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
24823        let response = r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"outcome":"completed","recorded":false,"run_id":"run-selected-timeout","run_status":"failed","created_task_ids":[],"reason":"run_timed_out"}"#;
24824        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
24825        let client = Client::builder(server.base_url())
24826            .timeout(Duration::from_secs(2))
24827            .build()
24828            .expect("client");
24829
24830        let direct_error = client
24831            .complete_workflow_task(
24832                "workflow-timeout-task",
24833                "timeout-worker",
24834                3,
24835                vec![json!({
24836                    "type": "complete_workflow",
24837                    "result": fixture_envelope(Value::Null)
24838                })],
24839            )
24840            .await
24841            .expect_err("the low-level client preserves the completion rejection");
24842        let Error::Http { status, body } = direct_error else {
24843            panic!("expected the original HTTP completion rejection");
24844        };
24845        assert_eq!(status, reqwest::StatusCode::CONFLICT);
24846        assert_eq!(
24847            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
24848            "run_timed_out"
24849        );
24850
24851        let mut worker = Worker::new(client, "rust-workers")
24852            .worker_id("timeout-worker")
24853            .poll_timeout(Duration::from_millis(10));
24854        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
24855            Ok(json!({"late": "result"}))
24856        });
24857
24858        assert_eq!(
24859            worker
24860                .run_once()
24861                .await
24862                .expect("authoritative selected-run timeout settles the tick"),
24863            1
24864        );
24865        assert_eq!(
24866            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
24867            2,
24868            "both the direct client proof and managed worker must see the rejection"
24869        );
24870    }
24871
24872    #[tokio::test]
24873    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
24874        for (name, status, response) in [
24875            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
24876            (
24877                "command was recorded",
24878                "409 Conflict",
24879                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
24880            ),
24881            (
24882                "lease conflict",
24883                "409 Conflict",
24884                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
24885            ),
24886            (
24887                "nonterminal run",
24888                "409 Conflict",
24889                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
24890            ),
24891            (
24892                "different selected run",
24893                "409 Conflict",
24894                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-reused-workflow-current","run_status":"failed","reason":"run_timed_out"}"#,
24895            ),
24896            (
24897                "different task attempt",
24898                "409 Conflict",
24899                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
24900            ),
24901            (
24902                "authentication failure",
24903                "401 Unauthorized",
24904                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
24905            ),
24906            (
24907                "authorization failure",
24908                "403 Forbidden",
24909                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
24910            ),
24911            (
24912                "protocol failure",
24913                "400 Bad Request",
24914                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
24915            ),
24916            (
24917                "malformed command",
24918                "422 Unprocessable Entity",
24919                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
24920            ),
24921            (
24922                "transient server failure",
24923                "503 Service Unavailable",
24924                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
24925            ),
24926        ] {
24927            let server = MockWorkerServer::workflow_completion(status, response);
24928            let client = Client::builder(server.base_url())
24929                .timeout(Duration::from_secs(2))
24930                .build()
24931                .expect("client");
24932            let mut worker = Worker::new(client, "rust-workers")
24933                .worker_id("timeout-worker")
24934                .poll_timeout(Duration::from_millis(10));
24935            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
24936                Ok(json!({"late": "result"}))
24937            });
24938
24939            let error = worker
24940                .run_once()
24941                .await
24942                .expect_err(&format!("{name} must remain an error"));
24943            assert!(
24944                matches!(error, Error::Http { .. } | Error::Protocol(_)),
24945                "{name} returned an unexpected error variant: {error}"
24946            );
24947        }
24948    }
24949
24950    #[tokio::test]
24951    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
24952        let server = MockWorkerServer::start();
24953        let client = Client::builder(server.base_url())
24954            .worker_token(Some("worker-secret".to_string()))
24955            .namespace("orders")
24956            .timeout(Duration::from_secs(2))
24957            .build()
24958            .expect("client");
24959        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
24960
24961        let result = client
24962            .deregister_worker_registration("worker/α space")
24963            .await
24964            .expect("deregister worker registration");
24965
24966        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
24967        assert_eq!(
24968            server.worker_protocol_for(path).as_deref(),
24969            Some(WORKER_PROTOCOL_VERSION)
24970        );
24971        assert_eq!(server.control_protocol_for(path), None);
24972        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
24973        assert_eq!(
24974            server.authorization_for(path).as_deref(),
24975            Some("Bearer worker-secret")
24976        );
24977        assert_eq!(
24978            result,
24979            WorkerDeregistrationEnvelope {
24980                worker_id: "deregistered-worker".to_string(),
24981                outcome: "deregistered".to_string(),
24982                recovered_workflow_task_count: 2,
24983            }
24984        );
24985    }
24986
24987    #[tokio::test]
24988    async fn low_level_registration_rejects_update_validators_before_transport() {
24989        let server = MockWorkerServer::start();
24990        let client = Client::builder(server.base_url())
24991            .timeout(Duration::from_secs(2))
24992            .build()
24993            .expect("client");
24994
24995        for update_validators in [json!(["approve"]), json!("approve")] {
24996            let error = client
24997                .register_worker_with_command_contracts(
24998                    "validator-claiming-worker",
24999                    "rust-workers",
25000                    vec!["orders".to_string()],
25001                    vec![],
25002                    1,
25003                    1,
25004                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
25005                    json!({
25006                        "orders": {
25007                            "queries": ["current"],
25008                            "updates": ["approve"],
25009                            "update_validators": update_validators,
25010                        },
25011                    }),
25012                )
25013                .await
25014                .expect_err("unsupported validator claims must fail before registration");
25015
25016            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
25017                panic!("expected typed unsupported-validator failure");
25018            };
25019            assert_eq!(workflow_type, "orders");
25020        }
25021        assert_eq!(server.request_count("/api/worker/register"), 0);
25022    }
25023
25024    #[tokio::test]
25025    async fn low_level_registration_preserves_query_and_update_contracts() {
25026        let server = MockWorkerServer::start();
25027        let client = Client::builder(server.base_url())
25028            .timeout(Duration::from_secs(2))
25029            .build()
25030            .expect("client");
25031        let contracts = json!({
25032            "orders": {
25033                "queries": ["current"],
25034                "updates": ["approve"],
25035                "update_validators": [],
25036            },
25037            "payments": {
25038                "queries": ["status"],
25039                "updates": ["capture"],
25040            },
25041        });
25042
25043        client
25044            .register_worker_with_command_contracts(
25045                "command-worker",
25046                "rust-workers",
25047                vec!["orders".to_string(), "payments".to_string()],
25048                vec![],
25049                1,
25050                1,
25051                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
25052                contracts.clone(),
25053            )
25054            .await
25055            .expect("query and update contracts must remain supported");
25056
25057        assert_eq!(
25058            server.request_body("/api/worker/register")["workflow_command_contracts"],
25059            contracts
25060        );
25061        assert!(server
25062            .request_body("/api/worker/register")
25063            .get("workflow_definition_fingerprints")
25064            .is_none());
25065    }
25066
25067    #[tokio::test]
25068    async fn rust_worker_advertises_source_backed_definition_and_clears_it_on_reregistration() {
25069        let server = MockWorkerServer::start();
25070        let client = Client::builder(server.base_url())
25071            .timeout(Duration::from_secs(2))
25072            .build()
25073            .expect("client");
25074        let mut worker = Worker::new(client, "rust-workers");
25075        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
25076
25077        assert!(worker
25078            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
25079            .is_err());
25080        assert!(worker
25081            .set_workflow_definition_sources("orders", &[])
25082            .is_err());
25083        worker
25084            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
25085            .expect("embed workflow source");
25086        worker.register().await.expect("register worker");
25087        let first = server.request_bodies("/api/worker/register")[0]
25088            ["workflow_definition_fingerprints"]["orders"]
25089            .as_str()
25090            .expect("source-backed fingerprint")
25091            .to_string();
25092        assert!(first.starts_with("sha256:"));
25093
25094        worker
25095            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
25096            .expect("change embedded helper source");
25097        worker.register().await.expect("register changed source");
25098        let changed = server.request_bodies("/api/worker/register")[1]
25099            ["workflow_definition_fingerprints"]["orders"]
25100            .as_str()
25101            .expect("changed fingerprint")
25102            .to_string();
25103        assert_ne!(first, changed);
25104
25105        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
25106        worker
25107            .register()
25108            .await
25109            .expect("register replacement handler");
25110        assert_eq!(
25111            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
25112            json!({})
25113        );
25114    }
25115
25116    #[tokio::test]
25117    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
25118        let server = MockWorkerServer::start();
25119        let control_only = Client::builder(server.base_url())
25120            .control_token(Some("control-secret".to_string()))
25121            .build()
25122            .expect("control client");
25123
25124        let error = control_only
25125            .register_worker("worker", "queue", vec![], vec![], 1, 1)
25126            .await
25127            .expect_err("control token must not authorize a worker request");
25128        assert!(matches!(
25129            error,
25130            Error::MissingRoleCredentials { role: "worker", .. }
25131        ));
25132        assert_eq!(server.request_count("/api/worker/register"), 0);
25133
25134        let worker_only = Client::builder(server.base_url())
25135            .worker_token(Some("worker-secret".to_string()))
25136            .build()
25137            .expect("worker client");
25138        let error = worker_only
25139            .health()
25140            .await
25141            .expect_err("worker token must not authorize a control request");
25142        assert!(matches!(
25143            error,
25144            Error::MissingRoleCredentials {
25145                role: "control",
25146                ..
25147            }
25148        ));
25149        assert_eq!(server.request_count("/api/health"), 0);
25150    }
25151
25152    #[tokio::test]
25153    async fn shared_token_supports_worker_and_control_planes() {
25154        let server = MockWorkerServer::start();
25155        let client = Client::builder(server.base_url())
25156            .token(Some("shared-secret".to_string()))
25157            .build()
25158            .expect("client");
25159
25160        client.health().await.expect("control request");
25161        client
25162            .register_worker("worker", "queue", vec![], vec![], 1, 1)
25163            .await
25164            .expect("worker request");
25165
25166        assert_eq!(
25167            server.authorization_for("/api/health").as_deref(),
25168            Some("Bearer shared-secret")
25169        );
25170        assert_eq!(
25171            server.control_protocol_for("/api/health").as_deref(),
25172            Some(CONTROL_PLANE_VERSION)
25173        );
25174        assert_eq!(
25175            server.authorization_for("/api/worker/register").as_deref(),
25176            Some("Bearer shared-secret")
25177        );
25178        assert_eq!(
25179            server
25180                .worker_protocol_for("/api/worker/register")
25181                .as_deref(),
25182            Some(WORKER_PROTOCOL_VERSION)
25183        );
25184    }
25185
25186    #[tokio::test]
25187    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
25188        let server = MockWorkerServer::start();
25189        let client = Client::builder(server.base_url())
25190            .timeout(Duration::from_secs(2))
25191            .build()
25192            .expect("client");
25193
25194        client
25195            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
25196            .await
25197            .expect("register");
25198        client
25199            .heartbeat_worker("capture-worker", 1, 1)
25200            .await
25201            .expect("heartbeat");
25202        client
25203            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
25204            .await
25205            .expect("workflow poll");
25206        client
25207            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
25208            .await
25209            .expect("activity poll");
25210
25211        for path in [
25212            "/api/worker/register",
25213            "/api/worker/heartbeat",
25214            "/api/worker/workflow-tasks/poll",
25215            "/api/worker/activity-tasks/poll",
25216        ] {
25217            assert_eq!(
25218                server.worker_protocol_for(path).as_deref(),
25219                Some(WORKER_PROTOCOL_VERSION),
25220                "unexpected protocol for {path}"
25221            );
25222        }
25223
25224        assert_eq!(
25225            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
25226            1
25227        );
25228        assert_eq!(
25229            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
25230            500
25231        );
25232        assert_eq!(
25233            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
25234            1
25235        );
25236        assert!(
25237            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
25238                .as_str()
25239                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
25240        );
25241        assert!(
25242            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
25243                .as_str()
25244                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
25245        );
25246    }
25247
25248    #[tokio::test]
25249    async fn query_task_endpoints_send_the_query_feature_protocol() {
25250        let server = MockWorkerServer::start();
25251        let client = Client::builder(server.base_url())
25252            .timeout(Duration::from_secs(2))
25253            .build()
25254            .expect("client");
25255
25256        client
25257            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
25258            .await
25259            .expect("query poll");
25260        client
25261            .complete_query_task(
25262                "query-capture",
25263                "capture-worker",
25264                1,
25265                json!(8),
25266                DEFAULT_CODEC,
25267            )
25268            .await
25269            .expect("query complete");
25270        client
25271            .fail_query_task(
25272                "query-capture",
25273                "capture-worker",
25274                1,
25275                "failed",
25276                "query_rejected",
25277                "QueryFailed",
25278            )
25279            .await
25280            .expect("query fail");
25281
25282        for path in [
25283            "/api/worker/query-tasks/poll",
25284            "/api/worker/query-tasks/query-capture/complete",
25285            "/api/worker/query-tasks/query-capture/fail",
25286        ] {
25287            assert_eq!(
25288                server.worker_protocol_for(path).as_deref(),
25289                Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
25290                "unexpected protocol for {path}"
25291            );
25292        }
25293
25294        assert_eq!(
25295            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
25296            1
25297        );
25298        assert!(
25299            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
25300                .as_str()
25301                .is_some_and(|id| id.starts_with("rust-query-poll-"))
25302        );
25303    }
25304
25305    #[tokio::test]
25306    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
25307        let server = MockWorkerServer::transient_worker_failures();
25308        let client = Client::builder(server.base_url())
25309            .timeout(Duration::from_secs(2))
25310            .build()
25311            .expect("client");
25312
25313        client
25314            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
25315            .await
25316            .expect("workflow poll retry");
25317        client
25318            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
25319            .await
25320            .expect("activity poll retry");
25321        client
25322            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
25323            .await
25324            .expect("query poll retry");
25325
25326        for path in [
25327            "/api/worker/workflow-tasks/poll",
25328            "/api/worker/activity-tasks/poll",
25329            "/api/worker/query-tasks/poll",
25330        ] {
25331            let bodies = server.request_bodies(path);
25332            assert_eq!(bodies.len(), 2, "{path} must be retried once");
25333            assert_eq!(
25334                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
25335                "{path} must preserve the request binding across retry"
25336            );
25337        }
25338    }
25339
25340    #[tokio::test]
25341    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
25342        let server = MockWorkerServer::consecutive_poll_failures(2);
25343        let client = Client::builder(server.base_url())
25344            .timeout(Duration::from_secs(2))
25345            .build()
25346            .expect("client");
25347        let mut worker = Worker::new(client, "capture")
25348            .worker_id("capture-worker")
25349            .poll_timeout(Duration::from_millis(10))
25350            .retry_policy(WorkerRetryPolicy {
25351                max_retries: 2,
25352                initial_backoff: Duration::from_millis(1),
25353                max_backoff: Duration::from_millis(1),
25354            });
25355        worker.register_workflow(
25356            "capture.workflow",
25357            |_ctx, _input| async move { Ok(Value::Null) },
25358        );
25359        worker.register_activity(
25360            "capture.activity",
25361            |_ctx, _input| async move { Ok(Value::Null) },
25362        );
25363        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
25364            Ok(Value::Null)
25365        });
25366
25367        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
25368
25369        for path in [
25370            "/api/worker/workflow-tasks/poll",
25371            "/api/worker/activity-tasks/poll",
25372            "/api/worker/query-tasks/poll",
25373        ] {
25374            let bodies = server.request_bodies(path);
25375            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
25376            assert!(
25377                bodies
25378                    .iter()
25379                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
25380                "{path} must preserve one request binding across every retry"
25381            );
25382        }
25383    }
25384
25385    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
25386        let reason = if unavailable {
25387            "storage_admission_unavailable"
25388        } else {
25389            "storage_pressure"
25390        };
25391        let mut body = json!({
25392            "reason": reason,
25393            "storage_state": if unavailable { "fenced" } else { "draining" },
25394            "retryable": true,
25395            "retry_after_seconds": 1,
25396        });
25397        if !mid_poll {
25398            body["request_admitted"] = json!(false);
25399        }
25400        if let Some(id) = poll_id {
25401            body["task"] = Value::Null;
25402            body["poll_status"] = json!(reason);
25403            body["poll_request_id"] = json!(id);
25404            body["retry_same_poll_request_id"] = json!(true);
25405            body["claim_admitted"] = json!(false);
25406        }
25407        body
25408    }
25409
25410    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
25411        let operation = match path {
25412            "/api/worker/register" => "register_worker",
25413            "/api/worker/heartbeat" => "heartbeat_worker",
25414            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
25415            "/api/worker/activity-tasks/poll" => "poll_activity_task",
25416            "/api/worker/query-tasks/poll" => "poll_query_task",
25417            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
25418            _ => return None,
25419        };
25420        let request: Value = serde_json::from_str(request).ok()?;
25421        let mut response = json!({
25422            "reason": "backend_unavailable",
25423            "operation": operation,
25424            "outcome": "unknown",
25425            "retryable": true,
25426            "retry_after_seconds": 1,
25427            "worker_id": request["worker_id"],
25428            "task_queue": request.get("task_queue"),
25429        });
25430        if path.ends_with("/poll") {
25431            response["task"] = Value::Null;
25432            response["poll_status"] = json!("backend_unavailable");
25433            response["poll_request_id"] = request["poll_request_id"].clone();
25434            response["retry_same_poll_request_id"] = json!(true);
25435        }
25436        Some(response)
25437    }
25438
25439    fn backend_retry_override(
25440        path: &str,
25441        request: &str,
25442        number: usize,
25443    ) -> Option<(&'static str, String)> {
25444        if number > 8 {
25445            return None;
25446        }
25447        Some((
25448            "503 Service Unavailable",
25449            backend_refusal(path, request)?.to_string(),
25450        ))
25451    }
25452
25453    fn backend_unavailable_override(
25454        path: &str,
25455        request: &str,
25456        _number: usize,
25457    ) -> Option<(&'static str, String)> {
25458        Some((
25459            "503 Service Unavailable",
25460            backend_refusal(path, request)?.to_string(),
25461        ))
25462    }
25463
25464    fn storage_worker(server: &MockWorkerServer) -> Worker {
25465        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
25466            .worker_id("storage-worker")
25467            .retry_policy(WorkerRetryPolicy {
25468                max_retries: 1,
25469                initial_backoff: Duration::from_millis(1),
25470                max_backoff: Duration::from_millis(1),
25471            })
25472    }
25473
25474    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
25475        let requests = server.requests.lock().expect("requests");
25476        let bodies: Vec<_> = requests
25477            .iter()
25478            .filter(|request| request.path == path)
25479            .map(|request| &request.body)
25480            .collect();
25481        assert_eq!(bodies.len(), count, "{path}");
25482        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
25483    }
25484
25485    #[test]
25486    fn backend_recovery_requires_the_explicit_worker_contract() {
25487        for (path, operation) in [
25488            ("/worker/register", "register_worker"),
25489            ("/worker/heartbeat", "heartbeat_worker"),
25490            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
25491            ("/worker/activity-tasks/poll", "poll_activity_task"),
25492            ("/worker/query-tasks/poll", "poll_query_task"),
25493            (
25494                "/worker/update-validation-tasks/poll",
25495                "poll_update_validation_task",
25496            ),
25497        ] {
25498            let poll_id = path.ends_with("/poll").then_some("same-poll");
25499            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
25500            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
25501                .expect("worker operation");
25502            assert_eq!(body["operation"], operation);
25503            let error = Error::Http {
25504                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
25505                body: body.to_string(),
25506            };
25507            assert_eq!(
25508                worker_backend_unavailable_retry_after(&error, path, poll_id),
25509                Some(Duration::from_secs(1))
25510            );
25511            assert!(!worker_operation_is_retryable(&error));
25512            for (field, value) in [
25513                ("operation", json!("wrong_operation")),
25514                ("outcome", json!("completed")),
25515                ("retryable", json!(false)),
25516                ("retry_after_seconds", json!(0)),
25517                ("worker_id", json!("")),
25518            ] {
25519                let mut invalid = body.clone();
25520                invalid[field] = value;
25521                let error = Error::Http {
25522                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
25523                    body: invalid.to_string(),
25524                };
25525                assert!(
25526                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
25527                    "{path}: {field}"
25528                );
25529                assert!(!worker_operation_is_retryable(&error));
25530            }
25531            if let Some(poll_id) = poll_id {
25532                for (field, value) in [
25533                    ("poll_request_id", json!("wrong-poll")),
25534                    ("poll_status", json!("empty")),
25535                    ("task", json!({"task_id":"claimed"})),
25536                    ("retry_same_poll_request_id", json!(false)),
25537                ] {
25538                    let mut invalid = body.clone();
25539                    invalid[field] = value;
25540                    let error = Error::Http {
25541                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
25542                        body: invalid.to_string(),
25543                    };
25544                    assert!(
25545                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
25546                            .is_none(),
25547                        "{path}: {field}"
25548                    );
25549                }
25550            }
25551            let error = Error::Http {
25552                status: reqwest::StatusCode::UNAUTHORIZED,
25553                body: body.to_string(),
25554            };
25555            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
25556            assert!(!worker_operation_is_retryable(&error));
25557        }
25558    }
25559
25560    #[tokio::test]
25561    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
25562        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25563            request_override: Some(backend_retry_override),
25564            ..MockWorkerBehavior::default()
25565        });
25566        let mut worker =
25567            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
25568        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
25569        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
25570        worker.register_query("backend.workflow", "state", |_, _| async {
25571            Ok(Value::Null)
25572        });
25573        worker.register().await.expect("registration recovery");
25574        worker
25575            .client
25576            .heartbeat_worker("storage-worker", 1, 1)
25577            .await
25578            .expect("heartbeat recovery");
25579        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
25580        for path in [
25581            "/api/worker/register",
25582            "/api/worker/heartbeat",
25583            "/api/worker/workflow-tasks/poll",
25584            "/api/worker/activity-tasks/poll",
25585            "/api/worker/query-tasks/poll",
25586        ] {
25587            assert_identical_requests(&server, path, 9);
25588        }
25589    }
25590
25591    #[tokio::test]
25592    async fn backend_recovery_wait_stops_with_worker() {
25593        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25594            request_override: Some(backend_unavailable_override),
25595            ..MockWorkerBehavior::default()
25596        });
25597        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
25598            max_retries: 1,
25599            initial_backoff: Duration::from_secs(2),
25600            max_backoff: Duration::from_secs(2),
25601        });
25602        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
25603        let started = tokio::time::Instant::now();
25604        let _ = tokio::time::timeout(
25605            Duration::from_secs(1),
25606            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
25607        )
25608        .await
25609        .expect("shutdown interrupts backend wait");
25610        assert!(started.elapsed() < Duration::from_secs(1));
25611        assert!(server.request_count("/api/worker/register") >= 1);
25612    }
25613
25614    #[test]
25615    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
25616        for unavailable in [false, true] {
25617            for mid_poll in [false, true] {
25618                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
25619                let error = Error::Http {
25620                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
25621                    body: body.to_string(),
25622                };
25623                assert_eq!(
25624                    worker_storage_admission_retry_after(&error, Some("same-poll")),
25625                    Some(Duration::from_secs(1))
25626                );
25627                assert!(
25628                    !worker_operation_is_retryable(&error),
25629                    "storage is not a bounded generic retry"
25630                );
25631                for (field, value) in [
25632                    ("poll_request_id", json!("wrong-poll")),
25633                    ("task", json!({"task_id":"claimed"})),
25634                    ("retryable", json!(false)),
25635                    ("retry_after_seconds", json!(0)),
25636                    ("retry_after_seconds", json!(true)),
25637                    ("retry_after_seconds", json!(1.0)),
25638                    ("storage_state", json!("normal")),
25639                    ("poll_status", json!("empty")),
25640                    ("claim_admitted", json!(true)),
25641                    ("retry_same_poll_request_id", json!(false)),
25642                    ("request_admitted", json!(true)),
25643                ] {
25644                    let mut invalid = body.clone();
25645                    invalid[field] = value;
25646                    let error = Error::Http {
25647                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
25648                        body: invalid.to_string(),
25649                    };
25650                    assert!(
25651                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
25652                        "{field}"
25653                    );
25654                }
25655            }
25656        }
25657        let body = storage_refusal(None, false, false);
25658        let error = Error::Http {
25659            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
25660            body: body.to_string(),
25661        };
25662        assert!(worker_storage_admission_retry_after(&error, None).is_some());
25663        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
25664        let error = Error::Http {
25665            status: reqwest::StatusCode::FORBIDDEN,
25666            body: body.to_string(),
25667        };
25668        assert!(worker_storage_admission_retry_after(&error, None).is_none());
25669        let body = storage_refusal(None, false, true);
25670        let error = Error::Http {
25671            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
25672            body: body.to_string(),
25673        };
25674        assert!(worker_storage_admission_retry_after(&error, None).is_none());
25675    }
25676
25677    #[tokio::test]
25678    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
25679        for unavailable in [false, true] {
25680            for mid_poll in [false, true] {
25681                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25682                    poll_failures_per_path: 1,
25683                    storage_refusals: 7,
25684                    storage_path: Some("/poll"),
25685                    storage_unavailable: unavailable,
25686                    storage_mid_poll: mid_poll,
25687                    ..MockWorkerBehavior::default()
25688                });
25689                let mut worker = storage_worker(&server);
25690                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
25691                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
25692                for path in [
25693                    "/api/worker/workflow-tasks/poll",
25694                    "/api/worker/activity-tasks/poll",
25695                    "/api/worker/query-tasks/poll",
25696                ] {
25697                    assert_identical_requests(&server, path, 9);
25698                }
25699            }
25700        }
25701    }
25702
25703    #[tokio::test]
25704    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
25705        struct CountedBody(Arc<AtomicUsize>);
25706        impl Serialize for CountedBody {
25707            fn serialize<S: Serializer>(
25708                &self,
25709                serializer: S,
25710            ) -> std::result::Result<S::Ok, S::Error> {
25711                let count = self.0.fetch_add(1, Ordering::SeqCst);
25712                json!({"serialization":count,"lease_owner":"worker","attempt":7})
25713                    .serialize(serializer)
25714            }
25715        }
25716        for path in [
25717            "/api/worker/register",
25718            "/api/worker/heartbeat",
25719            "/api/worker/workflow-tasks/storage-task/complete",
25720            "/api/worker/workflow-tasks/storage-task/fail",
25721            "/api/worker/activity-tasks/storage-task/complete",
25722            "/api/worker/activity-tasks/storage-task/fail",
25723            "/api/worker/activity-tasks/storage-task/heartbeat",
25724            "/api/worker/query-tasks/storage-task/complete",
25725            "/api/worker/query-tasks/storage-task/fail",
25726        ] {
25727            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25728                storage_refusals: 7,
25729                storage_path: Some(path),
25730                ..MockWorkerBehavior::default()
25731            });
25732            let worker =
25733                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
25734            let calls = Arc::new(AtomicUsize::new(0));
25735            let _: Value = worker
25736                .client
25737                .request_json(
25738                    reqwest::Method::POST,
25739                    &path[4..],
25740                    RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
25741                    Some(&CountedBody(Arc::clone(&calls))),
25742                )
25743                .await
25744                .expect("prepared request recovery");
25745            assert_eq!(calls.load(Ordering::SeqCst), 1);
25746            assert_identical_requests(&server, path, 8);
25747        }
25748        for worker_scope in [false, true] {
25749            let path = if worker_scope {
25750                "/api/health"
25751            } else {
25752                "/api/worker/register"
25753            };
25754            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25755                storage_refusals: usize::MAX,
25756                storage_path: Some(path),
25757                ..MockWorkerBehavior::default()
25758            });
25759            let worker = storage_worker(&server);
25760            let client = worker.client.clone();
25761            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
25762            let error = if worker_scope {
25763                worker
25764                    .client
25765                    .health()
25766                    .await
25767                    .expect_err("control plane is not retried")
25768            } else {
25769                client
25770                    .request_json::<Value, Value>(
25771                        reqwest::Method::POST,
25772                        "/worker/register",
25773                        RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
25774                        Some(&json!({})),
25775                    )
25776                    .await
25777                    .expect_err("direct client is not retried")
25778            };
25779            assert!(worker_storage_admission_body(&error).is_some());
25780            assert_eq!(server.request_count(path), 1);
25781        }
25782    }
25783
25784    #[tokio::test]
25785    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
25786        for fail in [false, true] {
25787            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25788                storage_activity: true,
25789                storage_refusals: 7,
25790                storage_path: Some("/storage-activity/"),
25791                ..MockWorkerBehavior::default()
25792            });
25793            let mut worker = storage_worker(&server);
25794            let calls = Arc::new(AtomicUsize::new(0));
25795            let observed = Arc::clone(&calls);
25796            worker.register_activity("storage.activity", move |ctx, _| {
25797                let calls = Arc::clone(&observed);
25798                async move {
25799                    calls.fetch_add(1, Ordering::SeqCst);
25800                    ctx.heartbeat(json!({"step":2})).await?;
25801                    if fail {
25802                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
25803                    } else {
25804                        Ok(json!({"receipt":true}))
25805                    }
25806                }
25807            });
25808            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
25809            assert_eq!(calls.load(Ordering::SeqCst), 1);
25810            assert_identical_requests(
25811                &server,
25812                "/api/worker/activity-tasks/storage-activity/heartbeat",
25813                8,
25814            );
25815            let suffix = if fail { "fail" } else { "complete" };
25816            assert_identical_requests(
25817                &server,
25818                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
25819                8,
25820            );
25821            let other = if fail { "complete" } else { "fail" };
25822            assert_eq!(
25823                server.request_count(&format!(
25824                    "/api/worker/activity-tasks/storage-activity/{other}"
25825                )),
25826                0
25827            );
25828        }
25829    }
25830
25831    #[tokio::test]
25832    async fn storage_waits_are_interruptible_without_false_activity_failure() {
25833        for path in [
25834            "/api/worker/register",
25835            "/api/worker/heartbeat",
25836            "/api/worker/activity-tasks/poll",
25837            "/api/worker/activity-tasks/storage-activity/heartbeat",
25838            "/api/worker/activity-tasks/storage-activity/complete",
25839        ] {
25840            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25841                storage_activity: true,
25842                storage_refusals: usize::MAX,
25843                storage_path: Some(path),
25844                ..MockWorkerBehavior::default()
25845            });
25846            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
25847            worker.register_activity("storage.activity", |ctx, _| async move {
25848                ctx.heartbeat(json!({"step":2})).await?;
25849                Ok(json!({"receipt":true}))
25850            });
25851            let shutdown = async {
25852                while server.request_count(path) == 0 {
25853                    tokio::time::sleep(Duration::from_millis(1)).await;
25854                }
25855            };
25856            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
25857                .await
25858                .expect("shutdown interrupts admission");
25859            assert!(
25860                result.is_err(),
25861                "a refused operation must not appear acknowledged: {path}, {result:?}"
25862            );
25863            assert_eq!(server.request_count(path), 1);
25864            assert_eq!(
25865                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
25866                0
25867            );
25868            assert_eq!(
25869                server.request_count("/api/worker/registrations/mock-worker"),
25870                usize::from(!path.ends_with("/register"))
25871            );
25872        }
25873    }
25874
25875    #[tokio::test]
25876    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
25877        for fail in [false, true] {
25878            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25879                storage_query: true,
25880                storage_refusals: 7,
25881                storage_path: Some("/storage-query/"),
25882                ..MockWorkerBehavior::default()
25883            });
25884            let mut worker = storage_worker(&server);
25885            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
25886            let calls = Arc::new(AtomicUsize::new(0));
25887            let observed = Arc::clone(&calls);
25888            worker.register_query("storage.workflow", "state", move |_, _| {
25889                let calls = Arc::clone(&observed);
25890                async move {
25891                    calls.fetch_add(1, Ordering::SeqCst);
25892                    if fail {
25893                        Err(Error::WorkerLoop("intentional query failure".to_string()))
25894                    } else {
25895                        Ok(json!({"state":"waiting"}))
25896                    }
25897                }
25898            });
25899            assert_eq!(worker.run_once().await.expect("query settled"), 1);
25900            assert_eq!(calls.load(Ordering::SeqCst), 1);
25901            let suffix = if fail { "fail" } else { "complete" };
25902            assert_identical_requests(
25903                &server,
25904                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
25905                8,
25906            );
25907            let other = if fail { "complete" } else { "fail" };
25908            assert_eq!(
25909                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
25910                0
25911            );
25912        }
25913    }
25914
25915    #[tokio::test]
25916    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
25917        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25918            storage_refusals: 7,
25919            storage_path: Some("/poll"),
25920            unauthorized_polls: true,
25921            ..MockWorkerBehavior::default()
25922        });
25923        let error = storage_worker(&server)
25924            .run_once()
25925            .await
25926            .expect_err("auth remains terminal");
25927        assert!(matches!(
25928            error,
25929            Error::Http {
25930                status: reqwest::StatusCode::UNAUTHORIZED,
25931                ..
25932            }
25933        ));
25934        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
25935
25936        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25937            storage_refusals: 7,
25938            storage_path: Some("/activity-cancel/complete"),
25939            ..MockWorkerBehavior::default()
25940        });
25941        let worker =
25942            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
25943        let error = worker
25944            .client
25945            .complete_activity_task(
25946                "activity-cancel",
25947                "attempt-cancel",
25948                "worker",
25949                json!({}),
25950                DEFAULT_CODEC,
25951            )
25952            .await
25953            .expect_err("cancellation remains terminal");
25954        assert!(activity_task_rejection_is_final(&error));
25955        assert_identical_requests(
25956            &server,
25957            "/api/worker/activity-tasks/activity-cancel/complete",
25958            8,
25959        );
25960
25961        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25962            storage_refusals: usize::MAX,
25963            storage_path: Some("/poll"),
25964            storage_wrong_poll_id: true,
25965            ..MockWorkerBehavior::default()
25966        });
25967        assert!(storage_worker(&server).run_once().await.is_err());
25968        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
25969    }
25970
25971    #[tokio::test]
25972    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
25973        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
25974            storage_refusals: usize::MAX,
25975            storage_path: Some("/poll"),
25976            ..MockWorkerBehavior::default()
25977        });
25978        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
25979        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
25980        let run = tokio::spawn(async move { worker.run().await });
25981        tokio::time::timeout(Duration::from_secs(2), async {
25982            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
25983                tokio::time::sleep(Duration::from_millis(1)).await;
25984            }
25985        })
25986        .await
25987        .expect("poll started");
25988        run.abort();
25989        assert!(run.await.expect_err("cancelled run").is_cancelled());
25990        tokio::time::sleep(Duration::from_millis(250)).await;
25991        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
25992    }
25993
25994    #[tokio::test]
25995    async fn query_protocol_rejection_from_older_server_is_typed() {
25996        let server = MockWorkerServer::reject_query_protocol();
25997        let client = Client::builder(server.base_url())
25998            .timeout(Duration::from_secs(2))
25999            .build()
26000            .expect("client");
26001
26002        let error = client
26003            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26004            .await
26005            .expect_err("server below query protocol floor must reject");
26006        let Error::Protocol(failure) = error else {
26007            panic!("expected typed protocol failure");
26008        };
26009
26010        assert_eq!(failure.status, 400);
26011        assert_eq!(failure.reason, "unsupported_protocol_version");
26012        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
26013        assert_eq!(
26014            failure.requested_version.as_deref(),
26015            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
26016        );
26017        assert_eq!(
26018            server
26019                .worker_protocol_for("/api/worker/query-tasks/poll")
26020                .as_deref(),
26021            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
26022        );
26023    }
26024
26025    #[tokio::test]
26026    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
26027        let server = MockWorkerServer::reject_query_protocol();
26028        let client = Client::builder(server.base_url())
26029            .timeout(Duration::from_secs(2))
26030            .build()
26031            .expect("client");
26032        let mut worker = Worker::new(client, "rust-workers")
26033            .worker_id("baseline-worker")
26034            .poll_timeout(Duration::from_millis(10));
26035
26036        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
26037            Ok(Value::Null)
26038        });
26039
26040        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
26041        assert_eq!(
26042            server
26043                .worker_protocol_for("/api/worker/workflow-tasks/poll")
26044                .as_deref(),
26045            Some(WORKER_PROTOCOL_VERSION)
26046        );
26047        assert_eq!(
26048            server.worker_protocol_for("/api/worker/query-tasks/poll"),
26049            None,
26050            "a worker without query handlers must not use the query-task endpoint"
26051        );
26052    }
26053
26054    #[tokio::test]
26055    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
26056        let server = MockWorkerServer::reject_query_completion();
26057        let client = Client::builder(server.base_url())
26058            .timeout(Duration::from_secs(2))
26059            .build()
26060            .expect("client");
26061
26062        let error = client
26063            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
26064            .await
26065            .expect_err("expired completion must be rejected");
26066        let Error::QueryFailed(failure) = error else {
26067            panic!("expected typed query failure");
26068        };
26069        assert_eq!(failure.status, 409);
26070        assert_eq!(failure.reason, "query_task_timed_out");
26071
26072        let mut worker = Worker::new(client, "rust-workers")
26073            .worker_id("late-worker")
26074            .poll_timeout(Duration::from_millis(10));
26075        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26076        worker.register_query(
26077            "counter",
26078            "current",
26079            |_ctx, _args| async move { Ok(json!(8)) },
26080        );
26081
26082        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
26083        assert_eq!(
26084            worker
26085                .run_once()
26086                .await
26087                .expect("worker continues after late completion"),
26088            0
26089        );
26090        assert_eq!(
26091            server.request_count("/api/worker/query-tasks/query-late/complete"),
26092            2
26093        );
26094        assert_eq!(
26095            server.request_count("/api/worker/query-tasks/query-late/fail"),
26096            0,
26097            "a server completion rejection must not be reported as an encoding failure"
26098        );
26099    }
26100
26101    #[tokio::test]
26102    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
26103        let server = MockWorkerServer::start();
26104        let client = Client::builder(server.base_url())
26105            .timeout(Duration::from_secs(2))
26106            .build()
26107            .expect("client");
26108        let mut worker = Worker::new(client, "rust-workers")
26109            .worker_id("joined-worker")
26110            .poll_timeout(Duration::from_millis(10));
26111        worker.register_workflow(
26112            "joined.workflow",
26113            |_ctx, _input| async move { Ok(Value::Null) },
26114        );
26115        worker.register_activity(
26116            "joined.activity",
26117            |_ctx, _input| async move { Ok(Value::Null) },
26118        );
26119        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
26120            Ok(Value::Null)
26121        });
26122
26123        worker
26124            .run_until(tokio::time::sleep(Duration::from_millis(20)))
26125            .await
26126            .expect("normal shutdown");
26127
26128        let deregistration_path = "/api/worker/registrations/mock-worker";
26129        assert_eq!(server.request_count(deregistration_path), 1);
26130        for poll_path in [
26131            "/api/worker/workflow-tasks/poll",
26132            "/api/worker/activity-tasks/poll",
26133            "/api/worker/query-tasks/poll",
26134        ] {
26135            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
26136        }
26137        assert_eq!(
26138            server.captured_paths().last().map(String::as_str),
26139            Some(deregistration_path),
26140            "deregistration must start only after every poller has joined"
26141        );
26142    }
26143
26144    #[tokio::test]
26145    async fn registration_failure_does_not_deregister() {
26146        let server = MockWorkerServer::rejected_registration();
26147        let client = Client::builder(server.base_url())
26148            .timeout(Duration::from_secs(2))
26149            .build()
26150            .expect("client");
26151        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
26152
26153        let error = worker
26154            .run_until(async {})
26155            .await
26156            .expect_err("registration must fail");
26157        assert!(matches!(
26158            error,
26159            Error::Http {
26160                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26161                ..
26162            }
26163        ));
26164        assert!(server
26165            .captured_paths()
26166            .iter()
26167            .all(|path| !path.starts_with("/api/worker/registrations/")));
26168    }
26169
26170    #[tokio::test]
26171    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
26172        let server = MockWorkerServer::rejected_registration_protocol();
26173        let client = Client::builder(server.base_url())
26174            .timeout(Duration::from_secs(2))
26175            .build()
26176            .expect("client");
26177        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
26178
26179        let error = worker
26180            .run_until(async {})
26181            .await
26182            .expect_err("a protocol 1.16 server must reject this worker");
26183        let Error::Protocol(failure) = error else {
26184            panic!("expected typed protocol rejection");
26185        };
26186        assert_eq!(failure.reason, "unsupported_protocol_version");
26187        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
26188        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
26189        assert_eq!(
26190            server
26191                .worker_protocol_for("/api/worker/register")
26192                .as_deref(),
26193            Some(WORKER_PROTOCOL_VERSION)
26194        );
26195    }
26196
26197    #[tokio::test]
26198    async fn declined_registration_does_not_deregister() {
26199        let server = MockWorkerServer::declined_registration();
26200        let client = Client::builder(server.base_url())
26201            .timeout(Duration::from_secs(2))
26202            .build()
26203            .expect("client");
26204        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
26205
26206        let error = worker
26207            .run_until(async {})
26208            .await
26209            .expect_err("declined registration must fail");
26210        assert!(matches!(error, Error::WorkerLoop(_)));
26211        assert!(error.to_string().contains("was not accepted"));
26212        assert!(server
26213            .captured_paths()
26214            .iter()
26215            .all(|path| !path.starts_with("/api/worker/registrations/")));
26216    }
26217
26218    #[tokio::test]
26219    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
26220        let server = MockWorkerServer::rejected_deregistration();
26221        let client = Client::builder(server.base_url())
26222            .timeout(Duration::from_secs(2))
26223            .build()
26224            .expect("client");
26225        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
26226
26227        let error = worker
26228            .run_until(async {})
26229            .await
26230            .expect_err("deregistration must fail");
26231        assert!(matches!(
26232            error,
26233            Error::Http {
26234                status: reqwest::StatusCode::FORBIDDEN,
26235                ..
26236            }
26237        ));
26238        assert_eq!(
26239            server.request_count("/api/worker/registrations/mock-worker"),
26240            1
26241        );
26242    }
26243
26244    #[tokio::test]
26245    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
26246        let server = MockWorkerServer::rejected_deregistration_protocol();
26247        let client = Client::builder(server.base_url())
26248            .timeout(Duration::from_secs(2))
26249            .build()
26250            .expect("client");
26251        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
26252
26253        let error = worker
26254            .run_until(async {})
26255            .await
26256            .expect_err("protocol rejection must fail shutdown");
26257        let Error::Protocol(failure) = error else {
26258            panic!("expected typed protocol failure");
26259        };
26260        assert_eq!(failure.reason, "unsupported_protocol_version");
26261        assert_eq!(
26262            failure.requested_version.as_deref(),
26263            Some(WORKER_PROTOCOL_VERSION)
26264        );
26265        assert_eq!(
26266            server.request_count("/api/worker/registrations/mock-worker"),
26267            1
26268        );
26269    }
26270
26271    #[tokio::test]
26272    async fn primary_poller_error_retains_deregistration_failure_context() {
26273        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
26274        let client = Client::builder(server.base_url())
26275            .timeout(Duration::from_secs(2))
26276            .build()
26277            .expect("client");
26278        let mut worker = Worker::new(client, "rust-workers")
26279            .worker_id("combined-failure")
26280            .poll_timeout(Duration::from_millis(10));
26281        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
26282            Ok(Value::Null)
26283        });
26284
26285        let error = worker
26286            .run()
26287            .await
26288            .expect_err("worker and cleanup must fail");
26289        let summary = error.to_string();
26290        assert!(summary.contains("authentication_failed"));
26291        assert!(summary.contains("worker cannot deregister"));
26292        let Error::WorkerShutdown {
26293            primary,
26294            deregistration,
26295        } = error
26296        else {
26297            panic!("expected combined worker shutdown error");
26298        };
26299        assert!(matches!(
26300            *primary,
26301            Error::Http {
26302                status: reqwest::StatusCode::UNAUTHORIZED,
26303                ..
26304            }
26305        ));
26306        assert!(matches!(
26307            *deregistration,
26308            Error::Http {
26309                status: reqwest::StatusCode::FORBIDDEN,
26310                ..
26311            }
26312        ));
26313        assert_eq!(
26314            server.request_count("/api/worker/registrations/mock-worker"),
26315            1
26316        );
26317    }
26318
26319    #[tokio::test]
26320    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
26321        let server = MockWorkerServer::start();
26322        let client = Client::builder(server.base_url())
26323            .timeout(Duration::from_secs(2))
26324            .build()
26325            .expect("client");
26326        let mut worker = Worker::new(client, "rust-workers")
26327            .worker_id("activity-only-worker")
26328            .poll_timeout(Duration::from_millis(10));
26329
26330        worker.register_activity(
26331            "activity.only",
26332            |_ctx, _args| async move { Ok(Value::Null) },
26333        );
26334
26335        worker.run_until(async {}).await.expect("run worker");
26336    }
26337
26338    #[tokio::test]
26339    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
26340        let server = MockWorkerServer::start();
26341        let client = Client::builder(server.base_url())
26342            .timeout(Duration::from_secs(2))
26343            .build()
26344            .expect("client");
26345        let mut worker = Worker::new(client, "rust-workers")
26346            .worker_id("workflow-only-worker")
26347            .poll_timeout(Duration::from_millis(10));
26348
26349        worker.register_workflow(
26350            "workflow.only",
26351            |_ctx, _input| async move { Ok(Value::Null) },
26352        );
26353
26354        worker.run_until(async {}).await.expect("run worker");
26355    }
26356
26357    #[tokio::test]
26358    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
26359        let server = MockWorkerServer::start();
26360        let client = Client::builder(server.base_url())
26361            .timeout(Duration::from_secs(2))
26362            .build()
26363            .expect("client");
26364        let observations = Arc::new(Mutex::new(Vec::new()));
26365        let observed = Arc::clone(&observations);
26366        let mut worker = Worker::new(client, "rust-workers")
26367            .worker_id("observed-heartbeat-worker")
26368            .poll_timeout(Duration::from_millis(10))
26369            .on_worker_heartbeat(move |observation| {
26370                observed
26371                    .lock()
26372                    .expect("heartbeat observations")
26373                    .push(observation.clone());
26374            });
26375
26376        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
26377            Ok(Value::Null)
26378        });
26379        let acknowledged = Arc::clone(&observations);
26380        worker
26381            .run_until(async move {
26382                tokio::time::timeout(Duration::from_secs(2), async move {
26383                    loop {
26384                        if !acknowledged
26385                            .lock()
26386                            .expect("heartbeat observations")
26387                            .is_empty()
26388                        {
26389                            break;
26390                        }
26391                        tokio::time::sleep(Duration::from_millis(1)).await;
26392                    }
26393                })
26394                .await
26395                .expect("heartbeat acknowledgement within timeout");
26396            })
26397            .await
26398            .expect("run worker");
26399
26400        let observations = observations.lock().expect("heartbeat observations");
26401        let first = observations.first().expect("heartbeat acknowledgement");
26402        assert_eq!(first.worker_id, "observed-heartbeat-worker");
26403        assert_eq!(first.task_queue, "rust-workers");
26404        assert!(first.acknowledged_at_unix_millis > 0);
26405        assert_eq!(first.acknowledgement, json!({}));
26406    }
26407
26408    #[tokio::test]
26409    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
26410        let server = MockWorkerServer::delayed_heartbeat_worker();
26411        let client = Client::builder(server.base_url())
26412            .timeout(Duration::from_secs(3))
26413            .build()
26414            .expect("client");
26415        let observations = Arc::new(Mutex::new(Vec::new()));
26416        let observed = Arc::clone(&observations);
26417        let mut worker = Worker::new(client, "rust-snapshot-workers")
26418            .worker_id("rust-snapshot-worker")
26419            .poll_timeout(Duration::from_millis(10))
26420            .on_worker_heartbeat(move |observation| {
26421                observed
26422                    .lock()
26423                    .expect("heartbeat observations")
26424                    .push(observation.clone());
26425            });
26426
26427        worker.register_workflow("snapshot", |ctx, _input| async move {
26428            ctx.wait_signal("finish").await?;
26429            Ok(json!({"status": "finished"}))
26430        });
26431        worker.register_query("snapshot", "current", |ctx, _args| async move {
26432            Ok(json!(ctx
26433                .signals("increment")
26434                .iter()
26435                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
26436                .sum::<i64>()))
26437        });
26438        worker.register_activity("cancel-aware", |_ctx, _args| async move {
26439            Ok(json!({"late": "completion"}))
26440        });
26441
26442        worker
26443            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
26444            .await
26445            .expect("delayed heartbeat must allow a clean worker shutdown");
26446
26447        let observations = observations.lock().expect("heartbeat observations");
26448        assert!(
26449            observations.len() >= 3,
26450            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
26451        );
26452        assert!(
26453            observations.windows(2).all(|pair| {
26454                pair[1].acknowledged_at_unix_millis
26455                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
26456                    >= 850
26457            }),
26458            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
26459        );
26460        drop(observations);
26461
26462        let heartbeat_times = server.request_times("/api/worker/heartbeat");
26463        let delayed_request_at = *heartbeat_times
26464            .get(1)
26465            .expect("intentionally delayed heartbeat request");
26466        let delay_window_start = delayed_request_at + Duration::from_millis(100);
26467        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
26468        for path in [
26469            "/api/worker/workflow-tasks/poll",
26470            "/api/worker/activity-tasks/poll",
26471            "/api/worker/query-tasks/poll",
26472        ] {
26473            assert!(
26474                server
26475                    .request_times(path)
26476                    .iter()
26477                    .any(|received_at| *received_at >= delay_window_start
26478                        && *received_at <= delay_window_end),
26479                "{path} must keep polling while a heartbeat acknowledgement is delayed"
26480            );
26481        }
26482        assert!(
26483            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
26484            "workflow work must be settled"
26485        );
26486        assert!(
26487            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
26488            "activity work must be settled"
26489        );
26490        assert!(
26491            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
26492            "query work must be settled"
26493        );
26494    }
26495
26496    #[tokio::test]
26497    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
26498        let server = MockWorkerServer::heartbeat_retry_worker();
26499        let client = Client::builder(server.base_url())
26500            .timeout(Duration::from_secs(2))
26501            .build()
26502            .expect("client");
26503        let observations = Arc::new(Mutex::new(Vec::new()));
26504        let observed = Arc::clone(&observations);
26505        let worker = Worker::new(client, "rust-workers")
26506            .worker_id("heartbeat-retry-worker")
26507            .retry_policy(WorkerRetryPolicy {
26508                max_retries: 1,
26509                initial_backoff: Duration::from_millis(300),
26510                max_backoff: Duration::from_millis(300),
26511            })
26512            .on_worker_heartbeat(move |observation| {
26513                observed
26514                    .lock()
26515                    .expect("heartbeat observations")
26516                    .push(observation.clone());
26517            });
26518
26519        worker
26520            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
26521            .await
26522            .expect("retryable heartbeat failure must remain bounded and recover");
26523
26524        let observations = observations.lock().expect("heartbeat observations");
26525        assert!(observations.len() >= 3, "heartbeat retry must recover");
26526        assert!(
26527            observations.windows(2).all(|pair| {
26528                pair[1]
26529                    .acknowledged_at_unix_millis
26530                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
26531                    >= 850
26532            }),
26533            "a successful retry must start a fresh advertised cadence: {observations:?}"
26534        );
26535        assert_eq!(
26536            server.request_count("/api/worker/heartbeat"),
26537            observations.len() + 1,
26538            "one retryable failure must add exactly one bounded request"
26539        );
26540    }
26541
26542    #[tokio::test]
26543    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
26544        let server = MockWorkerServer::waiting_query_worker();
26545        let client = Client::builder(server.base_url())
26546            .timeout(Duration::from_secs(2))
26547            .build()
26548            .expect("client");
26549        let observations = Arc::new(Mutex::new(Vec::new()));
26550        let observed = Arc::clone(&observations);
26551        let mut worker = Worker::new(client, "rust-snapshot-workers")
26552            .worker_id("rust-snapshot-worker")
26553            .poll_timeout(Duration::from_millis(10))
26554            .on_worker_heartbeat(move |observation| {
26555                observed
26556                    .lock()
26557                    .expect("heartbeat observations")
26558                    .push(observation.clone());
26559            });
26560
26561        worker.register_workflow("snapshot", |ctx, _input| async move {
26562            ctx.wait_signal("finish").await?;
26563            Ok(json!({"status": "finished"}))
26564        });
26565        worker.register_query("snapshot", "current", |ctx, _args| async move {
26566            let current = ctx
26567                .signals("increment")
26568                .iter()
26569                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
26570                .sum::<i64>();
26571            Ok(json!(current))
26572        });
26573        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
26574
26575        worker
26576            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
26577            .await
26578            .expect("pending workflow and query poller must remain live until shutdown");
26579
26580        assert!(
26581            observations.lock().expect("heartbeat observations").len() >= 4,
26582            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
26583        );
26584        assert!(
26585            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
26586            "workflow polling must continue after empty replay acknowledgements"
26587        );
26588        assert!(
26589            server.request_count("/api/worker/query-tasks/poll") >= 2,
26590            "query polling must continue after serving the current query"
26591        );
26592        assert_eq!(
26593            server.request_body("/api/worker/register")["capabilities"],
26594            json!([
26595                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
26596                DURABLE_SELECTION_CAPABILITY,
26597                MEMO_UPSERTS_CAPABILITY,
26598                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
26599                QUERY_TASKS_CAPABILITY,
26600                WORKFLOW_UPDATES_CAPABILITY,
26601                MESSAGE_STREAMS_CAPABILITY
26602            ])
26603        );
26604        assert_eq!(
26605            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
26606            json!({
26607                "queries": ["current"],
26608                "query_contracts": [],
26609                "signals": [],
26610                "signal_contracts": [],
26611                "updates": ["replace"],
26612                "update_contracts": [],
26613                "update_validators": [],
26614            })
26615        );
26616
26617        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
26618        assert_eq!(
26619            opened["commands"],
26620            json!([{
26621                "type": "open_signal_wait",
26622                "signal_name": "finish",
26623            }])
26624        );
26625
26626        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
26627            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
26628            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
26629            let failure = server.request_body(&fail_path);
26630            assert_eq!(
26631                failure["failure"]["type"],
26632                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
26633            );
26634            assert_eq!(server.request_count(&completion_path), 0);
26635        }
26636
26637        let query_completion =
26638            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
26639        assert_eq!(query_completion["result"], json!(8));
26640
26641        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
26642        assert_eq!(
26643            server.request_count(terminal_path),
26644            1,
26645            "the matching signal must settle the workflow exactly once"
26646        );
26647        let terminal = server.request_body(terminal_path);
26648        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
26649        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
26650        assert_eq!(
26651            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
26652                .expect("terminal workflow result"),
26653            json!({"status": "finished"})
26654        );
26655    }
26656
26657    #[tokio::test]
26658    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
26659        let server = MockWorkerServer::transient_worker_failures();
26660        let client = Client::builder(server.base_url())
26661            .timeout(Duration::from_secs(2))
26662            .build()
26663            .expect("client");
26664        let mut worker = Worker::new(client, "rust-workers")
26665            .worker_id("retry-worker")
26666            .poll_timeout(Duration::from_millis(10))
26667            .retry_policy(WorkerRetryPolicy {
26668                max_retries: 2,
26669                initial_backoff: Duration::from_millis(1),
26670                max_backoff: Duration::from_millis(1),
26671            });
26672        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26673        worker.register_activity(
26674            "counter.activity",
26675            |_ctx, _input| async move { Ok(Value::Null) },
26676        );
26677        worker.register_query(
26678            "counter",
26679            "current",
26680            |_ctx, _args| async move { Ok(json!(8)) },
26681        );
26682
26683        worker
26684            .run_until(tokio::time::sleep(Duration::from_millis(75)))
26685            .await
26686            .expect("transient failures must not stop the worker");
26687
26688        for path in [
26689            "/api/worker/heartbeat",
26690            "/api/worker/workflow-tasks/poll",
26691            "/api/worker/activity-tasks/poll",
26692            "/api/worker/query-tasks/poll",
26693        ] {
26694            assert!(
26695                server.request_count(path) >= 2,
26696                "{path} must continue after its transient failure"
26697            );
26698        }
26699    }
26700
26701    #[tokio::test]
26702    async fn worker_continues_after_long_poll_capacity_backpressure() {
26703        let server = MockWorkerServer::capacity_limited_activity_poll();
26704        let client = Client::builder(server.base_url())
26705            .timeout(Duration::from_secs(2))
26706            .build()
26707            .expect("client");
26708        let mut worker = Worker::new(client, "rust-workers")
26709            .worker_id("capacity-worker")
26710            .poll_timeout(Duration::from_millis(10))
26711            .retry_policy(WorkerRetryPolicy {
26712                max_retries: 0,
26713                initial_backoff: Duration::from_millis(1),
26714                max_backoff: Duration::from_millis(1),
26715            });
26716        worker.register_activity("capacity.activity", |_ctx, _input| async move {
26717            Ok(json!({"handled": true}))
26718        });
26719
26720        worker
26721            .run_until(tokio::time::sleep(Duration::from_millis(50)))
26722            .await
26723            .expect("capacity backpressure must not stop the worker");
26724
26725        assert!(
26726            server.request_count("/api/worker/activity-tasks/poll") >= 2,
26727            "the activity poller must continue after capacity backpressure"
26728        );
26729        assert_eq!(
26730            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
26731            1,
26732            "the worker must complete work returned after capacity recovers"
26733        );
26734    }
26735
26736    #[test]
26737    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
26738        let capacity = Error::Http {
26739            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
26740            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
26741        };
26742        assert_eq!(
26743            worker_poll_capacity_retry_after(&capacity),
26744            Some(Duration::from_secs(3))
26745        );
26746
26747        let rejected_capacity = Error::Http {
26748            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
26749            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
26750        };
26751        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
26752        assert!(!worker_operation_is_retryable(&rejected_capacity));
26753
26754        let ordinary_rate_limit = Error::Http {
26755            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
26756            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
26757                .to_string(),
26758        };
26759        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
26760        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
26761    }
26762
26763    #[tokio::test]
26764    async fn worker_bounds_transport_retries() {
26765        let server = MockWorkerServer::unavailable_polls();
26766        let client = Client::builder(server.base_url())
26767            .timeout(Duration::from_secs(2))
26768            .build()
26769            .expect("client");
26770        let mut worker = Worker::new(client, "rust-workers")
26771            .worker_id("bounded-retry-worker")
26772            .poll_timeout(Duration::from_millis(10))
26773            .retry_policy(WorkerRetryPolicy {
26774                max_retries: 2,
26775                initial_backoff: Duration::from_millis(1),
26776                max_backoff: Duration::from_millis(1),
26777            });
26778        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26779
26780        let error = worker.run().await.expect_err("retry bound must terminate");
26781        assert!(matches!(error, Error::Transport(_)));
26782        assert_eq!(
26783            server.request_count("/api/worker/workflow-tasks/poll"),
26784            3,
26785            "one initial request plus exactly two retries"
26786        );
26787    }
26788
26789    #[tokio::test]
26790    async fn worker_retry_policy_can_disable_poll_retries() {
26791        let server = MockWorkerServer::unavailable_polls();
26792        let client = Client::builder(server.base_url())
26793            .timeout(Duration::from_secs(2))
26794            .build()
26795            .expect("client");
26796        let mut worker = Worker::new(client, "rust-workers")
26797            .worker_id("no-retry-worker")
26798            .poll_timeout(Duration::from_millis(10))
26799            .retry_policy(WorkerRetryPolicy {
26800                max_retries: 0,
26801                initial_backoff: Duration::from_millis(1),
26802                max_backoff: Duration::from_millis(1),
26803            });
26804        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26805
26806        let error = worker
26807            .run_once()
26808            .await
26809            .expect_err("disabled retries must return the first transport failure");
26810        assert!(matches!(error, Error::Transport(_)));
26811        assert_eq!(
26812            server.request_count("/api/worker/workflow-tasks/poll"),
26813            1,
26814            "max_retries=0 must send only the initial request"
26815        );
26816    }
26817
26818    #[tokio::test]
26819    async fn worker_does_not_retry_authentication_failures() {
26820        let server = MockWorkerServer::unauthorized_polls();
26821        let client = Client::builder(server.base_url())
26822            .timeout(Duration::from_secs(2))
26823            .build()
26824            .expect("client");
26825        let mut worker = Worker::new(client, "rust-workers")
26826            .worker_id("unauthorized-worker")
26827            .poll_timeout(Duration::from_millis(10));
26828        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26829
26830        let error = worker
26831            .run()
26832            .await
26833            .expect_err("authentication must terminate");
26834        let Error::Http { status, body } = error else {
26835            panic!("expected stable HTTP authentication error");
26836        };
26837        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
26838        assert!(body.contains("authentication_failed"));
26839        assert_eq!(
26840            server.request_count("/api/worker/workflow-tasks/poll"),
26841            1,
26842            "authentication failures must not be retried"
26843        );
26844    }
26845
26846    #[derive(Clone, Debug)]
26847    struct CapturedRequest {
26848        headers: String,
26849        method: String,
26850        path: String,
26851        authorization: Option<String>,
26852        namespace: Option<String>,
26853        worker_protocol: Option<String>,
26854        control_protocol: Option<String>,
26855        body: String,
26856        received_at: Instant,
26857    }
26858
26859    struct MockWorkerServer {
26860        addr: SocketAddr,
26861        stop: Arc<AtomicBool>,
26862        requests: Arc<Mutex<Vec<CapturedRequest>>>,
26863        thread: Option<thread::JoinHandle<()>>,
26864    }
26865
26866    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
26867
26868    #[derive(Clone, Copy, Default)]
26869    struct MockWorkerBehavior {
26870        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
26871        request_override: Option<RequestOverride>,
26872        storage_refusals: usize,
26873        storage_path: Option<&'static str>,
26874        storage_unavailable: bool,
26875        storage_mid_poll: bool,
26876        storage_activity: bool,
26877        storage_query: bool,
26878        storage_wrong_poll_id: bool,
26879        reject_query_protocol: bool,
26880        reject_query_completion: bool,
26881        waiting_query_worker: bool,
26882        decline_registration: bool,
26883        complete_named_signal: bool,
26884        poll_failures_per_path: usize,
26885        long_poll_capacity_responses_per_path: usize,
26886        heartbeat_failures: usize,
26887        heartbeat_failure_request: Option<usize>,
26888        delayed_heartbeat_request: Option<usize>,
26889        heartbeat_response_delay: Duration,
26890        concurrent_requests: bool,
26891        unauthorized_polls: bool,
26892        reject_registration: bool,
26893        reject_registration_protocol: bool,
26894        reject_deregistration: bool,
26895        reject_deregistration_protocol: bool,
26896        cancelled_activity: bool,
26897        draining_polls: bool,
26898        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
26899        workflow_completion_status: Option<&'static str>,
26900        workflow_completion_body: Option<&'static str>,
26901    }
26902
26903    impl MockWorkerServer {
26904        fn start() -> Self {
26905            Self::start_with_behavior(MockWorkerBehavior::default())
26906        }
26907
26908        fn reject_query_protocol() -> Self {
26909            Self::start_with_behavior(MockWorkerBehavior {
26910                reject_query_protocol: true,
26911                ..MockWorkerBehavior::default()
26912            })
26913        }
26914
26915        fn reject_query_completion() -> Self {
26916            Self::start_with_behavior(MockWorkerBehavior {
26917                reject_query_completion: true,
26918                ..MockWorkerBehavior::default()
26919            })
26920        }
26921
26922        fn waiting_query_worker() -> Self {
26923            Self::start_with_behavior(MockWorkerBehavior {
26924                waiting_query_worker: true,
26925                complete_named_signal: true,
26926                ..MockWorkerBehavior::default()
26927            })
26928        }
26929
26930        fn transient_worker_failures() -> Self {
26931            Self::start_with_behavior(MockWorkerBehavior {
26932                poll_failures_per_path: 1,
26933                heartbeat_failures: 1,
26934                ..MockWorkerBehavior::default()
26935            })
26936        }
26937
26938        fn consecutive_poll_failures(count: usize) -> Self {
26939            Self::start_with_behavior(MockWorkerBehavior {
26940                poll_failures_per_path: count,
26941                ..MockWorkerBehavior::default()
26942            })
26943        }
26944
26945        fn capacity_limited_activity_poll() -> Self {
26946            Self::start_with_behavior(MockWorkerBehavior {
26947                long_poll_capacity_responses_per_path: 1,
26948                ..MockWorkerBehavior::default()
26949            })
26950        }
26951
26952        fn delayed_heartbeat_worker() -> Self {
26953            Self::start_with_behavior(MockWorkerBehavior {
26954                waiting_query_worker: true,
26955                delayed_heartbeat_request: Some(2),
26956                heartbeat_response_delay: Duration::from_millis(1_500),
26957                concurrent_requests: true,
26958                cancelled_activity: true,
26959                ..MockWorkerBehavior::default()
26960            })
26961        }
26962
26963        fn heartbeat_retry_worker() -> Self {
26964            Self::start_with_behavior(MockWorkerBehavior {
26965                waiting_query_worker: true,
26966                heartbeat_failure_request: Some(2),
26967                concurrent_requests: true,
26968                ..MockWorkerBehavior::default()
26969            })
26970        }
26971
26972        fn unavailable_polls() -> Self {
26973            Self::start_with_behavior(MockWorkerBehavior {
26974                poll_failures_per_path: usize::MAX,
26975                ..MockWorkerBehavior::default()
26976            })
26977        }
26978
26979        fn unauthorized_polls() -> Self {
26980            Self::start_with_behavior(MockWorkerBehavior {
26981                unauthorized_polls: true,
26982                ..MockWorkerBehavior::default()
26983            })
26984        }
26985
26986        fn rejected_registration() -> Self {
26987            Self::start_with_behavior(MockWorkerBehavior {
26988                reject_registration: true,
26989                ..MockWorkerBehavior::default()
26990            })
26991        }
26992
26993        fn rejected_registration_protocol() -> Self {
26994            Self::start_with_behavior(MockWorkerBehavior {
26995                reject_registration_protocol: true,
26996                ..MockWorkerBehavior::default()
26997            })
26998        }
26999
27000        fn declined_registration() -> Self {
27001            Self::start_with_behavior(MockWorkerBehavior {
27002                decline_registration: true,
27003                ..MockWorkerBehavior::default()
27004            })
27005        }
27006
27007        fn rejected_deregistration() -> Self {
27008            Self::start_with_behavior(MockWorkerBehavior {
27009                reject_deregistration: true,
27010                ..MockWorkerBehavior::default()
27011            })
27012        }
27013
27014        fn rejected_deregistration_protocol() -> Self {
27015            Self::start_with_behavior(MockWorkerBehavior {
27016                reject_deregistration_protocol: true,
27017                ..MockWorkerBehavior::default()
27018            })
27019        }
27020
27021        fn unauthorized_polls_and_rejected_deregistration() -> Self {
27022            Self::start_with_behavior(MockWorkerBehavior {
27023                unauthorized_polls: true,
27024                reject_deregistration: true,
27025                ..MockWorkerBehavior::default()
27026            })
27027        }
27028
27029        fn cancelled_activity() -> Self {
27030            Self::start_with_behavior(MockWorkerBehavior {
27031                cancelled_activity: true,
27032                ..MockWorkerBehavior::default()
27033            })
27034        }
27035
27036        fn draining_polls() -> Self {
27037            Self::start_with_behavior(MockWorkerBehavior {
27038                draining_polls: true,
27039                ..MockWorkerBehavior::default()
27040            })
27041        }
27042
27043        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
27044            Self::start_with_behavior(MockWorkerBehavior {
27045                invalid_task_payload_codec: Some(codec),
27046                ..MockWorkerBehavior::default()
27047            })
27048        }
27049
27050        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
27051            Self::start_with_behavior(MockWorkerBehavior {
27052                workflow_completion_status: Some(status),
27053                workflow_completion_body: Some(body),
27054                ..MockWorkerBehavior::default()
27055            })
27056        }
27057
27058        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
27059            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
27060            listener
27061                .set_nonblocking(true)
27062                .expect("configure mock listener");
27063            let addr = listener.local_addr().expect("mock server address");
27064            let stop = Arc::new(AtomicBool::new(false));
27065            let server_stop = Arc::clone(&stop);
27066            let requests = Arc::new(Mutex::new(Vec::new()));
27067            let server_requests = Arc::clone(&requests);
27068            let thread = thread::spawn(move || {
27069                let mut request_threads = Vec::new();
27070                while !server_stop.load(Ordering::SeqCst) {
27071                    match listener.accept() {
27072                        Ok((mut stream, _)) => {
27073                            if behavior.concurrent_requests {
27074                                let requests = Arc::clone(&server_requests);
27075                                request_threads.push(thread::spawn(move || {
27076                                    handle_mock_worker_request(&mut stream, &requests, behavior)
27077                                }));
27078                            } else {
27079                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
27080                            }
27081                        }
27082                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
27083                            let mut index = 0;
27084                            while index < request_threads.len() {
27085                                if request_threads[index].is_finished() {
27086                                    request_threads
27087                                        .swap_remove(index)
27088                                        .join()
27089                                        .expect("join mock request");
27090                                } else {
27091                                    index += 1;
27092                                }
27093                            }
27094                            thread::sleep(Duration::from_millis(5));
27095                        }
27096                        Err(_) => break,
27097                    }
27098                }
27099                for request_thread in request_threads {
27100                    request_thread.join().expect("join mock request");
27101                }
27102            });
27103
27104            Self {
27105                addr,
27106                stop,
27107                requests,
27108                thread: Some(thread),
27109            }
27110        }
27111
27112        fn base_url(&self) -> String {
27113            format!("http://{}", self.addr)
27114        }
27115
27116        fn worker_protocol_for(&self, path: &str) -> Option<String> {
27117            self.requests
27118                .lock()
27119                .expect("captured requests")
27120                .iter()
27121                .find(|request| request.path == path)
27122                .and_then(|request| request.worker_protocol.clone())
27123        }
27124
27125        fn control_protocol_for(&self, path: &str) -> Option<String> {
27126            self.requests
27127                .lock()
27128                .expect("captured requests")
27129                .iter()
27130                .find(|request| request.path == path)
27131                .and_then(|request| request.control_protocol.clone())
27132        }
27133
27134        fn method_for(&self, path: &str) -> Option<String> {
27135            self.requests
27136                .lock()
27137                .expect("captured requests")
27138                .iter()
27139                .find(|request| request.path == path)
27140                .map(|request| request.method.clone())
27141        }
27142
27143        fn authorization_for(&self, path: &str) -> Option<String> {
27144            self.requests
27145                .lock()
27146                .expect("captured requests")
27147                .iter()
27148                .find(|request| request.path == path)
27149                .and_then(|request| request.authorization.clone())
27150        }
27151
27152        fn namespace_for(&self, path: &str) -> Option<String> {
27153            self.requests
27154                .lock()
27155                .expect("captured requests")
27156                .iter()
27157                .find(|request| request.path == path)
27158                .and_then(|request| request.namespace.clone())
27159        }
27160
27161        fn request_count(&self, path: &str) -> usize {
27162            self.requests
27163                .lock()
27164                .expect("captured requests")
27165                .iter()
27166                .filter(|request| request.path == path)
27167                .count()
27168        }
27169
27170        fn captured_paths(&self) -> Vec<String> {
27171            self.requests
27172                .lock()
27173                .expect("captured requests")
27174                .iter()
27175                .map(|request| request.path.clone())
27176                .collect()
27177        }
27178
27179        fn request_times(&self, path: &str) -> Vec<Instant> {
27180            self.requests
27181                .lock()
27182                .expect("captured requests")
27183                .iter()
27184                .filter(|request| request.path == path)
27185                .map(|request| request.received_at)
27186                .collect()
27187        }
27188
27189        fn request_body(&self, path: &str) -> Value {
27190            let requests = self.requests.lock().expect("captured requests");
27191            let body = &requests
27192                .iter()
27193                .find(|request| request.path == path)
27194                .unwrap_or_else(|| panic!("missing request for {path}"))
27195                .body;
27196            serde_json::from_str(body).unwrap_or_else(|error| {
27197                panic!("invalid JSON request body for {path}: {error}: {body:?}")
27198            })
27199        }
27200
27201        fn request_bodies(&self, path: &str) -> Vec<Value> {
27202            self.requests
27203                .lock()
27204                .expect("captured requests")
27205                .iter()
27206                .filter(|request| request.path == path)
27207                .map(|request| {
27208                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
27209                        panic!(
27210                            "invalid JSON request body for {path}: {error}: {:?}",
27211                            request.body
27212                        )
27213                    })
27214                })
27215                .collect()
27216        }
27217    }
27218
27219    impl Drop for MockWorkerServer {
27220        fn drop(&mut self) {
27221            self.stop.store(true, Ordering::SeqCst);
27222            let _ = TcpStream::connect(self.addr);
27223
27224            if let Some(thread) = self.thread.take() {
27225                thread.join().expect("join mock server");
27226            }
27227        }
27228    }
27229
27230    fn handle_mock_worker_request(
27231        stream: &mut TcpStream,
27232        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
27233        behavior: MockWorkerBehavior,
27234    ) {
27235        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
27236        let mut buffer = [0_u8; 8192];
27237        let mut request = Vec::new();
27238
27239        loop {
27240            match stream.read(&mut buffer) {
27241                Ok(0) => break,
27242                Ok(read) => {
27243                    request.extend_from_slice(&buffer[..read]);
27244                    if mock_request_is_complete(&request) {
27245                        break;
27246                    }
27247                }
27248                Err(error)
27249                    if matches!(
27250                        error.kind(),
27251                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
27252                    ) =>
27253                {
27254                    break;
27255                }
27256                Err(_) => return,
27257            }
27258        }
27259
27260        let request = String::from_utf8_lossy(&request);
27261        let body = request
27262            .split_once("\r\n\r\n")
27263            .map(|(_, body)| body)
27264            .unwrap_or_default();
27265        let path = request
27266            .lines()
27267            .next()
27268            .and_then(|line| line.split_whitespace().nth(1))
27269            .unwrap_or_default();
27270        let method = request
27271            .lines()
27272            .next()
27273            .and_then(|line| line.split_whitespace().next())
27274            .unwrap_or_default();
27275        let authorization = request.lines().find_map(|line| {
27276            let (name, value) = line.split_once(':')?;
27277            name.eq_ignore_ascii_case("Authorization")
27278                .then(|| value.trim().to_string())
27279        });
27280        let namespace = request.lines().find_map(|line| {
27281            let (name, value) = line.split_once(':')?;
27282            name.eq_ignore_ascii_case("X-Namespace")
27283                .then(|| value.trim().to_string())
27284        });
27285        let worker_protocol = request.lines().find_map(|line| {
27286            let (name, value) = line.split_once(':')?;
27287            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
27288                .then(|| value.trim().to_string())
27289        });
27290        let control_protocol = request.lines().find_map(|line| {
27291            let (name, value) = line.split_once(':')?;
27292            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
27293                .then(|| value.trim().to_string())
27294        });
27295        let request_number = {
27296            let mut requests = requests.lock().expect("captured requests");
27297            requests.push(CapturedRequest {
27298                headers: request
27299                    .split_once("\r\n\r\n")
27300                    .map_or("", |(headers, _)| headers)
27301                    .to_owned(),
27302                method: method.to_string(),
27303                path: path.to_string(),
27304                authorization,
27305                namespace,
27306                worker_protocol: worker_protocol.clone(),
27307                control_protocol,
27308                body: body.to_string(),
27309                received_at: Instant::now(),
27310            });
27311            requests
27312                .iter()
27313                .filter(|request| request.path == path)
27314                .count()
27315        };
27316
27317        if let Some(response) = behavior
27318            .request_override
27319            .and_then(|handler| handler(path, body, request_number))
27320        {
27321            write_mock_response(stream, response.0, &response.1);
27322            return;
27323        }
27324        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
27325            write_mock_response(stream, response.0, &response.1);
27326            return;
27327        }
27328        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
27329            return;
27330        }
27331        let pressure_path = behavior
27332            .storage_path
27333            .is_some_and(|part| path.contains(part));
27334        let prior_failures = if path.ends_with("/poll") {
27335            behavior.poll_failures_per_path
27336        } else {
27337            0
27338        };
27339        if pressure_path
27340            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
27341        {
27342            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
27343            let poll_id = path
27344                .ends_with("/poll")
27345                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
27346            let mut refusal = storage_refusal(
27347                poll_id,
27348                behavior.storage_unavailable,
27349                behavior.storage_mid_poll,
27350            );
27351            if behavior.storage_wrong_poll_id {
27352                refusal["poll_request_id"] = json!("wrong-poll");
27353            }
27354            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
27355            return;
27356        }
27357        if path.contains("/storage-task/")
27358            || path.contains("/storage-activity/")
27359            || path.contains("/storage-query/")
27360        {
27361            write_mock_response(stream, "200 OK", "{}");
27362            return;
27363        }
27364        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
27365            write_mock_response(stream, "200 OK", &json!({"task":{
27366                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
27367                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
27368                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
27369                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
27370                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
27371            }}).to_string());
27372            return;
27373        }
27374        if behavior.storage_activity
27375            && path == "/api/worker/activity-tasks/poll"
27376            && request_number == 1
27377        {
27378            write_mock_response(stream, "200 OK", &json!({"task":{
27379                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
27380                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
27381                "attempt_number":7, "lease_owner":"storage-worker"
27382            }}).to_string());
27383            return;
27384        }
27385
27386        if path == "/api/worker/register" {
27387            if behavior.reject_registration_protocol {
27388                write_mock_response(
27389                    stream,
27390                    "400 Bad Request",
27391                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
27392                );
27393                return;
27394            }
27395            if behavior.reject_registration {
27396                write_mock_response(
27397                    stream,
27398                    "503 Service Unavailable",
27399                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
27400                );
27401                return;
27402            }
27403        }
27404
27405        if path.starts_with("/api/worker/registrations/") {
27406            if behavior.reject_deregistration_protocol {
27407                write_mock_response(
27408                    stream,
27409                    "400 Bad Request",
27410                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.19"}"#,
27411                );
27412            } else if behavior.reject_deregistration {
27413                write_mock_response(
27414                    stream,
27415                    "403 Forbidden",
27416                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
27417                );
27418            } else {
27419                write_mock_response(
27420                    stream,
27421                    "200 OK",
27422                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
27423                );
27424            }
27425            return;
27426        }
27427
27428        let is_poll = matches!(
27429            path,
27430            "/api/worker/workflow-tasks/poll"
27431                | "/api/worker/activity-tasks/poll"
27432                | "/api/worker/query-tasks/poll"
27433        );
27434        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
27435            write_mock_response(
27436                stream,
27437                "429 Too Many Requests",
27438                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
27439            );
27440            return;
27441        }
27442        if is_poll && request_number <= behavior.poll_failures_per_path {
27443            return;
27444        }
27445        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
27446            return;
27447        }
27448        if path == "/api/worker/heartbeat"
27449            && behavior.heartbeat_failure_request == Some(request_number)
27450        {
27451            return;
27452        }
27453        if path == "/api/worker/heartbeat"
27454            && behavior.delayed_heartbeat_request == Some(request_number)
27455        {
27456            thread::sleep(behavior.heartbeat_response_delay);
27457        }
27458        if behavior.unauthorized_polls && is_poll {
27459            write_mock_response(
27460                stream,
27461                "401 Unauthorized",
27462                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
27463            );
27464            return;
27465        }
27466        if behavior.draining_polls && is_poll {
27467            write_mock_response(
27468                stream,
27469                "409 Conflict",
27470                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
27471            );
27472            return;
27473        }
27474
27475        if let Some(codec_case) = behavior.invalid_task_payload_codec {
27476            if is_poll && request_number == 1 {
27477                let mut task = match path {
27478                    "/api/worker/workflow-tasks/poll" => json!({
27479                        "task_id": "codec-workflow",
27480                        "workflow_type": "codec.workflow",
27481                        "payload_codec": DEFAULT_CODEC,
27482                        "workflow_task_attempt": 1,
27483                        "lease_owner": "codec-worker"
27484                    }),
27485                    "/api/worker/activity-tasks/poll" => json!({
27486                        "task_id": "codec-activity",
27487                        "activity_attempt_id": "codec-activity-attempt",
27488                        "activity_type": "codec.activity",
27489                        "payload_codec": DEFAULT_CODEC,
27490                        "attempt_number": 1,
27491                        "lease_owner": "codec-worker"
27492                    }),
27493                    "/api/worker/query-tasks/poll" => json!({
27494                        "query_task_id": "codec-query",
27495                        "query_task_attempt": 1,
27496                        "workflow_type": "codec.workflow",
27497                        "query_name": "known",
27498                        "payload_codec": DEFAULT_CODEC,
27499                        "lease_owner": "codec-worker"
27500                    }),
27501                    _ => unreachable!("is_poll limits task codec probe paths"),
27502                };
27503                codec_case.apply(&mut task);
27504                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
27505                return;
27506            }
27507
27508            if matches!(
27509                path,
27510                "/api/worker/workflow-tasks/codec-workflow/fail"
27511                    | "/api/worker/activity-tasks/codec-activity/fail"
27512                    | "/api/worker/query-tasks/codec-query/fail"
27513            ) {
27514                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
27515                return;
27516            }
27517        }
27518
27519        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
27520            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
27521            let body = format!(
27522                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
27523            );
27524            write_mock_response(stream, "400 Bad Request", &body);
27525            return;
27526        }
27527
27528        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
27529        {
27530            write_mock_response(
27531                stream,
27532                "409 Conflict",
27533                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
27534            );
27535            return;
27536        }
27537
27538        if behavior.workflow_completion_status.is_some()
27539            && path == "/api/worker/workflow-tasks/poll"
27540            && request_number == 1
27541        {
27542            write_mock_response(
27543                stream,
27544                "200 OK",
27545                r#"{"task":{"task_id":"workflow-timeout-task","workflow_id":"reused-workflow-id","run_id":"run-selected-timeout","workflow_type":"timeout.workflow","payload_codec":"avro","arguments":{"codec":"avro","blob":"wwHioz3/VYAiNwwA"},"history_events":[],"workflow_task_attempt":3,"lease_owner":"timeout-worker"}}"#,
27546            );
27547            return;
27548        }
27549
27550        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
27551            if let (Some(status), Some(body)) = (
27552                behavior.workflow_completion_status,
27553                behavior.workflow_completion_body,
27554            ) {
27555                write_mock_response(stream, status, body);
27556                return;
27557            }
27558        }
27559
27560        if behavior.waiting_query_worker {
27561            if behavior.complete_named_signal
27562                && path == "/api/worker/workflow-tasks/poll"
27563                && request_number == 1
27564            {
27565                let body = json!({
27566                    "task": {
27567                        "task_id": "snapshot-open",
27568                        "workflow_id": "snapshot-1",
27569                        "run_id": "snapshot-run-1",
27570                        "workflow_type": "snapshot",
27571                        "payload_codec": DEFAULT_CODEC,
27572                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
27573                            .expect("Avro workflow arguments"),
27574                        "history_events": [],
27575                        "workflow_task_attempt": 1,
27576                        "lease_owner": "rust-snapshot-worker"
27577                    }
27578                })
27579                .to_string();
27580                write_mock_response(stream, "200 OK", &body);
27581                return;
27582            }
27583
27584            let signal_request = request_number - usize::from(behavior.complete_named_signal);
27585            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
27586            if path == "/api/worker/workflow-tasks/poll"
27587                && signal_request >= 1
27588                && signal_request <= signal_request_limit
27589            {
27590                let finish = behavior.complete_named_signal && signal_request == 3;
27591                let amounts = if signal_request == 1 {
27592                    vec![3]
27593                } else {
27594                    vec![3, 5]
27595                };
27596                let task_id = if signal_request == 1 {
27597                    "snapshot-wait-3"
27598                } else if finish {
27599                    "snapshot-finish"
27600                } else {
27601                    "snapshot-wait-5"
27602                };
27603                let mut history_events = std::iter::once(json!({
27604                    "event_type": "SignalWaitOpened",
27605                    "payload": {"sequence": 1, "signal_name": "finish"}
27606                }))
27607                .chain(amounts.iter().enumerate().map(|(index, amount)| {
27608                    json!({
27609                        "event_type": "SignalReceived",
27610                        "payload": {
27611                            "signal_id": format!("increment-{amount}"),
27612                            "signal_name": "increment",
27613                            "workflow_sequence": index + 2,
27614                            "payload_codec": DEFAULT_CODEC,
27615                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
27616                                .expect("Avro signal envelope")
27617                        }
27618                    })
27619                }))
27620                .collect::<Vec<_>>();
27621                let (resume_id, resume_name, resume_arguments) = if finish {
27622                    history_events.push(json!({
27623                        "event_type": "SignalReceived",
27624                        "payload": {
27625                            "signal_id": "finish",
27626                            "signal_name": "finish",
27627                            "workflow_sequence": 4,
27628                            "payload_codec": DEFAULT_CODEC,
27629                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
27630                                .expect("Avro finish signal envelope")
27631                        }
27632                    }));
27633                    (
27634                        "finish".to_string(),
27635                        "finish".to_string(),
27636                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
27637                            .expect("Avro finish resume signal"),
27638                    )
27639                } else {
27640                    let amount = amounts.last().expect("amount");
27641                    (
27642                        format!("increment-{amount}"),
27643                        "increment".to_string(),
27644                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
27645                            .expect("Avro increment resume signal"),
27646                    )
27647                };
27648                let body = json!({
27649                    "task": {
27650                        "task_id": task_id,
27651                        "workflow_id": "snapshot-1",
27652                        "run_id": "snapshot-run-1",
27653                        "workflow_type": "snapshot",
27654                        "payload_codec": DEFAULT_CODEC,
27655                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
27656                            .expect("Avro workflow arguments"),
27657                        "history_events": history_events,
27658                        "workflow_task_attempt": 1,
27659                        "workflow_signal_id": resume_id,
27660                        "signal_name": resume_name,
27661                        "signal_arguments": resume_arguments,
27662                        "lease_owner": "rust-snapshot-worker"
27663                    }
27664                })
27665                .to_string();
27666                write_mock_response(stream, "200 OK", &body);
27667                return;
27668            }
27669
27670            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
27671                let history_events = [3, 5]
27672                    .into_iter()
27673                    .enumerate()
27674                    .map(|(index, amount)| {
27675                        json!({
27676                            "event_type": "SignalReceived",
27677                            "payload": {
27678                                "signal_id": format!("increment-{amount}"),
27679                                "signal_name": "increment",
27680                                "workflow_sequence": index + 2,
27681                                "payload_codec": DEFAULT_CODEC,
27682                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
27683                                    .expect("Avro query signal envelope")
27684                            }
27685                        })
27686                    })
27687                    .collect::<Vec<_>>();
27688                let body = json!({
27689                    "task": {
27690                        "query_task_id": "snapshot-current",
27691                        "query_task_attempt": 1,
27692                        "lease_owner": "rust-snapshot-worker",
27693                        "workflow_id": "snapshot-1",
27694                        "run_id": "snapshot-run-1",
27695                        "workflow_type": "snapshot",
27696                        "query_name": "current",
27697                        "payload_codec": DEFAULT_CODEC,
27698                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
27699                            .expect("Avro workflow arguments"),
27700                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
27701                            .expect("Avro query arguments"),
27702                        "history_events": history_events,
27703                        "run_status": "waiting"
27704                    }
27705                })
27706                .to_string();
27707                write_mock_response(stream, "200 OK", &body);
27708                return;
27709            }
27710
27711            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
27712                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
27713            {
27714                write_mock_response(
27715                    stream,
27716                    "200 OK",
27717                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
27718                );
27719                return;
27720            }
27721
27722            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
27723                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
27724                return;
27725            }
27726
27727            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
27728                write_mock_response(
27729                    stream,
27730                    "200 OK",
27731                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
27732                );
27733                return;
27734            }
27735
27736            if path == "/api/worker/query-tasks/snapshot-current/complete" {
27737                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
27738                return;
27739            }
27740        }
27741
27742        if matches!(
27743            path,
27744            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
27745        ) {
27746            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
27747                .expect("typed mock result");
27748            let body = json!({
27749                "result": typed_fidelity_probe().into_json().expect("result projection"),
27750                "result_envelope": result,
27751            })
27752            .to_string();
27753            write_mock_response(stream, "200 OK", &body);
27754            return;
27755        }
27756
27757        if path == "/api/workflows/typed-1" {
27758            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
27759                .expect("typed mock result");
27760            let body = json!({
27761                "workflow_id": "typed-1",
27762                "run_id": "run-typed-1",
27763                "workflow_type": "typed.echo",
27764                "status": "completed",
27765                "output": typed_fidelity_probe().into_json().expect("output projection"),
27766                "output_envelope": result,
27767            })
27768            .to_string();
27769            write_mock_response(stream, "200 OK", &body);
27770            return;
27771        }
27772
27773        let (status, body) = match path {
27774            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
27775            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
27776            "/api/workflows" => (
27777                "201 Created",
27778                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
27779            ),
27780            "/api/worker/register" if behavior.decline_registration => (
27781                "200 OK",
27782                r#"{"worker_id":"declined-worker","registered":false}"#,
27783            ),
27784            "/api/worker/register" if behavior.waiting_query_worker => (
27785                "200 OK",
27786                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
27787            ),
27788            "/api/worker/register" => (
27789                "200 OK",
27790                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
27791            ),
27792            "/api/worker/heartbeat" => ("200 OK", "{}"),
27793            "/api/worker/activity-tasks/poll"
27794                if behavior.cancelled_activity && request_number == 1 =>
27795            {
27796                (
27797                    "200 OK",
27798                    r#"{"task":{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","activity_type":"cancel-aware","payload_codec":"avro","arguments":{"codec":"avro","blob":"wwHioz3/VYAiNwwA"},"attempt_number":1,"lease_owner":"rust-cancel-worker"}}"#,
27799                )
27800            }
27801            "/api/worker/activity-tasks/poll"
27802                if behavior.long_poll_capacity_responses_per_path > 0
27803                    && request_number
27804                        == behavior
27805                            .long_poll_capacity_responses_per_path
27806                            .saturating_add(1) =>
27807            {
27808                (
27809                    "200 OK",
27810                    r#"{"task":{"task_id":"capacity-activity","activity_attempt_id":"capacity-attempt","activity_type":"capacity.activity","payload_codec":"avro","arguments":{"codec":"avro","blob":"wwHioz3/VYAiNwwA"},"attempt_number":1,"lease_owner":"capacity-worker"}}"#,
27811                )
27812            }
27813            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
27814                ("200 OK", r#"{"task":null}"#)
27815            }
27816            "/api/worker/query-tasks/poll"
27817                if behavior.reject_query_completion && request_number == 1 =>
27818            {
27819                (
27820                    "200 OK",
27821                    r#"{"task":{"query_task_id":"query-late","query_task_attempt":1,"lease_owner":"late-worker","workflow_id":"counter-late","run_id":"run-late","workflow_type":"counter","query_name":"current","payload_codec":"avro","workflow_arguments":{"codec":"avro","blob":"wwHioz3/VYAiNwwA"},"query_arguments":{"codec":"avro","blob":"wwHioz3/VYAiNwwA"},"history_events":[],"run_status":"running"}}"#,
27822                )
27823            }
27824            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
27825            "/api/worker/query-tasks/query-capture/complete"
27826            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
27827            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
27828                "200 OK",
27829                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
27830            ),
27831            "/api/worker/activity-tasks/activity-cancel/complete" => (
27832                "409 Conflict",
27833                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
27834            ),
27835            "/api/worker/activity-tasks/activity-typed/complete"
27836            | "/api/worker/activity-tasks/activity-typed/fail"
27837            | "/api/worker/activity-tasks/capacity-activity/complete"
27838            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
27839            "/api/workflows/counter-1/query/current" => (
27840                "200 OK",
27841                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
27842            ),
27843            "/api/workflows/counter-1/query/missing" => (
27844                "404 Not Found",
27845                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
27846            ),
27847            "/api/workflows/wf-lifecycle/cancel" => (
27848                "200 OK",
27849                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
27850            ),
27851            "/api/workflows/wf-lifecycle/terminate" => (
27852                "200 OK",
27853                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
27854            ),
27855            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
27856                "200 OK",
27857                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
27858            ),
27859            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
27860                "200 OK",
27861                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
27862            ),
27863            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
27864                "202 Accepted",
27865                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
27866            ),
27867            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
27868                "200 OK",
27869                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed-existing","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
27870            ),
27871            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
27872                "409 Conflict",
27873                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
27874            ),
27875            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
27876            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
27877                "409 Conflict",
27878                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
27879            ),
27880            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
27881                "200 OK",
27882                r#"{"workflow_id":"wf-failed","run_id":"run-failed","status":"failed","closed_reason":"failed","error":"payment failed","failure":{"message":"payment failed","failure_category":"application","exception_type":"PaymentError","exception_class":"billing::PaymentError","non_retryable":true,"exception":{"type":"PaymentError","class":"billing::PaymentError","message":"payment failed"},"failures":[{"id":"failure-17","failure_category":"application"}]}}"#,
27883            ),
27884            "/api/workflows/wf-cancelled" => (
27885                "200 OK",
27886                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
27887            ),
27888            "/api/workflows/wf-terminated" => (
27889                "200 OK",
27890                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
27891            ),
27892            "/api/workflows/wf-timed-out" => (
27893                "200 OK",
27894                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
27895            ),
27896            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
27897                "200 OK",
27898                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
27899            ),
27900            "/api/workflows/wf-selected" => (
27901                "200 OK",
27902                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
27903            ),
27904            "/api/workflows/wf-selected/runs/run-selected" => (
27905                "200 OK",
27906                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
27907            ),
27908            _ => ("404 Not Found", r#"{"message":"not found"}"#),
27909        };
27910        write_mock_response(stream, status, body);
27911    }
27912
27913    fn mock_request_is_complete(request: &[u8]) -> bool {
27914        let Some(header_end) = request
27915            .windows(4)
27916            .position(|window| window == b"\r\n\r\n")
27917            .map(|position| position + 4)
27918        else {
27919            return false;
27920        };
27921        let headers = String::from_utf8_lossy(&request[..header_end]);
27922        let content_length = headers.lines().find_map(|line| {
27923            let (name, value) = line.split_once(':')?;
27924            name.eq_ignore_ascii_case("content-length")
27925                .then(|| value.trim().parse::<usize>().ok())
27926                .flatten()
27927        });
27928
27929        request.len() >= header_end + content_length.unwrap_or(0)
27930    }
27931
27932    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
27933        let response = format!(
27934            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
27935            body.len()
27936        );
27937
27938        let _ = stream.write_all(response.as_bytes());
27939        let _ = stream.flush();
27940    }
27941
27942    fn activity_completion_backend_recovery(
27943        path: &str,
27944        _body: &str,
27945        request_number: usize,
27946    ) -> Option<(&'static str, String)> {
27947        match path {
27948            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
27949                "200 OK",
27950                r#"{"task":{"task_id":"recover-activity","activity_attempt_id":"recover-attempt","activity_type":"recover.activity","payload_codec":"avro","arguments":{"codec":"avro","blob":"wwHioz3/VYAiNwwA"},"attempt_number":1,"lease_owner":"recover-worker"}}"#.to_string(),
27951            )),
27952            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
27953                "503 Service Unavailable",
27954                r#"{"reason":"backend_unavailable","operation":"complete_activity_task","outcome":"unknown","worker_id":"recover-worker","task_queue":null,"retryable":true,"retry_after_seconds":1,"task_id":"recover-activity","lease_owner":"recover-worker","activity_attempt_id":"recover-attempt"}"#.to_string(),
27955            )),
27956            "/api/worker/activity-tasks/recover-activity/complete" => Some((
27957                "200 OK",
27958                r#"{"outcome":"completed","recorded":true}"#.to_string(),
27959            )),
27960            _ => None,
27961        }
27962    }
27963
27964    fn workflow_completion_backend_recovery(
27965        path: &str,
27966        _body: &str,
27967        request_number: usize,
27968    ) -> Option<(&'static str, String)> {
27969        match path {
27970            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
27971                "200 OK",
27972                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
27973            )),
27974            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
27975                "503 Service Unavailable",
27976                r#"{"reason":"backend_unavailable","operation":"complete_workflow_task","outcome":"unknown","worker_id":"recover-worker","task_queue":null,"retryable":true,"retry_after_seconds":1,"task_id":"recover-workflow","lease_owner":"recover-worker","workflow_task_attempt":3}"#.to_string(),
27977            )),
27978            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
27979                "200 OK",
27980                r#"{"outcome":"completed","recorded":true}"#.to_string(),
27981            )),
27982            _ => None,
27983        }
27984    }
27985
27986    fn activity_completion_stale_after_backend_recovery(
27987        path: &str,
27988        body: &str,
27989        request_number: usize,
27990    ) -> Option<(&'static str, String)> {
27991        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
27992            return Some((
27993                "409 Conflict",
27994                r#"{"task_id":"recover-activity","activity_attempt_id":"recover-attempt","lease_owner":"recover-worker","reason":"stale_attempt","outcome":"completed","recorded":false,"activity_status":"completed","attempt_status":"completed","task_status":"completed"}"#.to_string(),
27995            ));
27996        }
27997        activity_completion_backend_recovery(path, body, request_number)
27998    }
27999
28000    fn activity_completion_remains_unavailable(
28001        path: &str,
28002        body: &str,
28003        request_number: usize,
28004    ) -> Option<(&'static str, String)> {
28005        if path == "/api/worker/activity-tasks/recover-activity/complete" {
28006            return activity_completion_backend_recovery(path, body, 1);
28007        }
28008        activity_completion_backend_recovery(path, body, request_number)
28009    }
28010
28011    #[tokio::test]
28012    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
28013        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28014            request_override: Some(activity_completion_backend_recovery),
28015            ..MockWorkerBehavior::default()
28016        });
28017        let client = Client::builder(server.base_url())
28018            .timeout(Duration::from_secs(2))
28019            .build()
28020            .expect("client");
28021        let handler_calls = Arc::new(AtomicUsize::new(0));
28022        let mut worker = Worker::new(client, "recover-queue")
28023            .worker_id("recover-worker")
28024            .poll_timeout(Duration::from_millis(10));
28025        worker.register_activity("recover.activity", {
28026            let handler_calls = Arc::clone(&handler_calls);
28027            move |_ctx, _args| {
28028                let handler_calls = Arc::clone(&handler_calls);
28029                async move {
28030                    handler_calls.fetch_add(1, Ordering::SeqCst);
28031                    Ok(json!("done"))
28032                }
28033            }
28034        });
28035
28036        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
28037        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
28038        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
28039        assert_eq!(bodies.len(), 2);
28040        assert_eq!(bodies[0], bodies[1]);
28041    }
28042
28043    #[tokio::test]
28044    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
28045        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28046            request_override: Some(workflow_completion_backend_recovery),
28047            ..MockWorkerBehavior::default()
28048        });
28049        let client = Client::builder(server.base_url())
28050            .timeout(Duration::from_secs(2))
28051            .build()
28052            .expect("client");
28053        let handler_calls = Arc::new(AtomicUsize::new(0));
28054        let mut worker = Worker::new(client, "recover-queue")
28055            .worker_id("recover-worker")
28056            .poll_timeout(Duration::from_millis(10));
28057        worker.register_workflow("recover.workflow", {
28058            let handler_calls = Arc::clone(&handler_calls);
28059            move |_ctx, _args| {
28060                let handler_calls = Arc::clone(&handler_calls);
28061                async move {
28062                    handler_calls.fetch_add(1, Ordering::SeqCst);
28063                    Ok(json!("done"))
28064                }
28065            }
28066        });
28067
28068        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
28069        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
28070        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
28071        assert_eq!(bodies.len(), 2);
28072        assert_eq!(bodies[0], bodies[1]);
28073    }
28074
28075    #[tokio::test]
28076    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
28077        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28078            request_override: Some(activity_completion_stale_after_backend_recovery),
28079            ..MockWorkerBehavior::default()
28080        });
28081        let client = Client::builder(server.base_url())
28082            .timeout(Duration::from_secs(2))
28083            .build()
28084            .expect("client");
28085        let handler_calls = Arc::new(AtomicUsize::new(0));
28086        let mut worker = Worker::new(client, "recover-queue")
28087            .worker_id("recover-worker")
28088            .poll_timeout(Duration::from_millis(10));
28089        worker.register_activity("recover.activity", {
28090            let handler_calls = Arc::clone(&handler_calls);
28091            move |_ctx, _args| {
28092                let handler_calls = Arc::clone(&handler_calls);
28093                async move {
28094                    handler_calls.fetch_add(1, Ordering::SeqCst);
28095                    Ok(json!("done"))
28096                }
28097            }
28098        });
28099
28100        assert_eq!(
28101            worker
28102                .run_once()
28103                .await
28104                .expect("authoritative stale outcome"),
28105            1
28106        );
28107        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
28108        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
28109        assert_eq!(bodies.len(), 2);
28110        assert_eq!(bodies[0], bodies[1]);
28111    }
28112
28113    #[test]
28114    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
28115        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
28116        let response = json!({
28117            "reason":"backend_unavailable", "operation":"complete_activity_task",
28118            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
28119            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
28120            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
28121        });
28122        let path = "/worker/activity-tasks/recover-activity/complete";
28123        let error = |body: Value| Error::Http {
28124            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28125            body: body.to_string(),
28126        };
28127        assert_eq!(
28128            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
28129            Some(Duration::from_secs(1))
28130        );
28131
28132        for (field, invalid) in [
28133            ("operation", json!("poll_activity_task")),
28134            ("outcome", json!("rejected")),
28135            ("worker_id", json!("another-worker")),
28136            ("task_queue", json!("recover-queue")),
28137            ("retryable", json!(false)),
28138            ("retry_after_seconds", json!(0)),
28139            ("task_id", json!("another-task")),
28140            ("lease_owner", json!("another-worker")),
28141            ("activity_attempt_id", json!("another-attempt")),
28142        ] {
28143            let mut invalid_response = response.clone();
28144            invalid_response[field] = invalid;
28145            assert_eq!(
28146                worker_fenced_completion_retry_after(
28147                    &error(invalid_response),
28148                    path,
28149                    Some(&request)
28150                ),
28151                None,
28152                "must not retry mismatched {field}"
28153            );
28154        }
28155        assert_eq!(
28156            worker_fenced_completion_retry_after(&error(response), path, None),
28157            None
28158        );
28159    }
28160
28161    #[tokio::test]
28162    async fn shutdown_interrupts_fenced_completion_backend_wait() {
28163        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28164            request_override: Some(activity_completion_remains_unavailable),
28165            ..MockWorkerBehavior::default()
28166        });
28167        let client = Client::builder(server.base_url())
28168            .timeout(Duration::from_secs(2))
28169            .build()
28170            .expect("client");
28171        let stop = Arc::new(AtomicBool::new(false));
28172        let worker = Worker::new(client, "recover-queue")
28173            .worker_id("recover-worker")
28174            .with_storage_admission(Arc::clone(&stop));
28175        let completion = tokio::spawn(async move {
28176            worker
28177                .client
28178                .complete_activity_task(
28179                    "recover-activity",
28180                    "recover-attempt",
28181                    "recover-worker",
28182                    json!("done"),
28183                    DEFAULT_CODEC,
28184                )
28185                .await
28186        });
28187        let path = "/api/worker/activity-tasks/recover-activity/complete";
28188        tokio::time::timeout(Duration::from_secs(2), async {
28189            while server.request_count(path) == 0 {
28190                tokio::time::sleep(Duration::from_millis(10)).await;
28191            }
28192        })
28193        .await
28194        .expect("first completion request");
28195        stop.store(true, Ordering::SeqCst);
28196        let error = tokio::time::timeout(Duration::from_secs(1), completion)
28197            .await
28198            .expect("shutdown must interrupt retry wait")
28199            .expect("completion task")
28200            .expect_err("backend is still unavailable");
28201        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
28202        assert_eq!(server.request_count(path), 1);
28203    }
28204}