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 local_activity;
10mod runtime_payloads;
11mod runtime_uploads;
12mod worker_session;
13
14pub use cancellation_context::{
15    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
16};
17pub use cancellation_scope::CancellationScopeOpenReceipt;
18#[doc(hidden)]
19pub use cancellation_scope_history::{
20    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
21};
22#[doc(hidden)]
23pub use cancellation_scope_replay::CancellationScopeRequested;
24
25pub use cooperative_cancellation::{
26    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
27    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
28    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
29    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
30};
31
32use std::{
33    any::{type_name, Any, TypeId},
34    collections::{BTreeMap, BTreeSet, HashMap},
35    future::Future,
36    io::{self, Read},
37    pin::Pin,
38    sync::{
39        atomic::{AtomicBool, Ordering},
40        Arc, Mutex, OnceLock,
41    },
42    task::{Context as TaskContext, Poll},
43    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
44};
45
46use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
47use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
48use chrono::DateTime;
49use futures_util::{
50    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
51};
52pub use local_activity::LocalActivityOptions;
53use serde::{
54    de::DeserializeOwned,
55    ser::{SerializeMap, SerializeSeq},
56    Deserialize, Deserializer, Serialize, Serializer,
57};
58pub use serde_json::{json, Value};
59use sha2::{Digest, Sha256};
60use thiserror::Error;
61pub use uuid::Uuid;
62pub use worker_session::{WorkerSession, WorkerSessionOptions};
63
64pub const WORKER_PROTOCOL_VERSION: &str = "1.19";
65const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
66/// First additive worker protocol that defines portable worker-affinity features.
67pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
68pub const CONTROL_PLANE_VERSION: &str = "2";
69pub const DEFAULT_CODEC: &str = "avro";
70pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
71/// Worker-registration capability for authored condition-wait occurrence identity.
72pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
73    "condition_wait_occurrence_identity";
74/// Worker-registration capability for portable memo upserts.
75pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
76/// Worker-registration capability for server-routed read-only queries.
77pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
78/// Worker-registration capability for canonical typed search attributes.
79pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
80/// Worker-registration capability for synchronous workflow updates.
81pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
82/// Worker-registration capability for durable named input streams.
83pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
84/// Worker-registration capability for persisted first-completion selection.
85pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
86pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
87pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
88pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
89pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
90pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
91/// First additive worker protocol that defines query-task transport.
92pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
93/// First additive worker protocol that defines typed search-attribute upserts.
94pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
95/// First additive worker protocol that defines portable memo upserts.
96pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
97/// First additive worker protocol that preserves declared search-attribute types.
98pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
99/// First additive worker protocol that defines external durable condition waits.
100pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
101/// First additive worker protocol that preserves authored condition-wait occurrences.
102pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
103/// First additive worker protocol that defines durable selection groups.
104pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
105
106pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
107    let Some((major, minor)) = version.split_once('.') else {
108        return false;
109    };
110    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
111}
112
113fn validate_user_signal_name(signal_name: &str) -> Result<()> {
114    if signal_name == MESSAGE_STREAM_SIGNAL {
115        return Err(Error::Codec(format!(
116            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
117        )));
118    }
119    Ok(())
120}
121
122const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
123const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
124    "Workflow task waiting for scheduled history.";
125const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
126const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
127const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
128const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
129const MAX_MEMO_ENTRIES: usize = 100;
130const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
131const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
132
133const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
134    "lease_expired",
135    "query_task_not_found",
136    "query_task_not_leased",
137    "query_task_timed_out",
138];
139
140/// Manifest for the default service-worker profile.
141///
142/// Inline local execution is enabled separately by [`Worker::local_activities`].
143/// Default workers refuse it, while sessions and sticky execution remain unavailable.
144pub fn portable_worker_affinity_capability_manifest() -> Value {
145    json!({
146        "local_activities": {
147            "supported": false,
148            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
149            "reason": "rust_worker_does_not_execute_record_local_activity",
150        },
151        "worker_sessions": {
152            "supported": false,
153            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
154            "reason": "rust_worker_has_no_typed_session_lifecycle",
155        },
156        "sticky_execution": {
157            "supported": false,
158            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
159            "reason": "rust_worker_uses_complete_durable_history_replay",
160        },
161    })
162}
163
164/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
165pub const AVRO_VALUE_SCHEMA_JSON: &str =
166    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
167pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
168pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
169const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
170
171static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
172static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
173    OnceLock::new();
174
175#[derive(Clone, Copy)]
176enum RequestProtocol {
177    ControlPlane,
178    Worker(&'static str),
179}
180
181pub type Result<T> = std::result::Result<T, Error>;
182
183#[derive(Debug, Error)]
184pub enum Error {
185    #[error("transport error: {0}")]
186    Transport(#[from] reqwest::Error),
187    #[error(
188        "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"
189    )]
190    InvalidBaseUrl,
191    #[error("json error: {0}")]
192    Json(#[from] serde_json::Error),
193    #[error("http {status}: {body}")]
194    Http {
195        status: reqwest::StatusCode,
196        body: String,
197    },
198    #[error("codec error: {0}")]
199    Codec(String),
200    #[error(transparent)]
201    QueryFailed(QueryFailure),
202    #[error(transparent)]
203    Protocol(ProtocolFailure),
204    #[error(transparent)]
205    NonDeterministicReplay(ReplayFailure),
206    #[error(transparent)]
207    ChildWorkflowFailed(ChildWorkflowFailure),
208    #[error(transparent)]
209    ActivityFailed(ActivityFailure),
210    #[error(transparent)]
211    ParallelFailed(ParallelFailure),
212    #[error(transparent)]
213    SagaCompensationFailed(SagaCompensationFailure),
214    #[error(transparent)]
215    InvalidParallelGroup(ParallelGroupError),
216    #[error(transparent)]
217    DurableOperationCancelled(DurableOperationCancelled),
218    #[error(transparent)]
219    WorkflowCancellationRequested(WorkflowCancellationRequested),
220    #[error(transparent)]
221    CooperativeCancellationRequested(CooperativeCancellationRequested),
222    #[error(transparent)]
223    CancellationScopeRequested(CancellationScopeRequested),
224    #[error(transparent)]
225    WorkflowCommandRejected(WorkflowCommandRejection),
226    #[error(transparent)]
227    WorkflowFailed(WorkflowTerminalOutcome),
228    #[error(transparent)]
229    WorkflowCancelled(WorkflowTerminalOutcome),
230    #[error(transparent)]
231    WorkflowTerminated(WorkflowTerminalOutcome),
232    #[error(transparent)]
233    WorkflowTimedOut(WorkflowTerminalOutcome),
234    #[error(transparent)]
235    ActivityTaskRejected(ActivityTaskRejection),
236    #[error("workflow handler {0:?} is not registered")]
237    WorkflowNotRegistered(String),
238    #[error("activity handler {0:?} is not registered")]
239    ActivityNotRegistered(String),
240    #[error(
241        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
242    )]
243    HandlerType {
244        handler_kind: HandlerKind,
245        handler_name: String,
246        value_kind: HandlerValueKind,
247        rust_type: &'static str,
248        message: String,
249    },
250    #[error("workflow future yielded without emitting a durable command")]
251    WorkflowYieldedWithoutCommand,
252    #[error(
253        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
254    )]
255    MissingWorkflowCommandIdentity,
256    #[error("workflow state lock is poisoned")]
257    WorkflowStatePoisoned,
258    #[error("timer duration is too large for the worker protocol")]
259    TimerDurationOverflow,
260    #[error(transparent)]
261    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
262    #[error(transparent)]
263    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
264    #[error("operation timed out")]
265    Timeout,
266    #[error(
267        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
268    )]
269    MissingRoleCredentials {
270        role: &'static str,
271        opposite_role: &'static str,
272    },
273    #[error("worker loop error: {0}")]
274    WorkerLoop(String),
275    #[error(
276        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
277    )]
278    UnsupportedUpdateValidators { workflow_type: String },
279    #[error("{primary}; worker deregistration also failed: {deregistration}")]
280    WorkerShutdown {
281        primary: Box<Error>,
282        deregistration: Box<Error>,
283    },
284    #[error("invalid child workflow options: {0}")]
285    InvalidChildWorkflowOptions(String),
286    #[error("invalid workflow memo update: {0}")]
287    InvalidMemoUpdate(String),
288    #[error(
289        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
290    )]
291    WorkflowMemoUpdatesUnavailable,
292    #[error("cooperative cancellation is unavailable: {0}")]
293    CooperativeCancellationUnavailable(String),
294    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
295    CancellationScopeExecutionUnavailable,
296    #[error("invalid cooperative cancellation: {0}")]
297    InvalidCooperativeCancellation(String),
298    #[error("activity execution no longer owns its claim: {0}")]
299    ActivityExecutionAbandoned(String),
300    #[error(transparent)]
301    InvalidActivityOptions(ActivityOptionsError),
302    #[error(transparent)]
303    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
304    #[doc(hidden)]
305    #[error("workflow requested continue as new")]
306    ContinueAsNew(ContinueAsNewRequest),
307}
308
309/// Validation failure for a durable condition-wait definition.
310#[derive(Clone, Debug, Error, PartialEq, Eq)]
311pub enum ConditionWaitOptionsError {
312    #[error("condition_key must be non-empty")]
313    EmptyKey,
314    #[error("condition_definition_fingerprint must be non-empty")]
315    EmptyPredicateIdentity,
316    #[error("condition timeout is too large for the worker protocol")]
317    TimeoutOverflow,
318}
319
320/// Stable identity and optional durable timeout for a condition wait.
321///
322/// `predicate_identity` is recorded as the worker protocol's
323/// `condition_definition_fingerprint` and must change whenever predicate
324/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
325/// is written inline; it derives this identity from the predicate tokens.
326#[derive(Clone, Debug, PartialEq, Eq)]
327pub struct ConditionWaitOptions {
328    condition_key: String,
329    predicate_identity: String,
330    timeout: Option<Duration>,
331}
332
333impl ConditionWaitOptions {
334    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
335        Self {
336            condition_key: condition_key.into(),
337            predicate_identity: predicate_identity.into(),
338            timeout: None,
339        }
340    }
341
342    pub fn timeout(mut self, timeout: Duration) -> Self {
343        self.timeout = Some(timeout);
344        self
345    }
346
347    fn validate(
348        &self,
349    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
350        let condition_key = self.condition_key.trim();
351        if condition_key.is_empty() {
352            return Err(ConditionWaitOptionsError::EmptyKey);
353        }
354        let predicate_identity = self.predicate_identity.trim();
355        if predicate_identity.is_empty() {
356            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
357        }
358        let timeout_seconds = self
359            .timeout
360            .map(|timeout| {
361                timeout
362                    .as_secs()
363                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
364                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
365            })
366            .transpose()?;
367
368        Ok(ValidatedConditionWaitOptions {
369            condition_key: condition_key.to_string(),
370            predicate_identity: predicate_identity.to_string(),
371            timeout_seconds,
372        })
373    }
374}
375
376#[derive(Clone, Debug, PartialEq, Eq)]
377struct ValidatedConditionWaitOptions {
378    condition_key: String,
379    predicate_identity: String,
380    timeout_seconds: Option<u64>,
381}
382
383const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
384
385/// Unambiguous terminal result of a durable condition wait.
386#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
387#[serde(rename_all = "snake_case")]
388pub enum ConditionWaitResult {
389    Satisfied,
390    TimedOut,
391}
392
393impl ConditionWaitResult {
394    pub fn is_satisfied(self) -> bool {
395        self == Self::Satisfied
396    }
397
398    pub fn is_timed_out(self) -> bool {
399        self == Self::TimedOut
400    }
401}
402
403/// Build the stable condition definition identity used by [`wait_condition!`].
404#[doc(hidden)]
405pub fn __condition_definition_fingerprint(source: &str) -> String {
406    let mut digest = Sha256::new();
407    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
408    digest.update(source.as_bytes());
409    format!("sha256:{:x}", digest.finalize())
410}
411
412/// Create a durable condition wait whose predicate definition is fingerprinted
413/// from its inline Rust tokens.
414///
415/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
416/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
417#[macro_export]
418macro_rules! wait_condition {
419    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
420        $ctx.wait_condition(
421            $crate::ConditionWaitOptions::new(
422                $key,
423                $crate::__condition_definition_fingerprint(concat!(
424                    module_path!(),
425                    "\0",
426                    stringify!($predicate)
427                )),
428            )
429            .timeout($timeout),
430            $predicate,
431        )
432    }};
433    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
434        $ctx.wait_condition(
435            $crate::ConditionWaitOptions::new(
436                $key,
437                $crate::__condition_definition_fingerprint(concat!(
438                    module_path!(),
439                    "\0",
440                    stringify!($predicate)
441                )),
442            ),
443            $predicate,
444        )
445    }};
446}
447
448const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
449const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
450const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
451const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
452const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
453
454/// Validation failure for a typed workflow search-attribute update.
455#[derive(Clone, Debug, Error, PartialEq, Eq)]
456pub enum SearchAttributeUpdateError {
457    #[error("search-attribute update requires at least one attribute")]
458    Empty,
459    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
460    InvalidKey(String),
461    #[error("search-attribute update exceeds the limit of 100 attributes")]
462    TooManyAttributes,
463    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
464    ValueTooLong {
465        key: String,
466        kind: &'static str,
467        limit: usize,
468    },
469    #[error(
470        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
471    )]
472    EmptyString(String),
473    #[error("search attribute {0:?} has a non-finite float value")]
474    NonFiniteFloat(String),
475    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
476    InvalidDateTime(String),
477    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
478    PayloadTooLarge,
479}
480
481/// One public typed search-attribute value.
482#[derive(Clone, Debug, PartialEq)]
483pub enum SearchAttributeValue {
484    String(String),
485    Keyword(String),
486    KeywordList(Vec<String>),
487    Int(i64),
488    Float(f64),
489    Bool(bool),
490    DateTime(String),
491    Delete,
492}
493
494impl SearchAttributeValue {
495    fn type_name(&self) -> Option<&'static str> {
496        match self {
497            Self::String(_) => Some("string"),
498            Self::Keyword(_) => Some("keyword"),
499            Self::KeywordList(_) => Some("keyword_list"),
500            Self::Int(_) => Some("int"),
501            Self::Float(_) => Some("float"),
502            Self::Bool(_) => Some("bool"),
503            Self::DateTime(_) => Some("datetime"),
504            Self::Delete => None,
505        }
506    }
507
508    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
509        let normalize_string = |value: String, kind: &'static str, limit: usize| {
510            let value = value.trim().to_string();
511            if value.is_empty() {
512                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
513            }
514            if value.len() > limit {
515                return Err(SearchAttributeUpdateError::ValueTooLong {
516                    key: key.to_string(),
517                    kind,
518                    limit,
519                });
520            }
521            Ok(value)
522        };
523
524        match self {
525            Self::String(value) => Ok(Self::String(normalize_string(
526                value,
527                "string",
528                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
529            )?)),
530            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
531                value,
532                "keyword",
533                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
534            )?)),
535            Self::KeywordList(values) => {
536                let values = values
537                    .into_iter()
538                    .map(|value| {
539                        let value = value.trim().to_string();
540                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
541                            return Err(SearchAttributeUpdateError::ValueTooLong {
542                                key: key.to_string(),
543                                kind: "keyword-list entry",
544                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
545                            });
546                        }
547                        Ok(value)
548                    })
549                    .collect::<std::result::Result<Vec<_>, _>>()?;
550                Ok(Self::KeywordList(values))
551            }
552            Self::Float(value) if !value.is_finite() => {
553                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
554            }
555            Self::DateTime(value) => {
556                let value =
557                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
558                if DateTime::parse_from_rfc3339(&value).is_err() {
559                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
560                }
561                Ok(Self::DateTime(value))
562            }
563            value => Ok(value),
564        }
565    }
566
567    fn into_json(self) -> Value {
568        match self {
569            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
570                Value::String(value)
571            }
572            Self::KeywordList(values) => {
573                Value::Array(values.into_iter().map(Value::String).collect())
574            }
575            Self::Int(value) => json!(value),
576            Self::Float(value) => json!(value),
577            Self::Bool(value) => json!(value),
578            Self::Delete => Value::Null,
579        }
580    }
581}
582
583/// Validated typed workflow-side search-attribute mutation.
584#[derive(Clone, Debug, Default, PartialEq)]
585pub struct SearchAttributeUpdate {
586    attributes: BTreeMap<String, SearchAttributeValue>,
587}
588
589impl SearchAttributeUpdate {
590    pub fn new() -> Self {
591        Self::default()
592    }
593
594    pub fn set(
595        mut self,
596        key: impl Into<String>,
597        value: SearchAttributeValue,
598    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
599        let key = key.into();
600        validate_search_attribute_key(&key)?;
601        if !self.attributes.contains_key(&key)
602            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
603        {
604            return Err(SearchAttributeUpdateError::TooManyAttributes);
605        }
606        self.attributes.insert(key.clone(), value.normalized(&key)?);
607        self.validate_size()?;
608        Ok(self)
609    }
610
611    pub fn string(
612        self,
613        key: impl Into<String>,
614        value: impl Into<String>,
615    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
616        self.set(key, SearchAttributeValue::String(value.into()))
617    }
618
619    pub fn keyword(
620        self,
621        key: impl Into<String>,
622        value: impl Into<String>,
623    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
624        self.set(key, SearchAttributeValue::Keyword(value.into()))
625    }
626
627    pub fn keyword_list<I, V>(
628        self,
629        key: impl Into<String>,
630        values: I,
631    ) -> std::result::Result<Self, SearchAttributeUpdateError>
632    where
633        I: IntoIterator<Item = V>,
634        V: Into<String>,
635    {
636        self.set(
637            key,
638            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
639        )
640    }
641
642    pub fn int(
643        self,
644        key: impl Into<String>,
645        value: i64,
646    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
647        self.set(key, SearchAttributeValue::Int(value))
648    }
649
650    pub fn float(
651        self,
652        key: impl Into<String>,
653        value: f64,
654    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
655        self.set(key, SearchAttributeValue::Float(value))
656    }
657
658    pub fn bool(
659        self,
660        key: impl Into<String>,
661        value: bool,
662    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
663        self.set(key, SearchAttributeValue::Bool(value))
664    }
665
666    pub fn datetime(
667        self,
668        key: impl Into<String>,
669        value: impl Into<String>,
670    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
671        self.set(key, SearchAttributeValue::DateTime(value.into()))
672    }
673
674    pub fn delete(
675        self,
676        key: impl Into<String>,
677    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
678        self.set(key, SearchAttributeValue::Delete)
679    }
680
681    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
682        let (attributes, _) = self.clone().into_wire_parts();
683        if serde_json::to_vec(&attributes)
684            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
685            .unwrap_or(true)
686        {
687            return Err(SearchAttributeUpdateError::PayloadTooLarge);
688        }
689        Ok(())
690    }
691
692    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
693        let mut attributes = serde_json::Map::new();
694        let mut attribute_types = BTreeMap::new();
695        for (key, value) in self.attributes {
696            if let Some(type_name) = value.type_name() {
697                attribute_types.insert(key.clone(), type_name.to_string());
698            }
699            attributes.insert(key, value.into_json());
700        }
701        (Value::Object(attributes), attribute_types)
702    }
703
704    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
705        if self.attributes.is_empty() {
706            return Err(SearchAttributeUpdateError::Empty);
707        }
708        self.validate_size()
709    }
710}
711
712fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
713    let valid = !key.is_empty()
714        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
715        && key
716            .bytes()
717            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
718    if valid {
719        Ok(())
720    } else {
721        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
722    }
723}
724
725/// The registered handler family reported by [`Error::HandlerType`].
726#[derive(Clone, Copy, Debug, PartialEq, Eq)]
727pub enum HandlerKind {
728    Workflow,
729    Activity,
730}
731
732impl std::fmt::Display for HandlerKind {
733    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
734        formatter.write_str(match self {
735            Self::Workflow => "workflow",
736            Self::Activity => "activity",
737        })
738    }
739}
740
741/// Whether a typed handler failed to adapt its input or result.
742#[derive(Clone, Copy, Debug, PartialEq, Eq)]
743pub enum HandlerValueKind {
744    Input,
745    Result,
746}
747
748impl std::fmt::Display for HandlerValueKind {
749    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
750        formatter.write_str(match self {
751            Self::Input => "input",
752            Self::Result => "result",
753        })
754    }
755}
756
757/// The lifecycle command sent to a workflow execution.
758#[derive(Clone, Copy, Debug, PartialEq, Eq)]
759pub enum WorkflowCommandKind {
760    Cancel,
761    Terminate,
762}
763
764impl WorkflowCommandKind {
765    fn as_str(self) -> &'static str {
766        match self {
767            Self::Cancel => "cancel",
768            Self::Terminate => "terminate",
769        }
770    }
771}
772
773/// Optional structured fields for a cancellation or termination request.
774#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
775pub struct WorkflowCommandOptions {
776    #[serde(skip_serializing_if = "Option::is_none")]
777    pub reason: Option<String>,
778    #[serde(skip_serializing_if = "Option::is_none")]
779    pub request_id: Option<String>,
780}
781
782/// Server-enforced timeout policy for a workflow start.
783///
784/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
785/// only bounds how long the caller waits. A server deadline produces a terminal
786/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
787/// `run_timeout`.
788#[derive(Clone, Debug, PartialEq, Eq)]
789pub struct WorkflowStartOptions {
790    pub execution_timeout_seconds: u64,
791    pub run_timeout_seconds: u64,
792}
793
794impl Default for WorkflowStartOptions {
795    fn default() -> Self {
796        Self {
797            execution_timeout_seconds: 3600,
798            run_timeout_seconds: 600,
799        }
800    }
801}
802
803impl WorkflowStartOptions {
804    pub fn new() -> Self {
805        Self::default()
806    }
807
808    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
809        self.execution_timeout_seconds = seconds;
810        self
811    }
812
813    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
814        self.run_timeout_seconds = seconds;
815        self
816    }
817
818    fn validate(&self) -> Result<()> {
819        if self.execution_timeout_seconds == 0 {
820            return Err(Error::Codec(
821                "execution_timeout_seconds must be at least 1".to_string(),
822            ));
823        }
824        if self.run_timeout_seconds == 0 {
825            return Err(Error::Codec(
826                "run_timeout_seconds must be at least 1".to_string(),
827            ));
828        }
829        if self.run_timeout_seconds > self.execution_timeout_seconds {
830            return Err(Error::Codec(
831                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
832            ));
833        }
834
835        Ok(())
836    }
837}
838
839/// Optional routing overrides for a continue-as-new transition.
840///
841/// Omitted values retain the current workflow type and task queue. Server-owned
842/// instance metadata is not accepted here and is carried by the server.
843#[derive(Clone, Debug, Default, PartialEq, Eq)]
844pub struct ContinueAsNewOptions {
845    pub workflow_type: Option<String>,
846    pub task_queue: Option<String>,
847}
848
849impl ContinueAsNewOptions {
850    pub fn new() -> Self {
851        Self::default()
852    }
853
854    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
855        self.workflow_type = Some(workflow_type.into());
856        self
857    }
858
859    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
860        self.task_queue = Some(task_queue.into());
861        self
862    }
863
864    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
865        for (field, value) in [
866            ("workflow_type", self.workflow_type.as_deref()),
867            ("task_queue", self.task_queue.as_deref()),
868        ] {
869            if value.is_some_and(|value| value.trim().is_empty()) {
870                return Err(ContinueAsNewOptionsError {
871                    field,
872                    message: format!("{field} must not be empty"),
873                });
874            }
875        }
876        Ok(())
877    }
878}
879
880/// A stable validation error raised before a continue-as-new command is emitted.
881#[derive(Clone, Debug, Error, PartialEq, Eq)]
882#[error("invalid continue-as-new option {field}: {message}")]
883pub struct ContinueAsNewOptionsError {
884    pub field: &'static str,
885    pub message: String,
886}
887
888/// Public history-budget information attached to the current workflow task.
889#[derive(Clone, Debug, Default, PartialEq, Eq)]
890pub struct WorkflowHistoryBudget {
891    pub event_count: u64,
892    pub size_bytes: Option<u64>,
893    pub continue_as_new_recommended: bool,
894    pub pressure: Option<String>,
895}
896
897#[doc(hidden)]
898#[derive(Clone, Debug)]
899pub struct ContinueAsNewRequest {
900    arguments: AvroValue,
901    options: ContinueAsNewOptions,
902}
903
904impl WorkflowCommandOptions {
905    pub fn new() -> Self {
906        Self::default()
907    }
908
909    pub fn reason(mut self, reason: impl Into<String>) -> Self {
910        self.reason = Some(reason.into());
911        self
912    }
913
914    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
915        self.request_id = Some(request_id.into());
916        self
917    }
918}
919
920/// The accepted, machine-readable result of a lifecycle command.
921#[derive(Clone, Debug, PartialEq)]
922pub struct WorkflowCommandResult {
923    pub command: WorkflowCommandKind,
924    pub workflow_id: String,
925    pub run_id: Option<String>,
926    pub outcome: Option<String>,
927    pub reason: Option<String>,
928    pub command_status: Option<String>,
929    pub raw: Value,
930}
931
932/// A new run continuing a failed run from its recorded activity boundary.
933#[derive(Clone, Debug, PartialEq)]
934pub struct WorkflowRedriveResult {
935    pub workflow_id: String,
936    pub source_run_id: String,
937    pub run_id: String,
938    pub resume_step_sequence: u64,
939    pub raw: Value,
940}
941
942/// A stable rejection returned by instance- or selected-run lifecycle commands.
943#[derive(Clone, Debug, Error)]
944#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
945pub struct WorkflowCommandRejection {
946    pub command: WorkflowCommandKind,
947    pub status: u16,
948    pub reason: String,
949    pub message: String,
950    pub workflow_id: String,
951    pub run_id: Option<String>,
952    pub target_scope: Option<String>,
953    pub body: Value,
954}
955
956/// Stable terminal categories returned by [`WorkflowHandle::result`].
957#[derive(Clone, Copy, Debug, PartialEq, Eq)]
958pub enum WorkflowTerminalKind {
959    Failed,
960    Cancelled,
961    Terminated,
962    TimedOut,
963}
964
965/// A typed terminal workflow outcome with durable identity and failure metadata.
966///
967/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
968/// of parsing its display representation. Fields remain `None` when an older
969/// server did not publish that metadata.
970#[derive(Clone, Debug, Error)]
971#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
972pub struct WorkflowTerminalOutcome {
973    pub kind: WorkflowTerminalKind,
974    pub workflow_id: String,
975    pub run_id: Option<String>,
976    pub reason: String,
977    pub failure_category: Option<String>,
978    pub failure_id: Option<String>,
979    pub exception_type: Option<String>,
980    pub exception_class: Option<String>,
981    pub non_retryable: Option<bool>,
982    pub message: Option<String>,
983    pub exception: Option<Value>,
984    pub raw: Value,
985}
986
987/// A worker-side activity settlement or heartbeat rejected by durable state.
988#[derive(Clone, Debug, Error)]
989#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
990pub struct ActivityTaskRejection {
991    pub operation: String,
992    pub status: u16,
993    pub reason: String,
994    pub task_id: String,
995    pub activity_attempt_id: String,
996    pub cancel_requested: bool,
997    pub can_continue: Option<bool>,
998    pub run_closed_reason: Option<String>,
999    pub body: Value,
1000}
1001
1002/// Stable validation categories for [`ActivityOptions`].
1003#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1004pub enum ActivityOptionsErrorKind {
1005    EmptyTaskQueue,
1006    EmptyRetryPolicy,
1007    InvalidMaxAttempts,
1008    BackoffWithoutRetryBudget,
1009    TooManyBackoffIntervals,
1010    InvalidBackoffCoefficient,
1011    BackoffGenerationTooLarge,
1012    BackoffOverflow,
1013    EmptyNonRetryableErrorType,
1014    TimeoutNotPositive,
1015    MissingTotalTimeout,
1016    TimeoutOverflow,
1017    TimeoutOrder,
1018}
1019
1020/// A machine-readable activity-options validation failure.
1021#[derive(Clone, Debug, Error, PartialEq, Eq)]
1022#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1023pub struct ActivityOptionsError {
1024    pub kind: ActivityOptionsErrorKind,
1025    pub field: Option<&'static str>,
1026    pub message: String,
1027}
1028
1029impl ActivityOptionsError {
1030    fn new(
1031        kind: ActivityOptionsErrorKind,
1032        field: Option<&'static str>,
1033        message: impl Into<String>,
1034    ) -> Self {
1035        Self {
1036            kind,
1037            field,
1038            message: message.into(),
1039        }
1040    }
1041}
1042
1043/// Stable terminal categories returned when an awaited activity does not succeed.
1044#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1045pub enum ActivityFailureKind {
1046    Failed,
1047    Cancelled,
1048    TimedOut,
1049}
1050
1051/// A stable, machine-readable terminal activity failure.
1052///
1053/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1054/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1055#[derive(Clone, Debug, Error, PartialEq)]
1056#[error("activity failed ({reason}): {message}")]
1057pub struct ActivityFailure {
1058    pub kind: ActivityFailureKind,
1059    pub reason: String,
1060    pub message: String,
1061    pub activity_execution_id: Option<String>,
1062    pub activity_attempt_id: Option<String>,
1063    pub activity_type: Option<String>,
1064    pub activity_class: Option<String>,
1065    pub attempt_number: Option<u64>,
1066    pub failure_id: Option<String>,
1067    pub failure_category: Option<String>,
1068    pub timeout_kind: Option<String>,
1069    pub non_retryable: bool,
1070    pub exception_type: Option<String>,
1071    pub exception_class: Option<String>,
1072    pub code: Option<Value>,
1073    pub exception: Option<Value>,
1074}
1075
1076/// Stable terminal categories returned when an awaited child does not succeed.
1077#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1078pub enum ChildWorkflowFailureKind {
1079    Failed,
1080    Cancelled,
1081    Terminated,
1082}
1083
1084/// A stable, machine-readable child workflow failure delivered to its parent.
1085///
1086/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1087/// of parsing the display message. Child and parent identifiers retain the
1088/// relationship recorded in durable history across worker restarts.
1089#[derive(Clone, Debug, Error)]
1090#[error("child workflow failed ({reason}): {message}")]
1091pub struct ChildWorkflowFailure {
1092    pub kind: ChildWorkflowFailureKind,
1093    pub reason: String,
1094    pub message: String,
1095    pub parent_workflow_id: Option<String>,
1096    pub parent_workflow_run_id: Option<String>,
1097    pub child_workflow_id: Option<String>,
1098    pub child_workflow_run_id: Option<String>,
1099    pub child_workflow_type: Option<String>,
1100    pub failure_id: Option<String>,
1101    pub failure_category: Option<String>,
1102    pub exception_type: Option<String>,
1103    pub exception_class: Option<String>,
1104    pub non_retryable: bool,
1105    pub code: Option<Value>,
1106    pub exception: Option<Value>,
1107}
1108
1109/// The identity of one durable workflow execution.
1110#[derive(Clone, Debug, PartialEq, Eq)]
1111pub struct WorkflowIdentity {
1112    pub workflow_id: Option<String>,
1113    pub run_id: Option<String>,
1114}
1115
1116/// A successful child result together with its durable parent-child identity.
1117#[derive(Clone, Debug, PartialEq)]
1118pub struct ChildWorkflowResult {
1119    pub parent: WorkflowIdentity,
1120    pub child: WorkflowIdentity,
1121    pub child_workflow_type: Option<String>,
1122    pub result: Value,
1123}
1124
1125/// Lossless successful child result for fixed Avro Value workflows.
1126#[derive(Clone, Debug, PartialEq)]
1127pub struct ChildWorkflowAvroResult {
1128    pub parent: WorkflowIdentity,
1129    pub child: WorkflowIdentity,
1130    pub child_workflow_type: Option<String>,
1131    pub result: AvroValue,
1132}
1133
1134/// Stable user-facing identity for one member of a durable selection group.
1135#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1136#[serde(untagged)]
1137pub enum SelectionKey {
1138    Index(usize),
1139    Name(String),
1140}
1141
1142impl From<usize> for SelectionKey {
1143    fn from(value: usize) -> Self {
1144        Self::Index(value)
1145    }
1146}
1147
1148impl From<String> for SelectionKey {
1149    fn from(value: String) -> Self {
1150        Self::Name(value)
1151    }
1152}
1153
1154impl From<&str> for SelectionKey {
1155    fn from(value: &str) -> Self {
1156        Self::Name(value.to_string())
1157    }
1158}
1159
1160/// Typed result of explicitly awaiting a cancelled non-winning operation.
1161#[derive(Clone, Debug, Error, PartialEq, Eq)]
1162#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1163pub struct DurableOperationCancelled {
1164    pub selection_group_id: String,
1165    pub member_key: SelectionKey,
1166    pub member_index: usize,
1167    pub operation_kind: String,
1168    pub operation_identity: String,
1169}
1170
1171/// Stable identity for one enclosing deterministic parallel group.
1172///
1173/// The same fields are attached to every ordinary activity, timer, or child
1174/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1175/// no Rust-specific wire command is introduced.
1176#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1177pub struct ParallelGroupMetadata {
1178    pub parallel_group_id: String,
1179    pub parallel_group_kind: String,
1180    pub parallel_group_base_sequence: u64,
1181    pub parallel_group_size: usize,
1182    pub parallel_group_index: usize,
1183    #[serde(default, skip_serializing_if = "Option::is_none")]
1184    pub parallel_group_mode: Option<String>,
1185    #[serde(default, skip_serializing_if = "Option::is_none")]
1186    pub selection_member_key: Option<SelectionKey>,
1187    #[serde(default, skip_serializing_if = "Option::is_none")]
1188    pub selection_member_index: Option<usize>,
1189    #[serde(default, skip_serializing_if = "Option::is_none")]
1190    pub selection_member_base_sequence: Option<u64>,
1191    #[serde(default, skip_serializing_if = "Option::is_none")]
1192    pub selection_member_size: Option<usize>,
1193    #[serde(default, skip_serializing_if = "Option::is_none")]
1194    pub selection_member_kind: Option<String>,
1195}
1196
1197/// One input-ordered result returned by [`WorkflowContext::parallel`].
1198#[derive(Clone, Debug, PartialEq)]
1199pub enum ParallelResult {
1200    Activity(Value),
1201    ChildWorkflow(ChildWorkflowResult),
1202    Timer,
1203    Signal(Vec<Value>),
1204    Condition(ConditionWaitResult),
1205    Group(Vec<ParallelResult>),
1206}
1207
1208/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1209#[derive(Clone, Debug, PartialEq)]
1210pub enum ParallelAvroResult {
1211    Activity(AvroValue),
1212    ChildWorkflow(ChildWorkflowAvroResult),
1213    Timer,
1214    Signal(Vec<AvroValue>),
1215    Condition(ConditionWaitResult),
1216    Group(Vec<ParallelAvroResult>),
1217}
1218
1219impl ParallelAvroResult {
1220    fn into_json_result(self) -> Result<ParallelResult> {
1221        match self {
1222            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1223            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1224                parent: result.parent,
1225                child: result.child,
1226                child_workflow_type: result.child_workflow_type,
1227                result: result.result.into_json()?,
1228            })),
1229            Self::Timer => Ok(ParallelResult::Timer),
1230            Self::Signal(values) => Ok(ParallelResult::Signal(
1231                values
1232                    .into_iter()
1233                    .map(AvroValue::into_json)
1234                    .collect::<Result<Vec<_>>>()?,
1235            )),
1236            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1237            Self::Group(results) => Ok(ParallelResult::Group(
1238                results
1239                    .into_iter()
1240                    .map(Self::into_json_result)
1241                    .collect::<Result<Vec<_>>>()?,
1242            )),
1243        }
1244    }
1245}
1246
1247/// One successful leaf retained when another parallel member failed.
1248#[derive(Clone, Debug, PartialEq)]
1249pub struct ParallelCompletion {
1250    pub member_path: Vec<usize>,
1251    pub result: ParallelResult,
1252}
1253
1254/// A deterministic join failed after some siblings had already completed.
1255///
1256/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1257/// error. `completed` is declaration ordered and contains only durable
1258/// successes observed in the same replay. Late sibling completions can add
1259/// entries on a later replay without changing `member_path` or the selected
1260/// positional failure.
1261#[derive(Debug, Error)]
1262#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1263pub struct ParallelFailure {
1264    pub group_id: String,
1265    pub member_path: Vec<usize>,
1266    pub group_path: Vec<ParallelGroupMetadata>,
1267    pub completed: Vec<ParallelCompletion>,
1268    #[source]
1269    pub cause: Box<Error>,
1270}
1271
1272/// Stable validation error returned before an invalid group emits commands.
1273#[derive(Clone, Debug, Error, PartialEq, Eq)]
1274#[error("invalid deterministic parallel group ({reason}): {message}")]
1275pub struct ParallelGroupError {
1276    pub reason: &'static str,
1277    pub member_path: Vec<usize>,
1278    pub message: String,
1279}
1280
1281/// Cooperative workflow cancellation observed at an author-controlled point.
1282#[derive(Clone, Debug, Error, PartialEq, Eq)]
1283#[error("workflow cancellation was requested")]
1284pub struct WorkflowCancellationRequested;
1285
1286/// A forward saga failure followed by a terminal compensation failure.
1287#[derive(Debug, Error)]
1288#[error(
1289    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1290)]
1291pub struct SagaCompensationFailure {
1292    pub initiating_failure: Box<Error>,
1293    pub compensation_failure: Box<Error>,
1294    pub compensation_activity_type: String,
1295    pub compensation_registration_order: usize,
1296}
1297
1298/// Server behavior when a parent closes while its child is still open.
1299#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1300pub enum ParentClosePolicy {
1301    #[default]
1302    Abandon,
1303    /// Legacy terminal cancellation without cooperative cleanup.
1304    RequestCancel,
1305    /// Request cooperative cleanup with the original lineage and deadline.
1306    RequestCancellation,
1307    Terminate,
1308}
1309
1310impl ParentClosePolicy {
1311    fn as_str(self) -> &'static str {
1312        match self {
1313            Self::Abandon => "abandon",
1314            Self::RequestCancel => "request_cancel",
1315            Self::RequestCancellation => "request_cancellation",
1316            Self::Terminate => "terminate",
1317        }
1318    }
1319}
1320
1321/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1322#[non_exhaustive]
1323#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1324pub enum CancellationPolicy {
1325    /// Request cancellation and continue without waiting. Historical Activity default.
1326    TryCancel,
1327    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1328    WaitCancellationCompleted,
1329    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1330    #[default]
1331    Abandon,
1332}
1333
1334impl CancellationPolicy {
1335    fn as_str(self) -> &'static str {
1336        match self {
1337            Self::TryCancel => "try_cancel",
1338            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1339            Self::Abandon => "abandon",
1340        }
1341    }
1342}
1343
1344/// Durable retry policy for one child workflow invocation.
1345#[derive(Clone, Debug, Default, PartialEq, Eq)]
1346pub struct ChildWorkflowRetryPolicy {
1347    pub max_attempts: Option<u32>,
1348    pub backoff_seconds: Vec<u64>,
1349    pub non_retryable_error_types: Vec<String>,
1350}
1351
1352/// Options recorded with a child-workflow command.
1353///
1354/// The task queue is mandatory so routing is explicit and replay-stable.
1355#[derive(Clone, Debug, PartialEq, Eq)]
1356pub struct ChildWorkflowOptions {
1357    pub task_queue: String,
1358    pub parent_close_policy: ParentClosePolicy,
1359    pub cancellation_policy: CancellationPolicy,
1360    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1361    pub execution_timeout_seconds: Option<u64>,
1362    pub run_timeout_seconds: Option<u64>,
1363}
1364
1365impl ChildWorkflowOptions {
1366    pub fn new(task_queue: impl Into<String>) -> Self {
1367        Self {
1368            task_queue: task_queue.into(),
1369            parent_close_policy: ParentClosePolicy::Abandon,
1370            cancellation_policy: CancellationPolicy::Abandon,
1371            retry_policy: None,
1372            execution_timeout_seconds: None,
1373            run_timeout_seconds: None,
1374        }
1375    }
1376
1377    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1378        self.parent_close_policy = policy;
1379        self
1380    }
1381
1382    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1383        self.cancellation_policy = policy;
1384        self
1385    }
1386
1387    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1388        self.retry_policy = Some(policy);
1389        self
1390    }
1391
1392    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1393        self.execution_timeout_seconds = Some(seconds);
1394        self
1395    }
1396
1397    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1398        self.run_timeout_seconds = Some(seconds);
1399        self
1400    }
1401}
1402
1403/// Backoff intervals for one durable activity retry policy.
1404#[derive(Clone, Debug, PartialEq, Eq)]
1405pub enum ActivityBackoff {
1406    /// Use these intervals between attempts. The server repeats the final
1407    /// interval if the retry budget contains more attempts than entries.
1408    Explicit(Vec<Duration>),
1409    /// Generate one interval for every retry using integer exponential growth.
1410    Exponential {
1411        initial_interval: Duration,
1412        coefficient: u32,
1413        maximum_interval: Option<Duration>,
1414    },
1415}
1416
1417/// Durable server-side retry policy for one activity execution.
1418#[derive(Clone, Debug, Default, PartialEq, Eq)]
1419pub struct ActivityRetryPolicy {
1420    pub max_attempts: Option<u32>,
1421    pub backoff: Option<ActivityBackoff>,
1422    pub non_retryable_error_types: Vec<String>,
1423}
1424
1425impl ActivityRetryPolicy {
1426    /// Start a policy with a finite attempt budget, including the first attempt.
1427    pub fn new(max_attempts: u32) -> Self {
1428        Self {
1429            max_attempts: Some(max_attempts),
1430            ..Self::default()
1431        }
1432    }
1433
1434    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1435        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1436        self
1437    }
1438
1439    pub fn exponential_backoff(
1440        mut self,
1441        initial_interval: Duration,
1442        coefficient: u32,
1443        maximum_interval: Option<Duration>,
1444    ) -> Self {
1445        self.backoff = Some(ActivityBackoff::Exponential {
1446            initial_interval,
1447            coefficient,
1448            maximum_interval,
1449        });
1450        self
1451    }
1452
1453    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1454        self.non_retryable_error_types.push(error_type.into());
1455        self
1456    }
1457
1458    pub fn non_retryable_error_types(
1459        mut self,
1460        error_types: impl IntoIterator<Item = impl Into<String>>,
1461    ) -> Self {
1462        self.non_retryable_error_types
1463            .extend(error_types.into_iter().map(Into::into));
1464        self
1465    }
1466}
1467
1468/// Options recorded atomically on one deterministic `schedule_activity` command.
1469///
1470/// Durations are rounded up to whole seconds when encoded, so the server never
1471/// receives a shorter timeout or backoff than the caller requested.
1472#[derive(Clone, Debug, Default, PartialEq, Eq)]
1473pub struct ActivityOptions {
1474    pub task_queue: Option<String>,
1475    pub retry_policy: Option<ActivityRetryPolicy>,
1476    pub start_to_close_timeout: Option<Duration>,
1477    pub schedule_to_start_timeout: Option<Duration>,
1478    pub schedule_to_close_timeout: Option<Duration>,
1479    pub heartbeat_timeout: Option<Duration>,
1480    pub cancellation_policy: Option<CancellationPolicy>,
1481}
1482
1483impl ActivityOptions {
1484    pub fn new() -> Self {
1485        Self::default()
1486    }
1487
1488    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1489        self.task_queue = Some(task_queue.into());
1490        self
1491    }
1492
1493    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1494        self.retry_policy = Some(policy);
1495        self
1496    }
1497
1498    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1499        self.start_to_close_timeout = Some(timeout);
1500        self
1501    }
1502
1503    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1504        self.schedule_to_start_timeout = Some(timeout);
1505        self
1506    }
1507
1508    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1509        self.schedule_to_close_timeout = Some(timeout);
1510        self
1511    }
1512
1513    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1514        self.heartbeat_timeout = Some(timeout);
1515        self
1516    }
1517
1518    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1519        self.cancellation_policy = Some(policy);
1520        self
1521    }
1522
1523    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1524        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1525            && self.schedule_to_close_timeout.is_none()
1526        {
1527            return Err(ActivityOptionsError::new(
1528                ActivityOptionsErrorKind::MissingTotalTimeout,
1529                Some("schedule_to_close_timeout"),
1530                "remote Activity Abandon requires a finite positive total timeout",
1531            ));
1532        }
1533        if self
1534            .task_queue
1535            .as_deref()
1536            .is_some_and(|queue| queue.trim().is_empty())
1537        {
1538            return Err(ActivityOptionsError::new(
1539                ActivityOptionsErrorKind::EmptyTaskQueue,
1540                Some("task_queue"),
1541                "task_queue must not be empty",
1542            ));
1543        }
1544
1545        for (field, value) in [
1546            ("start_to_close_timeout", self.start_to_close_timeout),
1547            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1548            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1549            ("heartbeat_timeout", self.heartbeat_timeout),
1550        ] {
1551            if value.is_some_and(|value| value.is_zero()) {
1552                return Err(ActivityOptionsError::new(
1553                    ActivityOptionsErrorKind::TimeoutNotPositive,
1554                    Some(field),
1555                    format!("{field} must be positive"),
1556                ));
1557            }
1558        }
1559
1560        validate_timeout_order(
1561            "heartbeat_timeout",
1562            self.heartbeat_timeout,
1563            "start_to_close_timeout",
1564            self.start_to_close_timeout,
1565        )?;
1566        validate_timeout_order(
1567            "start_to_close_timeout",
1568            self.start_to_close_timeout,
1569            "schedule_to_close_timeout",
1570            self.schedule_to_close_timeout,
1571        )?;
1572        validate_timeout_order(
1573            "schedule_to_start_timeout",
1574            self.schedule_to_start_timeout,
1575            "schedule_to_close_timeout",
1576            self.schedule_to_close_timeout,
1577        )?;
1578
1579        Ok(ValidatedActivityOptions {
1580            task_queue: self.task_queue.clone(),
1581            retry_policy: self
1582                .retry_policy
1583                .as_ref()
1584                .map(validate_activity_retry_policy)
1585                .transpose()?,
1586            start_to_close_timeout: timeout_seconds(
1587                "start_to_close_timeout",
1588                self.start_to_close_timeout,
1589            )?,
1590            schedule_to_start_timeout: timeout_seconds(
1591                "schedule_to_start_timeout",
1592                self.schedule_to_start_timeout,
1593            )?,
1594            schedule_to_close_timeout: timeout_seconds(
1595                "schedule_to_close_timeout",
1596                self.schedule_to_close_timeout,
1597            )?,
1598            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1599            cancellation_policy: self.cancellation_policy,
1600        })
1601    }
1602}
1603
1604/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1605///
1606/// Constructors capture arguments but perform no I/O. The join validates the
1607/// complete tree, attaches the existing parallel-group metadata to every
1608/// ordinary command, schedules all leaves, and then suspends.
1609pub enum ParallelOperation {
1610    Activity {
1611        activity_type: String,
1612        options: ActivityOptions,
1613        arguments: Result<AvroValue>,
1614    },
1615    ChildWorkflow {
1616        workflow_type: String,
1617        options: ChildWorkflowOptions,
1618        arguments: Result<AvroValue>,
1619    },
1620    Timer(Duration),
1621    Signal(String),
1622    Condition {
1623        options: ConditionWaitOptions,
1624        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1625    },
1626    Group(Vec<ParallelOperation>),
1627}
1628
1629impl ParallelOperation {
1630    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1631        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1632    }
1633
1634    pub fn activity_with_options<T: Serialize>(
1635        activity_type: impl Into<String>,
1636        options: ActivityOptions,
1637        args: T,
1638    ) -> Self {
1639        Self::Activity {
1640            activity_type: activity_type.into(),
1641            options,
1642            arguments: AvroValue::from_serialize(&args),
1643        }
1644    }
1645
1646    pub fn child_workflow<T: Serialize>(
1647        workflow_type: impl Into<String>,
1648        options: ChildWorkflowOptions,
1649        args: T,
1650    ) -> Self {
1651        Self::ChildWorkflow {
1652            workflow_type: workflow_type.into(),
1653            options,
1654            arguments: AvroValue::from_serialize(&args),
1655        }
1656    }
1657
1658    pub fn timer(duration: Duration) -> Self {
1659        Self::Timer(duration)
1660    }
1661
1662    pub fn signal(signal_name: impl Into<String>) -> Self {
1663        Self::Signal(signal_name.into())
1664    }
1665
1666    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1667    where
1668        F: Fn() -> Result<bool> + Send + 'static,
1669    {
1670        Self::Condition {
1671            options,
1672            predicate: Box::new(predicate),
1673        }
1674    }
1675
1676    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1677        Self::Group(operations)
1678    }
1679}
1680
1681#[derive(Clone, Debug)]
1682struct ValidatedActivityOptions {
1683    task_queue: Option<String>,
1684    retry_policy: Option<Value>,
1685    start_to_close_timeout: Option<u64>,
1686    schedule_to_start_timeout: Option<u64>,
1687    schedule_to_close_timeout: Option<u64>,
1688    heartbeat_timeout: Option<u64>,
1689    cancellation_policy: Option<CancellationPolicy>,
1690}
1691
1692fn validate_timeout_order(
1693    smaller_name: &'static str,
1694    smaller: Option<Duration>,
1695    larger_name: &'static str,
1696    larger: Option<Duration>,
1697) -> std::result::Result<(), ActivityOptionsError> {
1698    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1699        return Err(ActivityOptionsError::new(
1700            ActivityOptionsErrorKind::TimeoutOrder,
1701            Some(smaller_name),
1702            format!("{smaller_name} must be <= {larger_name}"),
1703        ));
1704    }
1705    Ok(())
1706}
1707
1708fn timeout_seconds(
1709    field: &'static str,
1710    value: Option<Duration>,
1711) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1712    value
1713        .map(|value| {
1714            activity_protocol_seconds(value).ok_or_else(|| {
1715                ActivityOptionsError::new(
1716                    ActivityOptionsErrorKind::TimeoutOverflow,
1717                    Some(field),
1718                    format!("{field} is too large for the worker protocol"),
1719                )
1720            })
1721        })
1722        .transpose()
1723}
1724
1725fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1726    value
1727        .as_secs()
1728        .checked_add(u64::from(value.subsec_nanos() > 0))
1729}
1730
1731fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1732    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1733}
1734
1735fn validate_activity_retry_policy(
1736    policy: &ActivityRetryPolicy,
1737) -> std::result::Result<Value, ActivityOptionsError> {
1738    if policy.max_attempts.is_none()
1739        && policy.backoff.is_none()
1740        && policy.non_retryable_error_types.is_empty()
1741    {
1742        return Err(ActivityOptionsError::new(
1743            ActivityOptionsErrorKind::EmptyRetryPolicy,
1744            Some("retry_policy"),
1745            "retry_policy must configure at least one field",
1746        ));
1747    }
1748    if policy.max_attempts == Some(0) {
1749        return Err(ActivityOptionsError::new(
1750            ActivityOptionsErrorKind::InvalidMaxAttempts,
1751            Some("retry_policy.max_attempts"),
1752            "max_attempts must be >= 1",
1753        ));
1754    }
1755    if policy
1756        .non_retryable_error_types
1757        .iter()
1758        .any(|error_type| error_type.trim().is_empty())
1759    {
1760        return Err(ActivityOptionsError::new(
1761            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1762            Some("retry_policy.non_retryable_error_types"),
1763            "non_retryable_error_types must not contain empty values",
1764        ));
1765    }
1766
1767    let backoff_seconds = match &policy.backoff {
1768        None => None,
1769        Some(backoff) => {
1770            let max_attempts = policy.max_attempts.ok_or_else(|| {
1771                ActivityOptionsError::new(
1772                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1773                    Some("retry_policy.backoff"),
1774                    "backoff requires max_attempts",
1775                )
1776            })?;
1777            let retry_count = max_attempts.saturating_sub(1) as usize;
1778            let intervals = match backoff {
1779                ActivityBackoff::Explicit(intervals) => {
1780                    if intervals.len() > retry_count {
1781                        return Err(ActivityOptionsError::new(
1782                            ActivityOptionsErrorKind::TooManyBackoffIntervals,
1783                            Some("retry_policy.backoff"),
1784                            "backoff interval count must not exceed max_attempts - 1",
1785                        ));
1786                    }
1787                    intervals.clone()
1788                }
1789                ActivityBackoff::Exponential {
1790                    initial_interval,
1791                    coefficient,
1792                    maximum_interval,
1793                } => {
1794                    if *coefficient < 1 {
1795                        return Err(ActivityOptionsError::new(
1796                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1797                            Some("retry_policy.backoff.coefficient"),
1798                            "backoff coefficient must be >= 1",
1799                        ));
1800                    }
1801                    if retry_count > 10_000 {
1802                        return Err(ActivityOptionsError::new(
1803                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1804                            Some("retry_policy.max_attempts"),
1805                            "generated backoff supports at most 10000 retry intervals",
1806                        ));
1807                    }
1808                    let mut current = *initial_interval;
1809                    let mut intervals = Vec::with_capacity(retry_count);
1810                    for _ in 0..retry_count {
1811                        let interval = maximum_interval
1812                            .map(|maximum| current.min(maximum))
1813                            .unwrap_or(current);
1814                        intervals.push(interval);
1815                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1816                            break;
1817                        }
1818                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1819                            ActivityOptionsError::new(
1820                                ActivityOptionsErrorKind::BackoffOverflow,
1821                                Some("retry_policy.backoff"),
1822                                "generated backoff interval overflowed",
1823                            )
1824                        })?;
1825                    }
1826                    intervals
1827                }
1828            };
1829            Some(
1830                intervals
1831                    .into_iter()
1832                    .map(|interval| {
1833                        activity_protocol_seconds(interval).ok_or_else(|| {
1834                            ActivityOptionsError::new(
1835                                ActivityOptionsErrorKind::BackoffOverflow,
1836                                Some("retry_policy.backoff"),
1837                                "backoff interval is too large for the worker protocol",
1838                            )
1839                        })
1840                    })
1841                    .collect::<std::result::Result<Vec<_>, _>>()?,
1842            )
1843        }
1844    };
1845
1846    let mut encoded = serde_json::Map::new();
1847    if let Some(max_attempts) = policy.max_attempts {
1848        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1849    }
1850    if let Some(backoff_seconds) = backoff_seconds {
1851        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1852    }
1853    if !policy.non_retryable_error_types.is_empty() {
1854        let mut canonical_error_types = Vec::new();
1855        for error_type in policy
1856            .non_retryable_error_types
1857            .iter()
1858            .map(|error_type| error_type.trim())
1859        {
1860            if !canonical_error_types.contains(&error_type) {
1861                canonical_error_types.push(error_type);
1862            }
1863        }
1864        encoded.insert(
1865            "non_retryable_error_types".to_string(),
1866            json!(canonical_error_types),
1867        );
1868    }
1869    Ok(Value::Object(encoded))
1870}
1871
1872/// A stable, machine-readable failure raised when workflow code no longer
1873/// reconstructs the durable command stream recorded in history.
1874#[derive(Clone, Debug, Error)]
1875#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1876pub struct ReplayFailure {
1877    pub reason: String,
1878    pub sequence: Option<u64>,
1879    pub expected: Option<String>,
1880    pub actual: Option<String>,
1881    pub message: String,
1882}
1883
1884impl ReplayFailure {
1885    fn new(
1886        reason: impl Into<String>,
1887        sequence: Option<u64>,
1888        expected: Option<String>,
1889        actual: Option<String>,
1890        message: impl Into<String>,
1891    ) -> Self {
1892        Self {
1893            reason: reason.into(),
1894            sequence,
1895            expected,
1896            actual,
1897            message: message.into(),
1898        }
1899    }
1900}
1901
1902/// A stable, machine-readable workflow query or query-task settlement failure.
1903#[derive(Clone, Debug, Error)]
1904#[error("query failed ({reason}, HTTP {status}): {message}")]
1905pub struct QueryFailure {
1906    pub status: u16,
1907    pub reason: String,
1908    pub message: String,
1909    pub body: Value,
1910}
1911
1912/// A stable failure returned when a server rejects an SDK protocol version.
1913#[derive(Clone, Debug, Error)]
1914#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
1915pub struct ProtocolFailure {
1916    pub status: u16,
1917    pub reason: String,
1918    pub message: String,
1919    pub supported_version: Option<String>,
1920    pub requested_version: Option<String>,
1921    pub body: Value,
1922}
1923
1924#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1925pub struct PayloadEnvelope {
1926    pub codec: String,
1927    pub blob: String,
1928}
1929
1930impl PayloadEnvelope {
1931    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
1932        encode_payload(value, DEFAULT_CODEC)
1933    }
1934
1935    /// Encode an explicit typed value, including the bytes branch that JSON
1936    /// serialization cannot represent.
1937    pub fn avro_value(value: &AvroValue) -> Result<Self> {
1938        encode_avro_value(value)
1939    }
1940}
1941
1942/// Native adapter for the fixed language-neutral Avro Value schema.
1943#[derive(Clone, Debug)]
1944pub enum AvroValue {
1945    Null,
1946    Boolean(bool),
1947    Long(i64),
1948    Double(f64),
1949    Bytes(Vec<u8>),
1950    String(String),
1951    Array(Vec<AvroValue>),
1952    Map(BTreeMap<String, AvroValue>),
1953}
1954
1955impl PartialEq for AvroValue {
1956    fn eq(&self, other: &Self) -> bool {
1957        match (self, other) {
1958            (Self::Null, Self::Null) => true,
1959            (Self::Boolean(left), Self::Boolean(right)) => left == right,
1960            (Self::Long(left), Self::Long(right)) => left == right,
1961            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
1962            (Self::Bytes(left), Self::Bytes(right)) => left == right,
1963            (Self::String(left), Self::String(right)) => left == right,
1964            (Self::Array(left), Self::Array(right)) => left == right,
1965            (Self::Map(left), Self::Map(right)) => left == right,
1966            _ => false,
1967        }
1968    }
1969}
1970
1971impl AvroValue {
1972    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
1973        Self::from_serde_value(
1974            serde_value::to_value(value).map_err(|error| {
1975                Error::Codec(format!("could not adapt value for Avro: {error}"))
1976            })?,
1977        )
1978    }
1979
1980    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
1981        use serde_value::Value as SerdeValue;
1982
1983        match value {
1984            SerdeValue::Unit => Ok(Self::Null),
1985            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
1986            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
1987            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
1988            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
1989            SerdeValue::I64(value) => Ok(Self::Long(value)),
1990            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
1991            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
1992            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
1993            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
1994                Error::Codec(
1995                    "integer_overflow: Avro Value long must be within signed 64-bit range"
1996                        .to_string(),
1997                )
1998            }),
1999            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2000            SerdeValue::F64(value) => Self::finite_double(value),
2001            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2002            SerdeValue::String(value) => Ok(Self::String(value)),
2003            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2004            SerdeValue::Option(None) => Ok(Self::Null),
2005            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2006                Self::from_serde_value(*value)
2007            }
2008            SerdeValue::Seq(values) => values
2009                .into_iter()
2010                .map(Self::from_serde_value)
2011                .collect::<Result<Vec<_>>>()
2012                .map(Self::Array),
2013            SerdeValue::Map(values) => values
2014                .into_iter()
2015                .map(|(key, value)| {
2016                    let SerdeValue::String(key) = key else {
2017                        return Err(Error::Codec(
2018                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2019                        ));
2020                    };
2021
2022                    Ok((key, Self::from_serde_value(value)?))
2023                })
2024                .collect::<Result<BTreeMap<_, _>>>()
2025                .map(Self::Map),
2026        }
2027    }
2028
2029    fn finite_double(value: f64) -> Result<Self> {
2030        if !value.is_finite() {
2031            return Err(Error::Codec(
2032                "non_finite_float: Avro Value doubles must be finite".to_string(),
2033            ));
2034        }
2035
2036        Ok(Self::Double(value))
2037    }
2038
2039    fn into_json(self) -> Result<Value> {
2040        match self {
2041            Self::Null => Ok(Value::Null),
2042            Self::Boolean(value) => Ok(Value::Bool(value)),
2043            Self::Long(value) => Ok(Value::Number(value.into())),
2044            Self::Double(value) => serde_json::Number::from_f64(value)
2045                .map(Value::Number)
2046                .ok_or_else(|| {
2047                    Error::Codec(
2048                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2049                    )
2050                }),
2051            Self::Bytes(value) => Ok(json!({
2052                "$type": "bytes",
2053                "base64": BASE64.encode(value),
2054            })),
2055            Self::String(value) => Ok(Value::String(value)),
2056            Self::Array(values) => values
2057                .into_iter()
2058                .map(Self::into_json)
2059                .collect::<Result<Vec<_>>>()
2060                .map(Value::Array),
2061            Self::Map(values) => values
2062                .into_iter()
2063                .map(|(key, value)| Ok((key, value.into_json()?)))
2064                .collect::<Result<serde_json::Map<_, _>>>()
2065                .map(Value::Object),
2066        }
2067    }
2068
2069    fn into_serde_value(self) -> serde_value::Value {
2070        use serde_value::Value as SerdeValue;
2071
2072        match self {
2073            Self::Null => SerdeValue::Unit,
2074            Self::Boolean(value) => SerdeValue::Bool(value),
2075            Self::Long(value) => SerdeValue::I64(value),
2076            Self::Double(value) => SerdeValue::F64(value),
2077            Self::Bytes(value) => SerdeValue::Bytes(value),
2078            Self::String(value) => SerdeValue::String(value),
2079            Self::Array(values) => {
2080                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2081            }
2082            Self::Map(values) => SerdeValue::Map(
2083                values
2084                    .into_iter()
2085                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2086                    .collect(),
2087            ),
2088        }
2089    }
2090
2091    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2092        self.into_serde_value().deserialize_into().map_err(|error| {
2093            Error::Codec(format!(
2094                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2095            ))
2096        })
2097    }
2098}
2099
2100impl Serialize for AvroValue {
2101    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2102    where
2103        S: Serializer,
2104    {
2105        match self {
2106            Self::Null => serializer.serialize_unit(),
2107            Self::Boolean(value) => serializer.serialize_bool(*value),
2108            Self::Long(value) => serializer.serialize_i64(*value),
2109            Self::Double(value) => serializer.serialize_f64(*value),
2110            Self::Bytes(value) => serializer.serialize_bytes(value),
2111            Self::String(value) => serializer.serialize_str(value),
2112            Self::Array(values) => {
2113                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2114                for value in values {
2115                    sequence.serialize_element(value)?;
2116                }
2117                sequence.end()
2118            }
2119            Self::Map(values) => {
2120                let mut map = serializer.serialize_map(Some(values.len()))?;
2121                for (key, value) in values {
2122                    map.serialize_entry(key, value)?;
2123                }
2124                map.end()
2125            }
2126        }
2127    }
2128}
2129
2130pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2131    let datum = avro_value_to_datum(value)?;
2132    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2133        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2134    let mut bytes = Vec::with_capacity(datum.len() + 10);
2135    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2136    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2137    bytes.extend_from_slice(&datum);
2138    Ok(PayloadEnvelope {
2139        codec: DEFAULT_CODEC.to_string(),
2140        blob: BASE64.encode(bytes),
2141    })
2142}
2143
2144pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2145    if envelope.codec != DEFAULT_CODEC {
2146        return Err(unsupported_payload_codec(&envelope.codec));
2147    }
2148    decode_avro_value_blob(&envelope.blob)
2149}
2150
2151pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2152    let blob = match codec {
2153        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2154        other => return Err(unsupported_payload_codec(other)),
2155    };
2156
2157    Ok(PayloadEnvelope {
2158        codec: codec.to_string(),
2159        blob,
2160    })
2161}
2162
2163pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2164    match envelope.codec.as_str() {
2165        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2166        other => Err(unsupported_payload_codec(other)),
2167    }
2168}
2169
2170fn handler_type_error<T>(
2171    handler_kind: HandlerKind,
2172    handler_name: &str,
2173    value_kind: HandlerValueKind,
2174    message: impl Into<String>,
2175) -> Error {
2176    Error::HandlerType {
2177        handler_kind,
2178        handler_name: handler_name.to_string(),
2179        value_kind,
2180        rust_type: type_name::<T>(),
2181        message: message.into(),
2182    }
2183}
2184
2185fn decode_handler_input<T: DeserializeOwned>(
2186    arguments: AvroValue,
2187    handler_kind: HandlerKind,
2188    handler_name: &str,
2189) -> Result<T> {
2190    let argument = match arguments {
2191        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2192            arguments.pop().expect("one typed handler argument")
2193        }
2194        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2195        AvroValue::Array(arguments) => {
2196            return Err(handler_type_error::<T>(
2197                handler_kind,
2198                handler_name,
2199                HandlerValueKind::Input,
2200                format!(
2201                    "typed handlers accept one request value, but the task carried {} arguments",
2202                    arguments.len()
2203                ),
2204            ));
2205        }
2206        argument => argument,
2207    };
2208
2209    argument.deserialize().map_err(|error| {
2210        handler_type_error::<T>(
2211            handler_kind,
2212            handler_name,
2213            HandlerValueKind::Input,
2214            error.to_string(),
2215        )
2216    })
2217}
2218
2219fn encode_handler_result<T: Serialize>(
2220    result: &T,
2221    handler_kind: HandlerKind,
2222    handler_name: &str,
2223) -> Result<AvroValue> {
2224    AvroValue::from_serialize(result).map_err(|error| {
2225        handler_type_error::<T>(
2226            handler_kind,
2227            handler_name,
2228            HandlerValueKind::Result,
2229            error.to_string(),
2230        )
2231    })
2232}
2233
2234fn decode_handler_result<T: DeserializeOwned>(
2235    result: AvroValue,
2236    handler_kind: HandlerKind,
2237    handler_name: &str,
2238) -> Result<T> {
2239    result.deserialize().map_err(|error| {
2240        handler_type_error::<T>(
2241            handler_kind,
2242            handler_name,
2243            HandlerValueKind::Result,
2244            error.to_string(),
2245        )
2246    })
2247}
2248
2249#[cfg(test)]
2250fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2251    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2252}
2253
2254fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2255    validate_payload_codec(fallback_codec)?;
2256
2257    if value.is_null() {
2258        return Ok(Value::Null);
2259    }
2260
2261    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2262        return decode_blob(blob, codec);
2263    }
2264
2265    if let Some(blob) = value.as_str() {
2266        return decode_blob(blob, fallback_codec);
2267    }
2268
2269    Err(untagged_payload_value())
2270}
2271
2272fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2273    let envelope = match codec {
2274        DEFAULT_CODEC => encode_avro_value(value)?,
2275        other => return Err(unsupported_payload_codec(other)),
2276    };
2277    Ok(serde_json::to_value(envelope)?)
2278}
2279
2280fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2281    validate_payload_codec(fallback_codec)?;
2282
2283    if value.is_null() {
2284        return Ok(AvroValue::Null);
2285    }
2286
2287    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2288        validate_payload_codec(codec)?;
2289        return decode_avro_value_blob(blob);
2290    }
2291
2292    if let Some(blob) = value.as_str() {
2293        return match fallback_codec {
2294            DEFAULT_CODEC => decode_avro_value_blob(blob),
2295            other => Err(unsupported_payload_codec(other)),
2296        };
2297    }
2298
2299    Err(untagged_payload_value())
2300}
2301
2302fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2303    match value {
2304        AvroValue::Null => AvroValue::Array(Vec::new()),
2305        AvroValue::Array(_) => value,
2306        other => AvroValue::Array(vec![other]),
2307    }
2308}
2309
2310fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2311    match codec {
2312        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2313        other => Err(unsupported_payload_codec(other)),
2314    }
2315}
2316
2317fn validate_payload_codec(codec: &str) -> Result<()> {
2318    match codec {
2319        DEFAULT_CODEC => Ok(()),
2320        MISSING_TASK_PAYLOAD_CODEC => {
2321            Err(invalid_task_payload_codec("task payload_codec is missing"))
2322        }
2323        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2324        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2325            "task payload_codec must be a string",
2326        )),
2327        other => Err(unsupported_payload_codec(other)),
2328    }
2329}
2330
2331fn invalid_task_payload_codec(reason: &str) -> Error {
2332    Error::Codec(format!(
2333        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2334    ))
2335}
2336
2337fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2338    let Some(object) = value.as_object() else {
2339        return Ok(None);
2340    };
2341    if !object.contains_key("codec") && !object.contains_key("blob") {
2342        return Ok(None);
2343    }
2344
2345    let codec = object
2346        .get("codec")
2347        .and_then(Value::as_str)
2348        .ok_or_else(invalid_payload_envelope)?;
2349    validate_payload_codec(codec)?;
2350    let blob = object
2351        .get("blob")
2352        .and_then(Value::as_str)
2353        .ok_or_else(invalid_payload_envelope)?;
2354    Ok(Some((codec, blob)))
2355}
2356
2357fn invalid_payload_envelope() -> Error {
2358    Error::Codec(
2359        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2360            .to_string(),
2361    )
2362}
2363
2364fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2365    for command in commands {
2366        let Some(command) = command.as_object() else {
2367            continue;
2368        };
2369        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2370            continue;
2371        };
2372        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2373            continue;
2374        };
2375
2376        if let Some(codec) = command.get("payload_codec") {
2377            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2378            validate_payload_codec(codec)?;
2379        }
2380
2381        let payload = command
2382            .get(payload_field)
2383            .ok_or_else(invalid_payload_envelope)?;
2384        if runtime_payloads::Reference::parse(payload)?.is_none() {
2385            validate_outbound_payload_envelope(payload)?;
2386        }
2387    }
2388    Ok(())
2389}
2390
2391fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2392    if commands.iter().any(|command| {
2393        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2394            && command
2395                .get("condition_wait_occurrence_id")
2396                .and_then(Value::as_str)
2397                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2398    }) {
2399        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2400    } else if commands.iter().any(|command| {
2401        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2402            && command.get("attribute_types").is_some()
2403    }) {
2404        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2405    } else if commands
2406        .iter()
2407        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2408    {
2409        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2410    } else if commands
2411        .iter()
2412        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2413    {
2414        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2415    } else if commands.iter().any(|command| {
2416        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2417    }) {
2418        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2419    } else {
2420        WORKER_PROTOCOL_VERSION
2421    }
2422}
2423
2424fn workflow_completion_protocol_version_with_message_streams(
2425    commands: &[Value],
2426    has_message_stream_metadata: bool,
2427) -> &'static str {
2428    let command_protocol = workflow_completion_protocol_version(commands);
2429    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2430        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2431    } else {
2432        command_protocol
2433    }
2434}
2435
2436fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2437    match command_type {
2438        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2439        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2440        "start_service_operation" => Some("request_payload"),
2441        "upsert_memo" => Some("entries"),
2442        _ => None,
2443    }
2444}
2445
2446fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2447    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2448        return Err(untagged_payload_value());
2449    };
2450    validate_payload_codec(codec)?;
2451    decode_avro_value_blob(blob)?;
2452    Ok(())
2453}
2454
2455fn unsupported_payload_codec(codec: &str) -> Error {
2456    Error::Codec(format!(
2457        "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"
2458    ))
2459}
2460
2461fn untagged_payload_value() -> Error {
2462    Error::Codec(
2463        "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"
2464            .to_string(),
2465    )
2466}
2467
2468fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2469    let bytes = BASE64.decode(blob).map_err(|err| {
2470        Error::Codec(format!(
2471            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2472        ))
2473    })?;
2474
2475    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2476        return Err(unsupported_payload_codec("json"));
2477    }
2478
2479    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2480        return Err(Error::Codec(
2481            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2482        ));
2483    }
2484
2485    let fingerprint: [u8; 8] = bytes[2..10]
2486        .try_into()
2487        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2488    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2489        return Err(Error::Codec(format!(
2490            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2491            fingerprint
2492                .iter()
2493                .map(|byte| format!("{byte:02x}"))
2494                .collect::<String>()
2495        )));
2496    }
2497
2498    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2499    // The current fingerprint selects the current immutable schema, so reader
2500    // resolution would only re-walk the same recursive union. Future retained
2501    // writer fingerprints supply a distinct reader schema in this branch.
2502    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2503    if datum_reader.truncated {
2504        return Err(Error::Codec(
2505            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2506        ));
2507    }
2508    let datum = datum.map_err(|err| {
2509        Error::Codec(format!(
2510            "invalid_payload_framing: malformed Avro Value datum: {err}"
2511        ))
2512    })?;
2513    if datum_reader.remaining() != 0 {
2514        return Err(Error::Codec(format!(
2515            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2516            datum_reader.remaining()
2517        )));
2518    }
2519    avro_value_from_datum(datum)
2520}
2521
2522struct StrictAvroDatumReader<'a> {
2523    bytes: &'a [u8],
2524    offset: usize,
2525    truncated: bool,
2526}
2527
2528impl<'a> StrictAvroDatumReader<'a> {
2529    fn new(bytes: &'a [u8]) -> Self {
2530        Self {
2531            bytes,
2532            offset: 0,
2533            truncated: false,
2534        }
2535    }
2536
2537    fn remaining(&self) -> usize {
2538        self.bytes.len() - self.offset
2539    }
2540}
2541
2542impl Read for StrictAvroDatumReader<'_> {
2543    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2544        let count = buffer.len().min(self.remaining());
2545        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2546        self.offset += count;
2547        if count < buffer.len() {
2548            self.truncated = true;
2549        }
2550
2551        Ok(count)
2552    }
2553}
2554
2555fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2556    let branch = match value {
2557        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2558        AvroValue::Boolean(value) => AvroDatum::Union(
2559            1,
2560            Box::new(AvroDatum::Record(vec![(
2561                "boolean".to_string(),
2562                AvroDatum::Boolean(*value),
2563            )])),
2564        ),
2565        AvroValue::Long(value) => AvroDatum::Union(
2566            2,
2567            Box::new(AvroDatum::Record(vec![(
2568                "long".to_string(),
2569                AvroDatum::Long(*value),
2570            )])),
2571        ),
2572        AvroValue::Double(value) => {
2573            if !value.is_finite() {
2574                return Err(Error::Codec(
2575                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2576                ));
2577            }
2578            AvroDatum::Union(
2579                3,
2580                Box::new(AvroDatum::Record(vec![(
2581                    "double".to_string(),
2582                    AvroDatum::Double(*value),
2583                )])),
2584            )
2585        }
2586        AvroValue::Bytes(value) => AvroDatum::Union(
2587            4,
2588            Box::new(AvroDatum::Record(vec![(
2589                "bytes".to_string(),
2590                AvroDatum::Bytes(value.clone()),
2591            )])),
2592        ),
2593        AvroValue::String(value) => AvroDatum::Union(
2594            5,
2595            Box::new(AvroDatum::Record(vec![(
2596                "string".to_string(),
2597                AvroDatum::String(value.clone()),
2598            )])),
2599        ),
2600        AvroValue::Array(values) => AvroDatum::Union(
2601            6,
2602            Box::new(AvroDatum::Record(vec![(
2603                "items".to_string(),
2604                AvroDatum::Array(
2605                    values
2606                        .iter()
2607                        .map(avro_value_to_datum)
2608                        .collect::<Result<Vec<_>>>()?,
2609                ),
2610            )])),
2611        ),
2612        AvroValue::Map(values) => AvroDatum::Union(
2613            7,
2614            Box::new(AvroDatum::Record(vec![(
2615                "entries".to_string(),
2616                AvroDatum::Array(
2617                    values
2618                        .iter()
2619                        .map(|(key, value)| {
2620                            Ok(AvroDatum::Record(vec![
2621                                ("key".to_string(), AvroDatum::String(key.clone())),
2622                                ("value".to_string(), avro_value_to_datum(value)?),
2623                            ]))
2624                        })
2625                        .collect::<Result<Vec<_>>>()?,
2626                ),
2627            )])),
2628        ),
2629    };
2630    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2631}
2632
2633fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2634    let AvroDatum::Record(mut outer) = datum else {
2635        return Err(Error::Codec(
2636            "invalid_payload_framing: datum is not a Value record".to_string(),
2637        ));
2638    };
2639    let (_, branch) = outer
2640        .pop()
2641        .filter(|(name, _)| name == "value")
2642        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2643    let AvroDatum::Union(_, branch) = branch else {
2644        return Err(Error::Codec(
2645            "invalid_payload_framing: invalid Value union".to_string(),
2646        ));
2647    };
2648    match *branch {
2649        AvroDatum::Null => Ok(AvroValue::Null),
2650        AvroDatum::Record(mut fields) => {
2651            let (name, value) = fields.pop().ok_or_else(|| {
2652                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2653            })?;
2654            match (name.as_str(), value) {
2655                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2656                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2657                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2658                    Ok(AvroValue::Double(value))
2659                }
2660                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2661                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2662                ("items", AvroDatum::Array(values)) => values
2663                    .into_iter()
2664                    .map(avro_value_from_datum)
2665                    .collect::<Result<Vec<_>>>()
2666                    .map(AvroValue::Array),
2667                ("entries", AvroDatum::Map(values)) => values
2668                    .into_iter()
2669                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2670                    .collect::<Result<BTreeMap<_, _>>>()
2671                    .map(AvroValue::Map),
2672                _ => Err(Error::Codec(
2673                    "invalid_payload_framing: unknown Value branch".to_string(),
2674                )),
2675            }
2676        }
2677        _ => Err(Error::Codec(
2678            "invalid_payload_framing: invalid Value branch".to_string(),
2679        )),
2680    }
2681}
2682
2683fn avro_value_schema() -> Result<&'static Schema> {
2684    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2685        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2686            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2687    }) {
2688        Ok(schema) => Ok(schema),
2689        Err(message) => Err(Error::Codec(message.clone())),
2690    }
2691}
2692
2693fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2694    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2695        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2696        // have the same block representation when each ordered array record
2697        // contains the map key followed by its value, so this encoding-only
2698        // adaptation lets the official encoder retain BTreeMap wire order.
2699        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2700            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2701        let entries_schema = schema
2702            .pointer_mut("/fields/0/type/7/fields/0/type")
2703            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2704        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2705            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2706        }
2707        *entries_schema = json!({
2708            "type": "array",
2709            "items": {
2710                "type": "record",
2711                "name": "MapEntry",
2712                "fields": [
2713                    {"name": "key", "type": "string"},
2714                    {"name": "value", "type": "Value"}
2715                ]
2716            }
2717        });
2718        Schema::parse_str(&schema.to_string())
2719            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2720    }) {
2721        Ok(schema) => Ok(schema),
2722        Err(message) => Err(Error::Codec(message.clone())),
2723    }
2724}
2725
2726#[derive(Clone, Debug)]
2727pub struct Client {
2728    http: reqwest::Client,
2729    base_url: String,
2730    token: Option<String>,
2731    control_token: Option<String>,
2732    worker_token: Option<String>,
2733    namespace: String,
2734    max_external_payload_bytes: usize,
2735    worker_storage_admission: Option<WorkerStorageAdmission>,
2736    cooperative_worker_protocol: bool,
2737    local_activities_enabled: bool,
2738    worker_sessions_enabled: bool,
2739    max_concurrent_worker_sessions: usize,
2740    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2741}
2742
2743impl Client {
2744    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2745        Self::builder(base_url).build()
2746    }
2747
2748    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2749        ClientBuilder {
2750            base_url: base_url.into(),
2751            token: None,
2752            control_token: None,
2753            worker_token: None,
2754            namespace: "default".to_string(),
2755            timeout: Duration::from_secs(60),
2756            max_external_payload_bytes: 64 * 1024 * 1024,
2757        }
2758    }
2759
2760    pub async fn health(&self) -> Result<Value> {
2761        self.request_json(
2762            reqwest::Method::GET,
2763            "/health",
2764            RequestProtocol::ControlPlane,
2765            Option::<&Value>::None,
2766        )
2767        .await
2768    }
2769
2770    pub async fn cluster_info(&self) -> Result<Value> {
2771        self.request_json(
2772            reqwest::Method::GET,
2773            "/cluster/info",
2774            RequestProtocol::ControlPlane,
2775            Option::<&Value>::None,
2776        )
2777        .await
2778    }
2779
2780    pub async fn start_workflow<T: Serialize>(
2781        &self,
2782        workflow_type: &str,
2783        task_queue: &str,
2784        workflow_id: &str,
2785        input: T,
2786    ) -> Result<WorkflowHandle> {
2787        self.start_workflow_with_options(
2788            workflow_type,
2789            task_queue,
2790            workflow_id,
2791            WorkflowStartOptions::default(),
2792            input,
2793        )
2794        .await
2795    }
2796
2797    /// Start a workflow with explicit server-enforced execution and run
2798    /// deadlines.
2799    pub async fn start_workflow_with_options<T: Serialize>(
2800        &self,
2801        workflow_type: &str,
2802        task_queue: &str,
2803        workflow_id: &str,
2804        options: WorkflowStartOptions,
2805        input: T,
2806    ) -> Result<WorkflowHandle> {
2807        options.validate()?;
2808        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2809        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2810        let body = json!({
2811            "workflow_id": workflow_id,
2812            "workflow_type": workflow_type,
2813            "task_queue": task_queue,
2814            "input": input_envelope,
2815            "execution_timeout_seconds": options.execution_timeout_seconds,
2816            "run_timeout_seconds": options.run_timeout_seconds
2817        });
2818
2819        let data: Value = self
2820            .request_json(
2821                reqwest::Method::POST,
2822                "/workflows",
2823                RequestProtocol::ControlPlane,
2824                Some(&body),
2825            )
2826            .await?;
2827
2828        Ok(WorkflowHandle {
2829            client: self.clone(),
2830            workflow_id: data
2831                .get("workflow_id")
2832                .and_then(Value::as_str)
2833                .unwrap_or(workflow_id)
2834                .to_string(),
2835            run_id: data
2836                .get("run_id")
2837                .and_then(Value::as_str)
2838                .map(str::to_string),
2839            workflow_type: data
2840                .get("workflow_type")
2841                .and_then(Value::as_str)
2842                .unwrap_or(workflow_type)
2843                .to_string(),
2844        })
2845    }
2846
2847    pub async fn signal_workflow<T: Serialize>(
2848        &self,
2849        workflow_id: &str,
2850        signal_name: &str,
2851        input: T,
2852    ) -> Result<Value> {
2853        self.signal_workflow_target(workflow_id, None, signal_name, input)
2854            .await
2855    }
2856
2857    /// Append one idempotently identified item to an instance-scoped input stream.
2858    pub async fn append_message_stream<T: Serialize>(
2859        &self,
2860        workflow_id: &str,
2861        stream_name: &str,
2862        message_id: &str,
2863        input: T,
2864    ) -> Result<Value> {
2865        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2866        let body = json!({
2867            "message_id": message_id,
2868            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2869        });
2870        self.request_json(
2871            reqwest::Method::POST,
2872            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2873            RequestProtocol::ControlPlane,
2874            Some(&body),
2875        )
2876        .await
2877    }
2878
2879    /// Signal only if `run_id` is still the current run for this instance.
2880    pub async fn signal_workflow_run<T: Serialize>(
2881        &self,
2882        workflow_id: &str,
2883        run_id: &str,
2884        signal_name: &str,
2885        input: T,
2886    ) -> Result<Value> {
2887        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2888            .await
2889    }
2890
2891    async fn signal_workflow_target<T: Serialize>(
2892        &self,
2893        workflow_id: &str,
2894        run_id: Option<&str>,
2895        signal_name: &str,
2896        input: T,
2897    ) -> Result<Value> {
2898        validate_user_signal_name(signal_name)?;
2899        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2900        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2901        let body = json!({
2902            "input": input_envelope
2903        });
2904        let path = match run_id {
2905            Some(run_id) => {
2906                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
2907            }
2908            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
2909        };
2910        self.request_json(
2911            reqwest::Method::POST,
2912            &path,
2913            RequestProtocol::ControlPlane,
2914            Some(&body),
2915        )
2916        .await
2917    }
2918
2919    /// Close the current run as cancelled immediately.
2920    ///
2921    /// Server revokes open tasks and timers without resuming workflow code for
2922    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
2923    /// request on a supporting runtime and opted-in worker.
2924    pub async fn cancel_workflow(
2925        &self,
2926        workflow_id: &str,
2927        options: WorkflowCommandOptions,
2928    ) -> Result<WorkflowCommandResult> {
2929        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
2930            .await
2931    }
2932
2933    /// Close the selected run as cancelled, only if `run_id` is still current.
2934    pub async fn cancel_workflow_run(
2935        &self,
2936        workflow_id: &str,
2937        run_id: &str,
2938        options: WorkflowCommandOptions,
2939    ) -> Result<WorkflowCommandResult> {
2940        self.workflow_command(
2941            workflow_id,
2942            Some(run_id),
2943            WorkflowCommandKind::Cancel,
2944            options,
2945        )
2946        .await
2947    }
2948
2949    /// Forcefully terminate the current run for an instance.
2950    pub async fn terminate_workflow(
2951        &self,
2952        workflow_id: &str,
2953        options: WorkflowCommandOptions,
2954    ) -> Result<WorkflowCommandResult> {
2955        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
2956            .await
2957    }
2958
2959    /// Forcefully terminate only if `run_id` is still current.
2960    pub async fn terminate_workflow_run(
2961        &self,
2962        workflow_id: &str,
2963        run_id: &str,
2964        options: WorkflowCommandOptions,
2965    ) -> Result<WorkflowCommandResult> {
2966        self.workflow_command(
2967            workflow_id,
2968            Some(run_id),
2969            WorkflowCommandKind::Terminate,
2970            options,
2971        )
2972        .await
2973    }
2974
2975    /// Continue a failed run from its recorded activity failure boundary.
2976    pub async fn redrive_workflow_run(
2977        &self,
2978        workflow_id: &str,
2979        failed_run_id: &str,
2980        request_id: Option<&str>,
2981    ) -> Result<WorkflowRedriveResult> {
2982        let body = request_id
2983            .map(|id| json!({"request_id": id}))
2984            .unwrap_or_else(|| json!({}));
2985        let data: Value = self
2986            .request_json(
2987                reqwest::Method::POST,
2988                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
2989                RequestProtocol::ControlPlane,
2990                Some(&body),
2991            )
2992            .await?;
2993        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
2994            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
2995        {
2996            return Err(Error::Codec(
2997                "redrive response was not accepted".to_string(),
2998            ));
2999        }
3000        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3001            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3002        {
3003            return Err(Error::Codec(
3004                "redrive response does not match the requested source run".to_string(),
3005            ));
3006        }
3007        let run_id = data
3008            .get("run_id")
3009            .and_then(Value::as_str)
3010            .filter(|id| !id.is_empty() && *id != failed_run_id)
3011            .ok_or_else(|| {
3012                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3013            })?;
3014        let resume_step_sequence = data
3015            .get("resume_step_sequence")
3016            .and_then(Value::as_u64)
3017            .filter(|sequence| *sequence > 0)
3018            .ok_or_else(|| {
3019                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3020            })?;
3021        Ok(WorkflowRedriveResult {
3022            workflow_id: workflow_id.to_string(),
3023            source_run_id: failed_run_id.to_string(),
3024            run_id: run_id.to_string(),
3025            resume_step_sequence,
3026            raw: data,
3027        })
3028    }
3029
3030    async fn workflow_command(
3031        &self,
3032        workflow_id: &str,
3033        run_id: Option<&str>,
3034        command: WorkflowCommandKind,
3035        options: WorkflowCommandOptions,
3036    ) -> Result<WorkflowCommandResult> {
3037        let path = match run_id {
3038            Some(run_id) => format!(
3039                "/workflows/{workflow_id}/runs/{run_id}/{}",
3040                command.as_str()
3041            ),
3042            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3043        };
3044        let data = match self
3045            .request_json(
3046                reqwest::Method::POST,
3047                &path,
3048                RequestProtocol::ControlPlane,
3049                Some(&options),
3050            )
3051            .await
3052        {
3053            Ok(data) => data,
3054            Err(Error::Http { status, body }) => {
3055                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3056                    command,
3057                    status,
3058                    body,
3059                    workflow_id,
3060                    run_id,
3061                )));
3062            }
3063            Err(error) => return Err(error),
3064        };
3065
3066        Ok(workflow_command_result(command, data, workflow_id, run_id))
3067    }
3068
3069    /// Execute a named, read-only query against a running or completed workflow.
3070    ///
3071    /// Arguments and results use the platform payload envelope. Server and
3072    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3073    /// reason, HTTP status, and original response body.
3074    pub async fn query_workflow<T: Serialize>(
3075        &self,
3076        workflow_id: &str,
3077        query_name: &str,
3078        input: T,
3079    ) -> Result<Value> {
3080        self.query_workflow_target(workflow_id, None, query_name, input)
3081            .await
3082    }
3083
3084    /// Query only if `run_id` is still current, preventing accidental retargeting.
3085    pub async fn query_workflow_run<T: Serialize>(
3086        &self,
3087        workflow_id: &str,
3088        run_id: &str,
3089        query_name: &str,
3090        input: T,
3091    ) -> Result<Value> {
3092        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3093            .await
3094    }
3095
3096    /// Query a workflow and return the lossless fixed Avro Value result.
3097    pub async fn query_workflow_avro_value<T: Serialize>(
3098        &self,
3099        workflow_id: &str,
3100        query_name: &str,
3101        input: T,
3102    ) -> Result<AvroValue> {
3103        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3104            .await
3105    }
3106
3107    /// Query a selected run and return the lossless fixed Avro Value result.
3108    pub async fn query_workflow_run_avro_value<T: Serialize>(
3109        &self,
3110        workflow_id: &str,
3111        run_id: &str,
3112        query_name: &str,
3113        input: T,
3114    ) -> Result<AvroValue> {
3115        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3116            .await
3117    }
3118
3119    async fn query_workflow_avro_value_target<T: Serialize>(
3120        &self,
3121        workflow_id: &str,
3122        run_id: Option<&str>,
3123        query_name: &str,
3124        input: T,
3125    ) -> Result<AvroValue> {
3126        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3127        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3128        let path = match run_id {
3129            Some(run_id) => {
3130                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3131            }
3132            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3133        };
3134        let response: Value = match self
3135            .request_json(
3136                reqwest::Method::POST,
3137                &path,
3138                RequestProtocol::ControlPlane,
3139                Some(&body),
3140            )
3141            .await
3142        {
3143            Ok(response) => response,
3144            Err(Error::Http { status, body }) => {
3145                return Err(Error::QueryFailed(query_failure(status, body)));
3146            }
3147            Err(error) => return Err(error),
3148        };
3149
3150        let envelope = response
3151            .get("result_envelope")
3152            .filter(|envelope| !envelope.is_null())
3153            .ok_or_else(|| {
3154                Error::Codec(
3155                    "missing_payload_envelope: typed query result requires result_envelope"
3156                        .to_string(),
3157                )
3158            })?;
3159        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3160    }
3161
3162    async fn query_workflow_target<T: Serialize>(
3163        &self,
3164        workflow_id: &str,
3165        run_id: Option<&str>,
3166        query_name: &str,
3167        input: T,
3168    ) -> Result<Value> {
3169        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3170        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3171        let body = json!({
3172            "input": input_envelope
3173        });
3174        let path = match run_id {
3175            Some(run_id) => {
3176                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3177            }
3178            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3179        };
3180        let response: Value = match self
3181            .request_json(
3182                reqwest::Method::POST,
3183                &path,
3184                RequestProtocol::ControlPlane,
3185                Some(&body),
3186            )
3187            .await
3188        {
3189            Ok(response) => response,
3190            Err(Error::Http { status, body }) => {
3191                return Err(Error::QueryFailed(query_failure(status, body)));
3192            }
3193            Err(error) => return Err(error),
3194        };
3195
3196        if let Some(envelope) = response
3197            .get("result_envelope")
3198            .filter(|envelope| !envelope.is_null())
3199        {
3200            return decode_wire_value(envelope, DEFAULT_CODEC);
3201        }
3202
3203        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3204    }
3205
3206    /// Send a synchronous update using fixed Avro Value arguments.
3207    pub async fn update_workflow<T: Serialize>(
3208        &self,
3209        workflow_id: &str,
3210        update_name: &str,
3211        input: T,
3212        request_id: Option<&str>,
3213    ) -> Result<Value> {
3214        let response = self
3215            .update_workflow_response(workflow_id, update_name, input, request_id)
3216            .await?;
3217        if let Some(envelope) = response
3218            .get("result_envelope")
3219            .filter(|envelope| !envelope.is_null())
3220        {
3221            return decode_wire_value(envelope, DEFAULT_CODEC);
3222        }
3223        Ok(response.get("result").cloned().unwrap_or(response))
3224    }
3225
3226    /// Send a synchronous update and retain a bytes-capable Avro result.
3227    pub async fn update_workflow_avro_value<T: Serialize>(
3228        &self,
3229        workflow_id: &str,
3230        update_name: &str,
3231        input: T,
3232        request_id: Option<&str>,
3233    ) -> Result<AvroValue> {
3234        let response = self
3235            .update_workflow_response(workflow_id, update_name, input, request_id)
3236            .await?;
3237        let envelope = response
3238            .get("result_envelope")
3239            .filter(|envelope| !envelope.is_null())
3240            .ok_or_else(|| {
3241                Error::Codec(
3242                    "missing_payload_envelope: typed update result requires result_envelope"
3243                        .to_string(),
3244                )
3245            })?;
3246        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3247    }
3248
3249    async fn update_workflow_response<T: Serialize>(
3250        &self,
3251        workflow_id: &str,
3252        update_name: &str,
3253        input: T,
3254        request_id: Option<&str>,
3255    ) -> Result<Value> {
3256        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3257        let mut body = json!({
3258            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3259            "wait_for": "completed",
3260        });
3261        if let Some(request_id) = request_id {
3262            body["request_id"] = json!(request_id);
3263        }
3264        self.request_json(
3265            reqwest::Method::POST,
3266            &format!("/workflows/{workflow_id}/update/{update_name}"),
3267            RequestProtocol::ControlPlane,
3268            Some(&body),
3269        )
3270        .await
3271    }
3272
3273    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3274        let path = format!("/workflows/{workflow_id}");
3275        let mut data: WorkflowDescription = self
3276            .request_json(
3277                reqwest::Method::GET,
3278                &path,
3279                RequestProtocol::ControlPlane,
3280                Option::<&Value>::None,
3281            )
3282            .await?;
3283        data.decode_payloads()?;
3284        Ok(data)
3285    }
3286
3287    /// Describe one selected run, including historical terminal runs.
3288    pub async fn describe_workflow_run(
3289        &self,
3290        workflow_id: &str,
3291        run_id: &str,
3292    ) -> Result<WorkflowDescription> {
3293        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3294        let mut data: WorkflowDescription = self
3295            .request_json(
3296                reqwest::Method::GET,
3297                &path,
3298                RequestProtocol::ControlPlane,
3299                Option::<&Value>::None,
3300            )
3301            .await?;
3302        data.decode_payloads()?;
3303        Ok(data)
3304    }
3305
3306    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3307        let mut path = format!(
3308            "/workflows/{}/runs/{}/streams",
3309            percent_encode_path_segment(workflow_id),
3310            percent_encode_path_segment(run_id),
3311        );
3312        if let Some(stream_name) = stream_name {
3313            path.push('/');
3314            path.push_str(&percent_encode_path_segment(stream_name));
3315        }
3316        path
3317    }
3318
3319    /// List the run-scoped output streams already opened by a workflow.
3320    pub async fn list_workflow_streams(
3321        &self,
3322        workflow_id: &str,
3323        run_id: &str,
3324    ) -> Result<Vec<WorkflowStreamDescription>> {
3325        let response: WorkflowStreamListResponse = self
3326            .request_json(
3327                reqwest::Method::GET,
3328                &Self::workflow_stream_path(workflow_id, run_id, None),
3329                RequestProtocol::ControlPlane,
3330                Option::<&Value>::None,
3331            )
3332            .await?;
3333        Ok(response.streams)
3334    }
3335
3336    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3337    pub async fn describe_workflow_stream(
3338        &self,
3339        workflow_id: &str,
3340        run_id: &str,
3341        stream_name: &str,
3342    ) -> Result<WorkflowStreamDescription> {
3343        let response: WorkflowStreamDescriptionResponse = self
3344            .request_json(
3345                reqwest::Method::GET,
3346                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3347                RequestProtocol::ControlPlane,
3348                Option::<&Value>::None,
3349            )
3350            .await?;
3351        Ok(response.stream)
3352    }
3353
3354    /// Read one bounded page beginning at a zero-based offset.
3355    ///
3356    /// Delivery is at least once: persist `next_offset` only after processing
3357    /// the page. The future is cancellation-safe; dropping it cancels the
3358    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3359    /// service contract.
3360    pub async fn subscribe_workflow_stream(
3361        &self,
3362        workflow_id: &str,
3363        run_id: &str,
3364        stream_name: &str,
3365        from_offset: u64,
3366        max_items: usize,
3367        wait: Duration,
3368    ) -> Result<WorkflowStreamPage> {
3369        let max_items = max_items.clamp(1, 500);
3370        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3371        let path = format!(
3372            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3373            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3374        );
3375        let response: WorkflowStreamPageResponse = self
3376            .request_json_with_timeout(
3377                reqwest::Method::GET,
3378                &path,
3379                RequestProtocol::ControlPlane,
3380                Option::<&Value>::None,
3381                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3382            )
3383            .await?;
3384
3385        let items = response
3386            .items
3387            .into_iter()
3388            .map(|raw| {
3389                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3390                let envelope = raw.get("payload").cloned();
3391                let payload = envelope
3392                    .as_ref()
3393                    .filter(|value| value.get("blob").is_some())
3394                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3395                    .transpose()?
3396                    .map(AvroValue::into_json)
3397                    .transpose()?;
3398                Ok(WorkflowStreamItem {
3399                    offset,
3400                    payload,
3401                    payload_envelope: envelope,
3402                    payload_reference: raw
3403                        .get("payload_reference")
3404                        .and_then(Value::as_str)
3405                        .map(str::to_string),
3406                    payload_codec: raw
3407                        .get("payload_codec")
3408                        .and_then(Value::as_str)
3409                        .map(str::to_string),
3410                    idempotency_key: raw
3411                        .get("idempotency_key")
3412                        .and_then(Value::as_str)
3413                        .map(str::to_string),
3414                    item_type: raw
3415                        .get("item_type")
3416                        .and_then(Value::as_str)
3417                        .map(str::to_string),
3418                    content_type: raw
3419                        .get("content_type")
3420                        .and_then(Value::as_str)
3421                        .map(str::to_string),
3422                    origin: raw
3423                        .get("origin")
3424                        .and_then(Value::as_str)
3425                        .map(str::to_string),
3426                    origin_reference: raw
3427                        .get("origin_reference")
3428                        .and_then(Value::as_str)
3429                        .map(str::to_string),
3430                    emitted_at: raw
3431                        .get("emitted_at")
3432                        .and_then(Value::as_str)
3433                        .map(str::to_string),
3434                    raw,
3435                })
3436            })
3437            .collect::<Result<Vec<_>>>()?;
3438        Ok(WorkflowStreamPage {
3439            stream: response.stream,
3440            items,
3441            next_offset: response.next_offset,
3442            terminal: response.terminal,
3443        })
3444    }
3445
3446    /// Append inline Avro envelopes or opaque external payload references.
3447    pub async fn append_workflow_stream(
3448        &self,
3449        workflow_id: &str,
3450        run_id: &str,
3451        stream_name: &str,
3452        items: &[WorkflowStreamAppendItem],
3453        max_pending_items: Option<u64>,
3454    ) -> Result<WorkflowStreamAppendResult> {
3455        if items.is_empty() {
3456            return Err(Error::Codec(
3457                "workflow_stream_items_empty: append requires at least one item".to_string(),
3458            ));
3459        }
3460        let mut body = json!({
3461            "items": items
3462                .iter()
3463                .map(|item| item.wire_value(None))
3464                .collect::<Vec<_>>(),
3465        });
3466        if let Some(max_pending_items) = max_pending_items {
3467            if max_pending_items == 0 {
3468                return Err(Error::Codec(
3469                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3470                        .to_string(),
3471                ));
3472            }
3473            body["max_pending_items"] = json!(max_pending_items);
3474        }
3475        let response: WorkflowStreamAppendResponse = self
3476            .request_json(
3477                reqwest::Method::POST,
3478                &format!(
3479                    "{}/items",
3480                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3481                ),
3482                RequestProtocol::ControlPlane,
3483                Some(&body),
3484            )
3485            .await?;
3486        Ok(WorkflowStreamAppendResult {
3487            stream: response.stream,
3488            accepted_offsets: response.accepted_offsets,
3489            accepted: response.accepted,
3490            deduped: response.deduped,
3491        })
3492    }
3493
3494    /// Close a stream, or mark it errored when `error_reason` is supplied.
3495    pub async fn close_workflow_stream(
3496        &self,
3497        workflow_id: &str,
3498        run_id: &str,
3499        stream_name: &str,
3500        error_reason: Option<&str>,
3501        retention_seconds: Option<u64>,
3502    ) -> Result<WorkflowStreamDescription> {
3503        let mut body = json!({});
3504        if let Some(error_reason) = error_reason {
3505            body["error_reason"] = json!(error_reason);
3506        }
3507        if let Some(retention_seconds) = retention_seconds {
3508            if retention_seconds == 0 {
3509                return Err(Error::Codec(
3510                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3511                        .to_string(),
3512                ));
3513            }
3514            body["retention_seconds"] = json!(retention_seconds);
3515        }
3516        let response: WorkflowStreamDescriptionResponse = self
3517            .request_json(
3518                reqwest::Method::POST,
3519                &format!(
3520                    "{}/close",
3521                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3522                ),
3523                RequestProtocol::ControlPlane,
3524                Some(&body),
3525            )
3526            .await?;
3527        Ok(response.stream)
3528    }
3529
3530    pub async fn register_worker(
3531        &self,
3532        worker_id: &str,
3533        task_queue: &str,
3534        supported_workflow_types: Vec<String>,
3535        supported_activity_types: Vec<String>,
3536        max_concurrent_workflow_tasks: usize,
3537        max_concurrent_activity_tasks: usize,
3538    ) -> Result<RegisterWorkerResponse> {
3539        self.register_worker_with_capabilities(
3540            worker_id,
3541            task_queue,
3542            supported_workflow_types,
3543            supported_activity_types,
3544            max_concurrent_workflow_tasks,
3545            max_concurrent_activity_tasks,
3546            Vec::new(),
3547        )
3548        .await
3549    }
3550
3551    /// Register a worker and explicitly advertise additive worker capabilities.
3552    pub async fn register_worker_with_capabilities(
3553        &self,
3554        worker_id: &str,
3555        task_queue: &str,
3556        supported_workflow_types: Vec<String>,
3557        supported_activity_types: Vec<String>,
3558        max_concurrent_workflow_tasks: usize,
3559        max_concurrent_activity_tasks: usize,
3560        capabilities: Vec<String>,
3561    ) -> Result<RegisterWorkerResponse> {
3562        self.register_worker_with_command_contracts(
3563            worker_id,
3564            task_queue,
3565            supported_workflow_types,
3566            supported_activity_types,
3567            max_concurrent_workflow_tasks,
3568            max_concurrent_activity_tasks,
3569            capabilities,
3570            Value::Object(serde_json::Map::new()),
3571        )
3572        .await
3573    }
3574
3575    /// Register a worker and advertise its named query and update handlers.
3576    ///
3577    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3578    /// so a workflow contract with a non-empty or malformed
3579    /// `update_validators` declaration returns
3580    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3581    #[allow(clippy::too_many_arguments)]
3582    pub async fn register_worker_with_command_contracts(
3583        &self,
3584        worker_id: &str,
3585        task_queue: &str,
3586        supported_workflow_types: Vec<String>,
3587        supported_activity_types: Vec<String>,
3588        max_concurrent_workflow_tasks: usize,
3589        max_concurrent_activity_tasks: usize,
3590        capabilities: Vec<String>,
3591        workflow_command_contracts: Value,
3592    ) -> Result<RegisterWorkerResponse> {
3593        self.register_worker_with_definition_fingerprints(
3594            worker_id,
3595            task_queue,
3596            supported_workflow_types,
3597            supported_activity_types,
3598            max_concurrent_workflow_tasks,
3599            max_concurrent_activity_tasks,
3600            capabilities,
3601            workflow_command_contracts,
3602            None,
3603        )
3604        .await
3605    }
3606
3607    #[allow(clippy::too_many_arguments)]
3608    async fn register_worker_with_definition_fingerprints(
3609        &self,
3610        worker_id: &str,
3611        task_queue: &str,
3612        supported_workflow_types: Vec<String>,
3613        supported_activity_types: Vec<String>,
3614        max_concurrent_workflow_tasks: usize,
3615        max_concurrent_activity_tasks: usize,
3616        capabilities: Vec<String>,
3617        workflow_command_contracts: Value,
3618        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3619    ) -> Result<RegisterWorkerResponse> {
3620        if let Some(contracts) = workflow_command_contracts.as_object() {
3621            for (workflow_type, contract) in contracts {
3622                let Some(update_validators) = contract.get("update_validators") else {
3623                    continue;
3624                };
3625                if !update_validators
3626                    .as_array()
3627                    .is_some_and(|validators| validators.is_empty())
3628                {
3629                    return Err(Error::UnsupportedUpdateValidators {
3630                        workflow_type: workflow_type.clone(),
3631                    });
3632                }
3633            }
3634        }
3635
3636        let mut body = json!({
3637            "worker_id": worker_id,
3638            "task_queue": task_queue,
3639            "runtime": "rust",
3640            "sdk_version": SDK_VERSION,
3641            "supported_workflow_types": supported_workflow_types,
3642            "supported_activity_types": supported_activity_types,
3643            "capabilities": capabilities,
3644            "capability_manifest": portable_worker_affinity_capability_manifest(),
3645            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3646            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3647        });
3648        if self.local_activities_enabled {
3649            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3650                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3651        }
3652        if self.worker_sessions_enabled {
3653            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3654                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3655            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3656        }
3657        if workflow_command_contracts
3658            .as_object()
3659            .is_some_and(|contracts| !contracts.is_empty())
3660        {
3661            body["workflow_command_contracts"] = workflow_command_contracts;
3662        }
3663        if let Some(fingerprints) = workflow_definition_fingerprints {
3664            body["workflow_definition_fingerprints"] = json!(fingerprints);
3665        }
3666
3667        let response: Value = self
3668            .request_json(
3669                reqwest::Method::POST,
3670                "/worker/register",
3671                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3672                Some(&body),
3673            )
3674            .await?;
3675        if self.local_activities_enabled || self.worker_sessions_enabled {
3676            let compatible = response["registered"].as_bool() == Some(true)
3677                && response["worker_id"].as_str() == Some(worker_id)
3678                && response["namespace"].as_str() == Some(self.namespace.as_str())
3679                && response["task_queue"].as_str() == Some(task_queue)
3680                && response["protocol_version"]
3681                    .as_str()
3682                    .and_then(|version| version.strip_prefix("1."))
3683                    .and_then(|minor| minor.parse::<u64>().ok())
3684                    .is_some_and(|minor| minor >= 18)
3685                && (!self.local_activities_enabled
3686                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3687                        == Some(true))
3688                && (!self.worker_sessions_enabled
3689                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3690                        == Some(true)
3691                        && response["capabilities"].as_array().is_some_and(|accepted| {
3692                            capabilities.iter().all(|capability| {
3693                                accepted
3694                                    .iter()
3695                                    .any(|value| value.as_str() == Some(capability.as_str()))
3696                            })
3697                        })));
3698            if !compatible {
3699                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3700                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3701                } else {
3702                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3703                });
3704                if response["registered"] == true
3705                    && response["worker_id"].as_str() == Some(worker_id)
3706                {
3707                    if let Err(deregistration) =
3708                        self.deregister_worker_registration(worker_id).await
3709                    {
3710                        return Err(Error::WorkerShutdown {
3711                            primary: Box::new(error),
3712                            deregistration: Box::new(deregistration),
3713                        });
3714                    }
3715                }
3716                return Err(error);
3717            }
3718        }
3719        if self.cooperative_worker_protocol {
3720            let compatible = response["registered"].as_bool() == Some(true)
3721                && response["worker_id"].as_str() == Some(worker_id)
3722                && response["namespace"].as_str() == Some(self.namespace.as_str())
3723                && response["task_queue"].as_str() == Some(task_queue)
3724                && response["protocol_version"]
3725                    .as_str()
3726                    .is_some_and(cooperative_cancellation::supports_protocol)
3727                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3728                    == Some(true)
3729                && response["capabilities"].as_array().is_some_and(|accepted| {
3730                    capabilities.iter().all(|capability| {
3731                        accepted
3732                            .iter()
3733                            .any(|value| value.as_str() == Some(capability.as_str()))
3734                    })
3735                });
3736            if !compatible {
3737                let error = Error::CooperativeCancellationUnavailable(
3738                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3739                );
3740                if response["registered"].as_bool() == Some(true)
3741                    && response["worker_id"].as_str() == Some(worker_id)
3742                {
3743                    if let Err(deregistration) =
3744                        self.deregister_worker_registration(worker_id).await
3745                    {
3746                        return Err(Error::WorkerShutdown {
3747                            primary: Box::new(error),
3748                            deregistration: Box::new(deregistration),
3749                        });
3750                    }
3751                }
3752                return Err(error);
3753            }
3754        }
3755        Ok(serde_json::from_value(response)?)
3756    }
3757
3758    /// Gracefully remove one worker's registration through the worker plane.
3759    ///
3760    /// This operation is separate from operator-facing worker management. It
3761    /// uses worker-protocol authentication and returns the server's lease
3762    /// recovery result.
3763    pub async fn deregister_worker_registration(
3764        &self,
3765        worker_id: &str,
3766    ) -> Result<WorkerDeregistrationEnvelope> {
3767        let path = format!(
3768            "/worker/registrations/{}",
3769            percent_encode_path_segment(worker_id)
3770        );
3771        self.request_json(
3772            reqwest::Method::DELETE,
3773            &path,
3774            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3775            Option::<&Value>::None,
3776        )
3777        .await
3778    }
3779
3780    /// Long-poll for an ephemeral, read-only workflow query task.
3781    pub async fn poll_query_task(
3782        &self,
3783        worker_id: &str,
3784        task_queue: &str,
3785        timeout: Duration,
3786    ) -> Result<Option<QueryTask>> {
3787        Ok(self
3788            .poll_query_task_response(worker_id, task_queue, timeout)
3789            .await?
3790            .task)
3791    }
3792
3793    /// Poll a query task while preserving server stop and drain metadata.
3794    pub async fn poll_query_task_response(
3795        &self,
3796        worker_id: &str,
3797        task_queue: &str,
3798        timeout: Duration,
3799    ) -> Result<PollQueryTaskResponse> {
3800        let poll_request_id = unique_request_id("rust-query-poll");
3801        self.poll_query_task_response_with_request_id(
3802            worker_id,
3803            task_queue,
3804            timeout,
3805            &poll_request_id,
3806            1,
3807        )
3808        .await
3809    }
3810
3811    async fn poll_query_task_response_with_request_id(
3812        &self,
3813        worker_id: &str,
3814        task_queue: &str,
3815        timeout: Duration,
3816        poll_request_id: &str,
3817        transport_retries: usize,
3818    ) -> Result<PollQueryTaskResponse> {
3819        let timeout_seconds = long_poll_timeout_seconds(timeout);
3820        let body = json!({
3821            "worker_id": worker_id,
3822            "task_queue": task_queue,
3823            "poll_request_id": poll_request_id,
3824            "timeout_seconds": timeout_seconds,
3825        });
3826        self.poll_request_json(
3827            "/worker/query-tasks/poll",
3828            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3829            &body,
3830            timeout + Duration::from_secs(5),
3831            transport_retries,
3832        )
3833        .await
3834    }
3835
3836    /// Complete a query task without appending workflow history.
3837    pub async fn complete_query_task<T: Serialize>(
3838        &self,
3839        query_task_id: &str,
3840        lease_owner: &str,
3841        query_task_attempt: u64,
3842        result: T,
3843        codec: &str,
3844    ) -> Result<Value> {
3845        let typed_result = AvroValue::from_serialize(&result)?;
3846        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3847        self.complete_query_task_with_envelope(
3848            query_task_id,
3849            lease_owner,
3850            query_task_attempt,
3851            typed_result.into_json()?,
3852            result_envelope,
3853        )
3854        .await
3855    }
3856
3857    async fn complete_query_task_with_envelope(
3858        &self,
3859        query_task_id: &str,
3860        lease_owner: &str,
3861        query_task_attempt: u64,
3862        result: Value,
3863        result_envelope: Value,
3864    ) -> Result<Value> {
3865        let body = json!({
3866            "lease_owner": lease_owner,
3867            "query_task_attempt": query_task_attempt,
3868            "result": result,
3869            "result_envelope": result_envelope,
3870        });
3871        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3872        let response = self
3873            .request_json(
3874                reqwest::Method::POST,
3875                &path,
3876                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3877                Some(&body),
3878            )
3879            .await;
3880        query_task_response(response)
3881    }
3882
3883    /// Report a stable machine-readable query-task failure.
3884    pub async fn fail_query_task(
3885        &self,
3886        query_task_id: &str,
3887        lease_owner: &str,
3888        query_task_attempt: u64,
3889        message: impl Into<String>,
3890        reason: impl Into<String>,
3891        failure_type: impl Into<String>,
3892    ) -> Result<Value> {
3893        let body = json!({
3894            "lease_owner": lease_owner,
3895            "query_task_attempt": query_task_attempt,
3896            "failure": {
3897                "message": message.into(),
3898                "reason": reason.into(),
3899                "type": failure_type.into(),
3900            }
3901        });
3902        let path = format!("/worker/query-tasks/{query_task_id}/fail");
3903        let response = self
3904            .request_json(
3905                reqwest::Method::POST,
3906                &path,
3907                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3908                Some(&body),
3909            )
3910            .await;
3911        query_task_response(response)
3912    }
3913
3914    pub async fn heartbeat_worker(
3915        &self,
3916        worker_id: &str,
3917        workflow_available: usize,
3918        activity_available: usize,
3919    ) -> Result<Value> {
3920        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
3921            .await
3922    }
3923
3924    async fn heartbeat_worker_with_sessions(
3925        &self,
3926        worker_id: &str,
3927        workflow_available: usize,
3928        activity_available: usize,
3929        session_available: Option<usize>,
3930    ) -> Result<Value> {
3931        let mut body = json!({
3932            "worker_id": worker_id,
3933            "task_slots": {
3934                "workflow_available": workflow_available,
3935                "activity_available": activity_available
3936            },
3937            "process_metrics": {
3938                "process_id": std::process::id(),
3939                "process_uptime_seconds": 0
3940            }
3941        });
3942
3943        if let Some(available) = session_available {
3944            body["task_slots"]["session_available"] = json!(available);
3945        }
3946
3947        self.request_json(
3948            reqwest::Method::POST,
3949            "/worker/heartbeat",
3950            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3951            Some(&body),
3952        )
3953        .await
3954    }
3955
3956    pub async fn poll_workflow_task(
3957        &self,
3958        worker_id: &str,
3959        task_queue: &str,
3960        timeout: Duration,
3961    ) -> Result<Option<WorkflowTask>> {
3962        Ok(self
3963            .poll_workflow_task_response(worker_id, task_queue, timeout)
3964            .await?
3965            .task)
3966    }
3967
3968    pub async fn poll_workflow_task_response(
3969        &self,
3970        worker_id: &str,
3971        task_queue: &str,
3972        timeout: Duration,
3973    ) -> Result<PollWorkflowTaskResponse> {
3974        let poll_request_id = unique_request_id("rust-workflow-poll");
3975        self.poll_workflow_task_response_with_request_id(
3976            worker_id,
3977            task_queue,
3978            timeout,
3979            &poll_request_id,
3980            1,
3981        )
3982        .await
3983    }
3984
3985    async fn poll_workflow_task_response_with_request_id(
3986        &self,
3987        worker_id: &str,
3988        task_queue: &str,
3989        timeout: Duration,
3990        poll_request_id: &str,
3991        transport_retries: usize,
3992    ) -> Result<PollWorkflowTaskResponse> {
3993        let body = json!({
3994            "worker_id": worker_id,
3995            "task_queue": task_queue,
3996            "poll_request_id": poll_request_id,
3997            "timeout_seconds": long_poll_timeout_seconds(timeout),
3998            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
3999        });
4000        let mut data: PollWorkflowTaskResponse = self
4001            .poll_request_json(
4002                "/worker/workflow-tasks/poll",
4003                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4004                &body,
4005                timeout + Duration::from_secs(5),
4006                transport_retries,
4007            )
4008            .await?;
4009
4010        if let Some(task) = data.task.as_mut() {
4011            self.fetch_remaining_workflow_history(worker_id, task)
4012                .await?;
4013        }
4014
4015        Ok(data)
4016    }
4017
4018    async fn fetch_remaining_workflow_history(
4019        &self,
4020        worker_id: &str,
4021        task: &mut WorkflowTask,
4022    ) -> Result<()> {
4023        let mut next_token = task.next_history_page_token.clone();
4024
4025        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4026            let lease_owner = task
4027                .lease_owner
4028                .clone()
4029                .unwrap_or_else(|| worker_id.to_string());
4030            let page = self
4031                .workflow_task_history_page(
4032                    &task.task_id,
4033                    &lease_owner,
4034                    task.workflow_task_attempt,
4035                    &token,
4036                )
4037                .await?;
4038
4039            task.append_history_page(page);
4040
4041            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4042                return Err(Error::Codec(
4043                    "workflow history pagination returned the same page token".to_string(),
4044                ));
4045            }
4046
4047            next_token = task.next_history_page_token.clone();
4048        }
4049
4050        Ok(())
4051    }
4052
4053    async fn workflow_task_history_page(
4054        &self,
4055        task_id: &str,
4056        lease_owner: &str,
4057        workflow_task_attempt: u64,
4058        next_history_page_token: &str,
4059    ) -> Result<WorkflowTaskHistoryPage> {
4060        let body = json!({
4061            "lease_owner": lease_owner,
4062            "workflow_task_attempt": workflow_task_attempt,
4063            "next_history_page_token": next_history_page_token
4064        });
4065        let path = format!("/worker/workflow-tasks/{task_id}/history");
4066
4067        self.request_json(
4068            reqwest::Method::POST,
4069            &path,
4070            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4071            Some(&body),
4072        )
4073        .await
4074    }
4075
4076    pub async fn complete_workflow_task(
4077        &self,
4078        task_id: &str,
4079        lease_owner: &str,
4080        workflow_task_attempt: u64,
4081        commands: Vec<Value>,
4082    ) -> Result<Value> {
4083        self.complete_workflow_task_with_message_streams(
4084            task_id,
4085            lease_owner,
4086            workflow_task_attempt,
4087            commands,
4088            Vec::new(),
4089            Vec::new(),
4090        )
4091        .await
4092    }
4093
4094    async fn complete_workflow_task_with_message_streams(
4095        &self,
4096        task_id: &str,
4097        lease_owner: &str,
4098        workflow_task_attempt: u64,
4099        commands: Vec<Value>,
4100        message_stream_cursors: Vec<Value>,
4101        message_stream_waits: Vec<Value>,
4102    ) -> Result<Value> {
4103        validate_workflow_task_commands(&commands)?;
4104        let has_message_stream_metadata =
4105            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4106        if has_message_stream_metadata
4107            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4108        {
4109            return Err(Error::Codec(
4110                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4111                    .to_string(),
4112            ));
4113        }
4114        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4115            &commands,
4116            has_message_stream_metadata,
4117        );
4118        let mut body = json!({
4119            "lease_owner": lease_owner,
4120            "workflow_task_attempt": workflow_task_attempt,
4121            "commands": commands
4122        });
4123        if !message_stream_cursors.is_empty() {
4124            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4125        }
4126        if !message_stream_waits.is_empty() {
4127            body["message_stream_waits"] = Value::Array(message_stream_waits);
4128        }
4129        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4130        self.request_json(
4131            reqwest::Method::POST,
4132            &path,
4133            RequestProtocol::Worker(protocol_version),
4134            Some(&body),
4135        )
4136        .await
4137    }
4138
4139    pub async fn fail_workflow_task(
4140        &self,
4141        task_id: &str,
4142        lease_owner: &str,
4143        workflow_task_attempt: u64,
4144        message: impl Into<String>,
4145    ) -> Result<Value> {
4146        self.fail_workflow_task_with_type(
4147            task_id,
4148            lease_owner,
4149            workflow_task_attempt,
4150            message,
4151            "RustWorkflowTaskFailure",
4152        )
4153        .await
4154    }
4155
4156    async fn fail_workflow_task_with_type(
4157        &self,
4158        task_id: &str,
4159        lease_owner: &str,
4160        workflow_task_attempt: u64,
4161        message: impl Into<String>,
4162        failure_type: &str,
4163    ) -> Result<Value> {
4164        let body = json!({
4165            "lease_owner": lease_owner,
4166            "workflow_task_attempt": workflow_task_attempt,
4167            "failure": {
4168                "message": message.into(),
4169                "type": failure_type
4170            }
4171        });
4172        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4173        self.request_json(
4174            reqwest::Method::POST,
4175            &path,
4176            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4177            Some(&body),
4178        )
4179        .await
4180    }
4181
4182    pub async fn poll_activity_task(
4183        &self,
4184        worker_id: &str,
4185        task_queue: &str,
4186        timeout: Duration,
4187    ) -> Result<Option<ActivityTask>> {
4188        Ok(self
4189            .poll_activity_task_response(worker_id, task_queue, timeout)
4190            .await?
4191            .task)
4192    }
4193
4194    /// Poll an activity task while preserving server stop and drain metadata.
4195    pub async fn poll_activity_task_response(
4196        &self,
4197        worker_id: &str,
4198        task_queue: &str,
4199        timeout: Duration,
4200    ) -> Result<PollActivityTaskResponse> {
4201        let poll_request_id = unique_request_id("rust-activity-poll");
4202        self.poll_activity_task_response_with_request_id(
4203            worker_id,
4204            task_queue,
4205            timeout,
4206            &poll_request_id,
4207            1,
4208        )
4209        .await
4210        .map(worker_session::SessionPollResponse::ordinary)
4211    }
4212
4213    async fn poll_activity_task_response_with_request_id(
4214        &self,
4215        worker_id: &str,
4216        task_queue: &str,
4217        timeout: Duration,
4218        poll_request_id: &str,
4219        transport_retries: usize,
4220    ) -> Result<worker_session::SessionPollResponse> {
4221        let body = json!({
4222            "worker_id": worker_id,
4223            "task_queue": task_queue,
4224            "poll_request_id": poll_request_id,
4225            "timeout_seconds": long_poll_timeout_seconds(timeout),
4226        });
4227        let data: worker_session::SessionPollResponse = self
4228            .poll_request_json(
4229                "/worker/activity-tasks/poll",
4230                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4231                &body,
4232                timeout + Duration::from_secs(5),
4233                transport_retries,
4234            )
4235            .await?;
4236        Ok(data)
4237    }
4238
4239    pub async fn complete_activity_task<T: Serialize>(
4240        &self,
4241        task_id: &str,
4242        activity_attempt_id: &str,
4243        lease_owner: &str,
4244        result: T,
4245        codec: &str,
4246    ) -> Result<Value> {
4247        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4248        let body = json!({
4249            "activity_attempt_id": activity_attempt_id,
4250            "lease_owner": lease_owner,
4251            "result": result
4252        });
4253        let path = format!("/worker/activity-tasks/{task_id}/complete");
4254        activity_task_response(
4255            self.request_json(
4256                reqwest::Method::POST,
4257                &path,
4258                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4259                Some(&body),
4260            )
4261            .await,
4262            "complete",
4263            task_id,
4264            activity_attempt_id,
4265        )
4266    }
4267
4268    pub async fn fail_activity_task(
4269        &self,
4270        task_id: &str,
4271        activity_attempt_id: &str,
4272        lease_owner: &str,
4273        message: impl Into<String>,
4274        non_retryable: bool,
4275    ) -> Result<Value> {
4276        let body = json!({
4277            "activity_attempt_id": activity_attempt_id,
4278            "lease_owner": lease_owner,
4279            "failure": {
4280                "message": message.into(),
4281                "type": "RustActivityFailure",
4282                "non_retryable": non_retryable
4283            }
4284        });
4285        let path = format!("/worker/activity-tasks/{task_id}/fail");
4286        activity_task_response(
4287            self.request_json(
4288                reqwest::Method::POST,
4289                &path,
4290                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4291                Some(&body),
4292            )
4293            .await,
4294            "fail",
4295            task_id,
4296            activity_attempt_id,
4297        )
4298    }
4299
4300    pub async fn heartbeat_activity_task<T: Serialize>(
4301        &self,
4302        task_id: &str,
4303        activity_attempt_id: &str,
4304        lease_owner: &str,
4305        details: T,
4306    ) -> Result<ActivityHeartbeatResponse> {
4307        serde_json::from_value(
4308            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4309                .await?,
4310        )
4311        .map_err(Error::from)
4312    }
4313
4314    async fn heartbeat_activity_task_value<T: Serialize>(
4315        &self,
4316        task_id: &str,
4317        activity_attempt_id: &str,
4318        lease_owner: &str,
4319        details: T,
4320    ) -> Result<Value> {
4321        let details = encode_typed_envelope(&AvroValue::from_serialize(&details)?, DEFAULT_CODEC)?;
4322        let body = json!({
4323            "activity_attempt_id": activity_attempt_id,
4324            "lease_owner": lease_owner,
4325            "details": details
4326        });
4327        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4328        activity_task_response(
4329            self.request_json(
4330                reqwest::Method::POST,
4331                &path,
4332                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4333                Some(&body),
4334            )
4335            .await,
4336            "heartbeat",
4337            task_id,
4338            activity_attempt_id,
4339        )
4340    }
4341
4342    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4343        &self,
4344        method: reqwest::Method,
4345        path: &str,
4346        protocol: RequestProtocol,
4347        body: Option<&B>,
4348    ) -> Result<T> {
4349        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4350            .await
4351    }
4352
4353    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4354        &self,
4355        method: reqwest::Method,
4356        path: &str,
4357        protocol: RequestProtocol,
4358        body: Option<&B>,
4359        timeout: Duration,
4360    ) -> Result<T> {
4361        let protocol = match protocol {
4362            RequestProtocol::Worker(version)
4363                if self.cooperative_worker_protocol
4364                    && version
4365                        .strip_prefix("1.")
4366                        .and_then(|minor| minor.parse::<u64>().ok())
4367                        .is_some_and(|minor| minor < 20) =>
4368            {
4369                RequestProtocol::Worker("1.20")
4370            }
4371            protocol => protocol,
4372        };
4373        let auth_token = self.auth_token(protocol)?;
4374        let mut request = self
4375            .http
4376            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4377            .timeout(timeout)
4378            .header(reqwest::header::ACCEPT, "application/json")
4379            .header(reqwest::header::CONTENT_TYPE, "application/json")
4380            .header("X-Namespace", &self.namespace);
4381
4382        match protocol {
4383            RequestProtocol::Worker(version) => {
4384                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4385            }
4386            RequestProtocol::ControlPlane => {
4387                request = request.header(
4388                    "X-Durable-Workflow-Control-Plane-Version",
4389                    CONTROL_PLANE_VERSION,
4390                );
4391            }
4392        }
4393
4394        if let Some(token) = auth_token {
4395            request = request.bearer_auth(token);
4396        }
4397
4398        if let Some(body) = body {
4399            let mut body = serde_json::to_value(body)?;
4400            if matches!(
4401                method,
4402                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4403            ) {
4404                self.externalize_runtime_payloads(&mut body, path, protocol)
4405                    .await?;
4406            }
4407            request = request.json(&body);
4408        }
4409
4410        let request = request.build()?;
4411        let request_body = request
4412            .body()
4413            .and_then(reqwest::Body::as_bytes)
4414            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4415        let poll_request_id = path.ends_with("/poll").then(|| {
4416            request_body
4417                .as_ref()
4418                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4419                .unwrap_or_default()
4420        });
4421        let mut storage_retries = 0_usize;
4422
4423        loop {
4424            // Keep the serialized body and lease/poll identity across admission pauses.
4425            let response = self
4426                .http
4427                .execute(request.try_clone().ok_or_else(|| {
4428                    Error::WorkerLoop("worker request body cannot be retried".to_string())
4429                })?)
4430                .await?;
4431            let status = response.status();
4432            let bytes = response.bytes().await?;
4433
4434            if !status.is_success() {
4435                let body = String::from_utf8_lossy(&bytes).to_string();
4436                if let Some(protocol) = protocol_failure(status, &body) {
4437                    return Err(Error::Protocol(protocol));
4438                }
4439                let error = Error::Http { status, body };
4440                if self
4441                    .wait_for_storage_admission(
4442                        &error,
4443                        protocol,
4444                        Some(path),
4445                        poll_request_id.as_deref(),
4446                        request_body.as_ref(),
4447                        &mut storage_retries,
4448                    )
4449                    .await
4450                {
4451                    continue;
4452                }
4453                return Err(error);
4454            }
4455
4456            if bytes.is_empty() {
4457                return Ok(serde_json::from_value(Value::Null)?);
4458            }
4459
4460            let mut value: Value = serde_json::from_slice(&bytes)?;
4461            self.resolve_runtime_payloads(&mut value, path, protocol)
4462                .await?;
4463            return Ok(serde_json::from_value(value)?);
4464        }
4465    }
4466
4467    async fn wait_for_storage_admission(
4468        &self,
4469        error: &Error,
4470        protocol: RequestProtocol,
4471        path: Option<&str>,
4472        poll_request_id: Option<&str>,
4473        request_body: Option<&Value>,
4474        retries: &mut usize,
4475    ) -> bool {
4476        let Some(admission) = self
4477            .worker_storage_admission
4478            .as_ref()
4479            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4480        else {
4481            return false;
4482        };
4483        let Some(advertised_delay) = worker_storage_admission_retry_after(error, poll_request_id)
4484            .or_else(|| {
4485                path.and_then(|path| {
4486                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4487                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4488                })
4489            })
4490        else {
4491            return false;
4492        };
4493        *retries = retries.saturating_add(1);
4494        let delay = worker_retry_delay(admission.policy, *retries)
4495            .max(advertised_delay)
4496            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4497        let deadline = tokio::time::Instant::now() + delay;
4498        loop {
4499            if admission.stop.load(Ordering::SeqCst) {
4500                return false;
4501            }
4502            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
4503            if remaining.is_zero() {
4504                return true;
4505            }
4506            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4507        }
4508    }
4509
4510    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4511        &self,
4512        path: &str,
4513        protocol: RequestProtocol,
4514        body: &B,
4515        timeout: Duration,
4516        max_retries: usize,
4517    ) -> Result<T> {
4518        let mut retries = 0;
4519
4520        loop {
4521            let response = self
4522                .request_json_with_timeout(
4523                    reqwest::Method::POST,
4524                    path,
4525                    protocol,
4526                    Some(body),
4527                    timeout,
4528                )
4529                .await;
4530
4531            match response {
4532                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4533                response => return worker_poll_response(response),
4534            }
4535        }
4536    }
4537
4538    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4539        match protocol {
4540            RequestProtocol::Worker(_) => {
4541                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4542                    return Ok(Some(token));
4543                }
4544                if self.control_token.is_some() {
4545                    return Err(Error::MissingRoleCredentials {
4546                        role: "worker",
4547                        opposite_role: "control",
4548                    });
4549                }
4550                Ok(None)
4551            }
4552            RequestProtocol::ControlPlane => {
4553                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4554                    return Ok(Some(token));
4555                }
4556                if self.worker_token.is_some() {
4557                    return Err(Error::MissingRoleCredentials {
4558                        role: "control",
4559                        opposite_role: "worker",
4560                    });
4561                }
4562                Ok(None)
4563            }
4564        }
4565    }
4566}
4567
4568fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4569    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4570    let reason = body
4571        .get("reason")
4572        .and_then(Value::as_str)
4573        .unwrap_or("query_rejected")
4574        .to_string();
4575    let message = body
4576        .get("message")
4577        .or_else(|| body.get("error"))
4578        .and_then(Value::as_str)
4579        .unwrap_or("workflow query was rejected")
4580        .to_string();
4581
4582    QueryFailure {
4583        status: status.as_u16(),
4584        reason,
4585        message,
4586        body,
4587    }
4588}
4589
4590fn workflow_command_result(
4591    command: WorkflowCommandKind,
4592    data: Value,
4593    workflow_id: &str,
4594    run_id: Option<&str>,
4595) -> WorkflowCommandResult {
4596    WorkflowCommandResult {
4597        command,
4598        workflow_id: data
4599            .get("workflow_id")
4600            .and_then(Value::as_str)
4601            .unwrap_or(workflow_id)
4602            .to_string(),
4603        run_id: data
4604            .get("run_id")
4605            .and_then(Value::as_str)
4606            .or(run_id)
4607            .map(str::to_string),
4608        outcome: data
4609            .get("outcome")
4610            .and_then(Value::as_str)
4611            .map(str::to_string),
4612        reason: data
4613            .get("reason")
4614            .and_then(Value::as_str)
4615            .map(str::to_string),
4616        command_status: data
4617            .get("command_status")
4618            .and_then(Value::as_str)
4619            .map(str::to_string),
4620        raw: data,
4621    }
4622}
4623
4624fn workflow_command_rejection(
4625    command: WorkflowCommandKind,
4626    status: reqwest::StatusCode,
4627    raw_body: String,
4628    workflow_id: &str,
4629    run_id: Option<&str>,
4630) -> WorkflowCommandRejection {
4631    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4632    WorkflowCommandRejection {
4633        command,
4634        status: status.as_u16(),
4635        reason: body
4636            .get("reason")
4637            .and_then(Value::as_str)
4638            .unwrap_or("workflow_command_rejected")
4639            .to_string(),
4640        message: body
4641            .get("message")
4642            .or_else(|| body.get("error"))
4643            .and_then(Value::as_str)
4644            .unwrap_or("workflow lifecycle command was rejected")
4645            .to_string(),
4646        workflow_id: body
4647            .get("workflow_id")
4648            .and_then(Value::as_str)
4649            .unwrap_or(workflow_id)
4650            .to_string(),
4651        run_id: body
4652            .get("run_id")
4653            .and_then(Value::as_str)
4654            .or(run_id)
4655            .map(str::to_string),
4656        target_scope: body
4657            .get("target_scope")
4658            .and_then(Value::as_str)
4659            .map(str::to_string),
4660        body,
4661    }
4662}
4663
4664fn query_task_response(response: Result<Value>) -> Result<Value> {
4665    match response {
4666        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4667        response => response,
4668    }
4669}
4670
4671fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4672    match response {
4673        Err(Error::Http { status, body })
4674            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4675        {
4676            Ok(serde_json::from_str(&body)?)
4677        }
4678        response => response,
4679    }
4680}
4681
4682fn worker_poll_body_is_stop(body: &str) -> bool {
4683    serde_json::from_str::<Value>(body)
4684        .ok()
4685        .is_some_and(|body| {
4686            worker_poll_is_stop(
4687                body.get("poll_status").and_then(Value::as_str),
4688                body.get("reason").and_then(Value::as_str),
4689            )
4690        })
4691}
4692
4693fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4694    matches!(poll_status, Some("draining" | "stopped"))
4695        || matches!(reason, Some("worker_draining" | "worker_stopped"))
4696}
4697
4698fn query_task_rejection_is_final(error: &Error) -> bool {
4699    matches!(
4700        error,
4701        Error::QueryFailed(failure)
4702            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
4703    )
4704}
4705
4706fn activity_task_response<T>(
4707    response: Result<T>,
4708    operation: &str,
4709    task_id: &str,
4710    activity_attempt_id: &str,
4711) -> Result<T> {
4712    match response {
4713        Err(Error::Http { status, body }) => {
4714            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
4715            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
4716                operation: operation.to_string(),
4717                status: status.as_u16(),
4718                reason: body
4719                    .get("reason")
4720                    .and_then(Value::as_str)
4721                    .unwrap_or("activity_task_rejected")
4722                    .to_string(),
4723                task_id: body
4724                    .get("task_id")
4725                    .and_then(Value::as_str)
4726                    .unwrap_or(task_id)
4727                    .to_string(),
4728                activity_attempt_id: body
4729                    .get("activity_attempt_id")
4730                    .and_then(Value::as_str)
4731                    .unwrap_or(activity_attempt_id)
4732                    .to_string(),
4733                cancel_requested: body
4734                    .get("cancel_requested")
4735                    .and_then(Value::as_bool)
4736                    .unwrap_or(false),
4737                can_continue: body.get("can_continue").and_then(Value::as_bool),
4738                run_closed_reason: body
4739                    .get("run_closed_reason")
4740                    .and_then(Value::as_str)
4741                    .map(str::to_string),
4742                body,
4743            }))
4744        }
4745        response => response,
4746    }
4747}
4748
4749fn activity_task_rejection_is_final(error: &Error) -> bool {
4750    matches!(
4751        error,
4752        Error::ActivityTaskRejected(rejection)
4753            if matches!(
4754                rejection.reason.as_str(),
4755                "run_cancelled"
4756                    | "run_terminated"
4757                    | "attempt_closed"
4758                    | "stale_attempt"
4759                    | "activity_cancelled"
4760                    | "task_cancelled"
4761                    | "run_closed"
4762                    | "activity_not_running"
4763                    | "attempt_not_found"
4764            )
4765    )
4766}
4767
4768fn workflow_task_completion_is_terminal_timeout(
4769    error: &Error,
4770    task_id: &str,
4771    workflow_task_attempt: u64,
4772    run_id: Option<&str>,
4773) -> bool {
4774    let Error::Http { status, body } = error else {
4775        return false;
4776    };
4777    if *status != reqwest::StatusCode::CONFLICT {
4778        return false;
4779    }
4780
4781    let Some(run_id) = run_id else {
4782        return false;
4783    };
4784    let Ok(body) = serde_json::from_str::<Value>(body) else {
4785        return false;
4786    };
4787
4788    body.get("recorded").and_then(Value::as_bool) == Some(false)
4789        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
4790        && body.get("run_status").and_then(Value::as_str) == Some("failed")
4791        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
4792        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
4793        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
4794}
4795
4796fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
4797    let body: Value = serde_json::from_str(raw_body).ok()?;
4798    let reason = body.get("reason")?.as_str()?;
4799    if !matches!(
4800        reason,
4801        "missing_protocol_version"
4802            | "unsupported_protocol_version"
4803            | "missing_control_plane_version"
4804            | "unsupported_control_plane_version"
4805    ) {
4806        return None;
4807    }
4808
4809    Some(ProtocolFailure {
4810        status: status.as_u16(),
4811        reason: reason.to_string(),
4812        message: body
4813            .get("message")
4814            .or_else(|| body.get("error"))
4815            .and_then(Value::as_str)
4816            .unwrap_or("protocol version rejected")
4817            .to_string(),
4818        supported_version: body
4819            .get("supported_version")
4820            .and_then(Value::as_str)
4821            .map(str::to_string),
4822        requested_version: body
4823            .get("requested_version")
4824            .and_then(Value::as_str)
4825            .map(str::to_string),
4826        body,
4827    })
4828}
4829
4830fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
4831    timeout
4832        .as_secs()
4833        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
4834        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
4835}
4836
4837fn worker_operation_is_retryable(error: &Error) -> bool {
4838    if worker_poll_capacity_retry_after(error).is_some()
4839        || worker_storage_admission_body(error).is_some()
4840        || worker_backend_unavailable_body(error).is_some()
4841        || worker_operation_is_explicitly_non_retryable(error)
4842    {
4843        return false;
4844    }
4845
4846    match error {
4847        Error::Transport(error) => {
4848            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
4849        }
4850        Error::Http { status, .. } => {
4851            matches!(
4852                *status,
4853                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
4854            ) || status.is_server_error()
4855        }
4856        _ => false,
4857    }
4858}
4859
4860fn worker_storage_admission_body(error: &Error) -> Option<Value> {
4861    let body: Value = match error {
4862        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
4863        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
4864        _ => return None,
4865    };
4866    matches!(
4867        body.get("reason").and_then(Value::as_str),
4868        Some("storage_pressure" | "storage_admission_unavailable")
4869    )
4870    .then_some(body)
4871}
4872
4873fn worker_storage_admission_retry_after(
4874    error: &Error,
4875    poll_request_id: Option<&str>,
4876) -> Option<Duration> {
4877    let Error::Http { status, .. } = error else {
4878        return None;
4879    };
4880    let body = worker_storage_admission_body(error)?;
4881    let delay = body.get("retry_after_seconds")?.as_u64()?;
4882    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
4883        || delay == 0
4884        || body.get("retryable") != Some(&Value::Bool(true))
4885        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
4886        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
4887        || body
4888            .get("request_admitted")
4889            .is_some_and(|admitted| admitted != &Value::Bool(false))
4890    {
4891        return None;
4892    }
4893    match poll_request_id {
4894        Some(id) => {
4895            if id.is_empty()
4896                || body.get("task") != Some(&Value::Null)
4897                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
4898                || body.get("poll_status") != body.get("reason")
4899                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
4900                || body.get("claim_admitted") != Some(&Value::Bool(false))
4901            {
4902                return None;
4903            }
4904        }
4905        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
4906        None => {}
4907    }
4908    Some(Duration::from_secs(delay))
4909}
4910
4911fn worker_backend_unavailable_retry_after(
4912    error: &Error,
4913    path: &str,
4914    poll_request_id: Option<&str>,
4915) -> Option<Duration> {
4916    let operation = match path {
4917        "/worker/register" => "register_worker",
4918        "/worker/heartbeat" => "heartbeat_worker",
4919        "/worker/workflow-tasks/poll" => "poll_workflow_task",
4920        "/worker/activity-tasks/poll" => "poll_activity_task",
4921        "/worker/query-tasks/poll" => "poll_query_task",
4922        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
4923        _ => return None,
4924    };
4925    let body = worker_backend_unavailable_body(error)?;
4926    let delay = body.get("retry_after_seconds")?.as_u64()?;
4927    if delay == 0
4928        || body.get("operation")?.as_str()? != operation
4929        || body.get("outcome")?.as_str()? != "unknown"
4930        || body.get("retryable") != Some(&Value::Bool(true))
4931        || body.get("worker_id")?.as_str()?.is_empty()
4932    {
4933        return None;
4934    }
4935    if let Some(id) = poll_request_id {
4936        if id.is_empty()
4937            || body.get("task") != Some(&Value::Null)
4938            || body.get("poll_status")?.as_str()? != "backend_unavailable"
4939            || body.get("poll_request_id")?.as_str()? != id
4940            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
4941        {
4942            return None;
4943        }
4944    } else if path.ends_with("/poll") {
4945        return None;
4946    }
4947    Some(Duration::from_secs(delay))
4948}
4949
4950fn worker_fenced_completion_retry_after(
4951    error: &Error,
4952    path: &str,
4953    request_body: Option<&Value>,
4954) -> Option<Duration> {
4955    let (operation, task_id, attempt_field) = if let Some(task_id) = path
4956        .strip_prefix("/worker/workflow-tasks/")
4957        .and_then(|tail| tail.strip_suffix("/complete"))
4958    {
4959        ("complete_workflow_task", task_id, "workflow_task_attempt")
4960    } else if let Some(task_id) = path
4961        .strip_prefix("/worker/activity-tasks/")
4962        .and_then(|tail| tail.strip_suffix("/complete"))
4963    {
4964        ("complete_activity_task", task_id, "activity_attempt_id")
4965    } else {
4966        return None;
4967    };
4968    if task_id.is_empty() || task_id.contains('/') {
4969        return None;
4970    }
4971
4972    let request = request_body?.as_object()?;
4973    let lease_owner = request.get("lease_owner")?.as_str()?;
4974    if lease_owner.is_empty() {
4975        return None;
4976    }
4977    let attempt = request.get(attempt_field)?;
4978    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
4979        || (attempt_field == "activity_attempt_id"
4980            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
4981    {
4982        return None;
4983    }
4984
4985    let body = worker_backend_unavailable_body(error)?;
4986    let delay = body.get("retry_after_seconds")?.as_u64()?;
4987    if delay == 0
4988        || body.get("operation")?.as_str()? != operation
4989        || body.get("outcome")?.as_str()? != "unknown"
4990        || body.get("retryable") != Some(&Value::Bool(true))
4991        || body.get("worker_id")?.as_str()? != lease_owner
4992        || body.get("task_queue") != Some(&Value::Null)
4993        || body.get("task_id")?.as_str()? != task_id
4994        || body.get("lease_owner")?.as_str()? != lease_owner
4995        || body.get(attempt_field) != Some(attempt)
4996    {
4997        return None;
4998    }
4999
5000    Some(Duration::from_secs(delay))
5001}
5002
5003fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5004    let Error::Http { status, body } = error else {
5005        return None;
5006    };
5007    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5008        return None;
5009    }
5010    let body: Value = serde_json::from_str(body).ok()?;
5011    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5012}
5013
5014fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5015    let Error::Http { body, .. } = error else {
5016        return false;
5017    };
5018
5019    serde_json::from_str::<Value>(body)
5020        .ok()
5021        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5022        == Some(false)
5023}
5024
5025fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5026    let Error::Http { status, body } = error else {
5027        return None;
5028    };
5029    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5030        return None;
5031    }
5032
5033    let body = serde_json::from_str::<Value>(body).ok()?;
5034    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5035        == Some("long_poll_capacity_exhausted")
5036        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5037    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5038        return None;
5039    }
5040
5041    Some(Duration::from_secs(
5042        body.get("retry_after_seconds")
5043            .and_then(Value::as_u64)
5044            .unwrap_or_default(),
5045    ))
5046}
5047
5048fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5049    let exponent = retry.saturating_sub(1).min(31) as u32;
5050    policy
5051        .initial_backoff
5052        .saturating_mul(1_u32 << exponent)
5053        .min(policy.max_backoff)
5054}
5055
5056#[derive(Debug)]
5057pub struct ClientBuilder {
5058    base_url: String,
5059    token: Option<String>,
5060    control_token: Option<String>,
5061    worker_token: Option<String>,
5062    namespace: String,
5063    timeout: Duration,
5064    max_external_payload_bytes: usize,
5065}
5066
5067impl ClientBuilder {
5068    pub fn token(mut self, token: Option<String>) -> Self {
5069        self.token = token;
5070        self
5071    }
5072
5073    pub fn control_token(mut self, token: Option<String>) -> Self {
5074        self.control_token = token;
5075        self
5076    }
5077
5078    pub fn worker_token(mut self, token: Option<String>) -> Self {
5079        self.worker_token = token;
5080        self
5081    }
5082
5083    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5084        self.namespace = namespace.into();
5085        self
5086    }
5087
5088    pub fn timeout(mut self, timeout: Duration) -> Self {
5089        self.timeout = timeout;
5090        self
5091    }
5092
5093    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5094    /// References are fetched only from this client's authenticated runtime.
5095    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5096        self.max_external_payload_bytes = bytes;
5097        self
5098    }
5099
5100    pub fn build(self) -> Result<Client> {
5101        let base_url = self.base_url.trim_end_matches('/').to_string();
5102        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5103            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5104            .unwrap_or_else(|_| base_url.ends_with("/api"));
5105
5106        if has_sdk_api_suffix {
5107            return Err(Error::InvalidBaseUrl);
5108        }
5109
5110        Ok(Client {
5111            http: reqwest::Client::builder()
5112                .timeout(self.timeout)
5113                .redirect(reqwest::redirect::Policy::none())
5114                .build()?,
5115            base_url,
5116            token: self.token,
5117            control_token: self.control_token,
5118            worker_token: self.worker_token,
5119            namespace: self.namespace,
5120            max_external_payload_bytes: self.max_external_payload_bytes,
5121            worker_storage_admission: None,
5122            cooperative_worker_protocol: false,
5123            local_activities_enabled: false,
5124            worker_sessions_enabled: false,
5125            max_concurrent_worker_sessions: 10,
5126            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5127        })
5128    }
5129}
5130
5131#[derive(Clone, Debug)]
5132pub struct WorkflowHandle {
5133    client: Client,
5134    pub workflow_id: String,
5135    pub run_id: Option<String>,
5136    pub workflow_type: String,
5137}
5138
5139impl WorkflowHandle {
5140    /// Describe whichever run is current for this stable workflow instance.
5141    pub async fn describe(&self) -> Result<WorkflowDescription> {
5142        self.client.describe_workflow(&self.workflow_id).await
5143    }
5144
5145    /// Describe the run identity originally selected by this handle.
5146    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5147        let run_id = self.run_id.as_deref().ok_or_else(|| {
5148            Error::Codec("run_id is required for selected-run description".to_string())
5149        })?;
5150        self.client
5151            .describe_workflow_run(&self.workflow_id, run_id)
5152            .await
5153    }
5154
5155    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5156        self.client
5157            .signal_workflow(&self.workflow_id, signal_name, input)
5158            .await
5159    }
5160
5161    pub async fn append_message<T: Serialize>(
5162        &self,
5163        stream_name: &str,
5164        message_id: &str,
5165        input: T,
5166    ) -> Result<Value> {
5167        self.client
5168            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5169            .await
5170    }
5171
5172    /// Signal only if this handle's selected run is still current.
5173    pub async fn signal_selected_run<T: Serialize>(
5174        &self,
5175        signal_name: &str,
5176        input: T,
5177    ) -> Result<Value> {
5178        let run_id = self.run_id.as_deref().ok_or_else(|| {
5179            Error::Codec("run_id is required for selected-run signaling".to_string())
5180        })?;
5181        self.client
5182            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5183            .await
5184    }
5185
5186    /// Close whichever run is current as cancelled, without workflow cleanup.
5187    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5188        self.client
5189            .cancel_workflow(&self.workflow_id, options)
5190            .await
5191    }
5192
5193    /// Request cancellation only if this handle's selected run is still current.
5194    pub async fn cancel_selected_run(
5195        &self,
5196        options: WorkflowCommandOptions,
5197    ) -> Result<WorkflowCommandResult> {
5198        let run_id = self.run_id.as_deref().ok_or_else(|| {
5199            Error::Codec("run_id is required for selected-run cancellation".to_string())
5200        })?;
5201        self.client
5202            .cancel_workflow_run(&self.workflow_id, run_id, options)
5203            .await
5204    }
5205
5206    /// Forcefully terminate whichever run is current.
5207    pub async fn terminate(
5208        &self,
5209        options: WorkflowCommandOptions,
5210    ) -> Result<WorkflowCommandResult> {
5211        self.client
5212            .terminate_workflow(&self.workflow_id, options)
5213            .await
5214    }
5215
5216    /// Terminate only if this handle's selected run is still current.
5217    pub async fn terminate_selected_run(
5218        &self,
5219        options: WorkflowCommandOptions,
5220    ) -> Result<WorkflowCommandResult> {
5221        let run_id = self.run_id.as_deref().ok_or_else(|| {
5222            Error::Codec("run_id is required for selected-run termination".to_string())
5223        })?;
5224        self.client
5225            .terminate_workflow_run(&self.workflow_id, run_id, options)
5226            .await
5227    }
5228
5229    /// Continue this handle's failed run without repeating completed activities.
5230    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5231        let run_id = self
5232            .run_id
5233            .as_deref()
5234            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5235        self.client
5236            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5237            .await
5238    }
5239
5240    /// Execute a named, read-only query against this workflow.
5241    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5242        self.client
5243            .query_workflow(&self.workflow_id, query_name, input)
5244            .await
5245    }
5246
5247    pub async fn query_avro_value<T: Serialize>(
5248        &self,
5249        query_name: &str,
5250        input: T,
5251    ) -> Result<AvroValue> {
5252        self.client
5253            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5254            .await
5255    }
5256
5257    pub async fn update<T: Serialize>(
5258        &self,
5259        update_name: &str,
5260        input: T,
5261        request_id: Option<&str>,
5262    ) -> Result<Value> {
5263        self.client
5264            .update_workflow(&self.workflow_id, update_name, input, request_id)
5265            .await
5266    }
5267
5268    pub async fn update_avro_value<T: Serialize>(
5269        &self,
5270        update_name: &str,
5271        input: T,
5272        request_id: Option<&str>,
5273    ) -> Result<AvroValue> {
5274        self.client
5275            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5276            .await
5277    }
5278
5279    /// Query only if this handle's selected run is still current.
5280    pub async fn query_selected_run<T: Serialize>(
5281        &self,
5282        query_name: &str,
5283        input: T,
5284    ) -> Result<Value> {
5285        let run_id = self
5286            .run_id
5287            .as_deref()
5288            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5289        self.client
5290            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5291            .await
5292    }
5293
5294    /// Await the final terminal outcome of the current continue-as-new chain.
5295    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5296        self.result_target(options, None).await
5297    }
5298
5299    /// Await the final result without projecting Avro bytes through JSON.
5300    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5301        self.result_avro_value_target(options, None).await
5302    }
5303
5304    /// Await the final result and decode it into a Serde application type.
5305    pub async fn result_typed<T: DeserializeOwned>(
5306        &self,
5307        options: WorkflowResultOptions,
5308    ) -> Result<T> {
5309        let result = self.result_avro_value(options).await?;
5310        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5311    }
5312
5313    /// Await only the run identity originally selected by this handle.
5314    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5315        let run_id = self.run_id.as_deref().ok_or_else(|| {
5316            Error::Codec("run_id is required for selected-run result".to_string())
5317        })?;
5318        self.result_target(options, Some(run_id)).await
5319    }
5320
5321    /// Await the selected run's result on the lossless Avro Value surface.
5322    pub async fn result_selected_run_avro_value(
5323        &self,
5324        options: WorkflowResultOptions,
5325    ) -> Result<AvroValue> {
5326        let run_id = self.run_id.as_deref().ok_or_else(|| {
5327            Error::Codec("run_id is required for selected-run result".to_string())
5328        })?;
5329        self.result_avro_value_target(options, Some(run_id)).await
5330    }
5331
5332    /// Await the selected run and decode its result into a Serde type.
5333    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5334        &self,
5335        options: WorkflowResultOptions,
5336    ) -> Result<T> {
5337        let result = self.result_selected_run_avro_value(options).await?;
5338        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5339    }
5340
5341    async fn result_avro_value_target(
5342        &self,
5343        options: WorkflowResultOptions,
5344        selected_run_id: Option<&str>,
5345    ) -> Result<AvroValue> {
5346        let started = Instant::now();
5347
5348        loop {
5349            let description = match selected_run_id {
5350                Some(run_id) => {
5351                    self.client
5352                        .describe_workflow_run(&self.workflow_id, run_id)
5353                        .await?
5354                }
5355                None => self.describe().await?,
5356            };
5357            if description.is_completed() {
5358                return description.output_avro_value.ok_or_else(|| {
5359                    Error::Codec(
5360                        "missing_payload_envelope: typed workflow result requires output_envelope"
5361                            .to_string(),
5362                    )
5363                });
5364            }
5365            if description.is_terminal() {
5366                let outcome =
5367                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5368                return Err(match outcome.kind {
5369                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5370                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5371                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5372                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5373                });
5374            }
5375            if started.elapsed() >= options.timeout {
5376                return Err(Error::Timeout);
5377            }
5378            tokio::time::sleep(options.poll_interval).await;
5379        }
5380    }
5381
5382    async fn result_target(
5383        &self,
5384        options: WorkflowResultOptions,
5385        selected_run_id: Option<&str>,
5386    ) -> Result<Value> {
5387        let started = Instant::now();
5388
5389        loop {
5390            let description = match selected_run_id {
5391                Some(run_id) => {
5392                    self.client
5393                        .describe_workflow_run(&self.workflow_id, run_id)
5394                        .await?
5395                }
5396                None => self.describe().await?,
5397            };
5398            if description.is_completed() {
5399                return Ok(description.output.unwrap_or(Value::Null));
5400            }
5401
5402            if description.is_terminal() {
5403                let outcome =
5404                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5405                return Err(match outcome.kind {
5406                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5407                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5408                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5409                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5410                });
5411            }
5412
5413            if started.elapsed() >= options.timeout {
5414                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5415                    kind: WorkflowTerminalKind::TimedOut,
5416                    workflow_id: description
5417                        .workflow_id
5418                        .clone()
5419                        .unwrap_or_else(|| self.workflow_id.clone()),
5420                    run_id: description
5421                        .run_id
5422                        .clone()
5423                        .or_else(|| selected_run_id.map(str::to_string)),
5424                    reason: "result_wait_timeout".to_string(),
5425                    failure_category: Some("client_timeout".to_string()),
5426                    failure_id: None,
5427                    exception_type: None,
5428                    exception_class: None,
5429                    non_retryable: None,
5430                    message: Some(format!(
5431                        "workflow result was not terminal within {:?}",
5432                        options.timeout
5433                    )),
5434                    exception: None,
5435                    raw: description.raw_value(),
5436                }));
5437            }
5438
5439            tokio::time::sleep(options.poll_interval).await;
5440        }
5441    }
5442}
5443
5444#[derive(Clone, Copy, Debug)]
5445pub struct WorkflowResultOptions {
5446    pub poll_interval: Duration,
5447    pub timeout: Duration,
5448}
5449
5450impl Default for WorkflowResultOptions {
5451    fn default() -> Self {
5452        Self {
5453            poll_interval: Duration::from_millis(500),
5454            timeout: Duration::from_secs(30),
5455        }
5456    }
5457}
5458
5459#[derive(Clone, Debug, Deserialize)]
5460pub struct WorkflowDescription {
5461    pub workflow_id: Option<String>,
5462    pub run_id: Option<String>,
5463    pub workflow_type: Option<String>,
5464    pub status: Option<String>,
5465    #[serde(default)]
5466    pub closed_reason: Option<String>,
5467    #[serde(default)]
5468    pub error: Option<String>,
5469    #[serde(default)]
5470    pub failure: Option<Value>,
5471    #[serde(default)]
5472    pub exception: Option<Value>,
5473    #[serde(default)]
5474    pub failures: Vec<Value>,
5475    #[serde(default)]
5476    pub output: Option<Value>,
5477    #[serde(default)]
5478    pub output_envelope: Option<Value>,
5479    #[serde(skip)]
5480    pub output_avro_value: Option<AvroValue>,
5481    #[serde(flatten)]
5482    pub raw: HashMap<String, Value>,
5483}
5484
5485/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5486#[derive(Clone, Debug, Deserialize)]
5487pub struct WorkflowStreamDescription {
5488    pub stream_name: String,
5489    pub status: String,
5490    pub last_offset: i64,
5491    pub total_items: u64,
5492    pub pending_items: u64,
5493    #[serde(default)]
5494    pub opened_at: Option<String>,
5495    #[serde(default)]
5496    pub last_appended_at: Option<String>,
5497    #[serde(default)]
5498    pub closed_at: Option<String>,
5499    #[serde(default)]
5500    pub error_reason: Option<String>,
5501    #[serde(default)]
5502    pub retention_seconds: Option<u64>,
5503    #[serde(flatten)]
5504    pub raw: HashMap<String, Value>,
5505}
5506
5507impl WorkflowStreamDescription {
5508    pub fn is_terminal(&self) -> bool {
5509        matches!(self.status.as_str(), "closed" | "errored")
5510    }
5511}
5512
5513/// One item for direct or replay-safe append.
5514#[derive(Clone, Debug, Default)]
5515pub struct WorkflowStreamAppendItem {
5516    pub payload_envelope: Option<Value>,
5517    pub payload_reference: Option<String>,
5518    pub item_type: Option<String>,
5519    pub content_type: Option<String>,
5520    pub idempotency_key: Option<String>,
5521}
5522
5523impl WorkflowStreamAppendItem {
5524    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5525    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5526        let value = AvroValue::from_serialize(&payload)?;
5527        Ok(Self {
5528            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5529            ..Self::default()
5530        })
5531    }
5532
5533    /// Preserve an external payload URI as an opaque service-contract reference.
5534    pub fn from_reference(reference: impl Into<String>) -> Self {
5535        Self {
5536            payload_reference: Some(reference.into()),
5537            ..Self::default()
5538        }
5539    }
5540
5541    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5542        self.item_type = Some(item_type.into());
5543        self
5544    }
5545
5546    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5547        self.content_type = Some(content_type.into());
5548        self
5549    }
5550
5551    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5552        self.idempotency_key = Some(idempotency_key.into());
5553        self
5554    }
5555
5556    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5557        let mut item = serde_json::Map::new();
5558        if let Some(payload) = &self.payload_envelope {
5559            item.insert("payload".to_string(), payload.clone());
5560            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5561        }
5562        if let Some(reference) = &self.payload_reference {
5563            item.insert("payload_reference".to_string(), json!(reference));
5564        }
5565        if let Some(item_type) = &self.item_type {
5566            item.insert("item_type".to_string(), json!(item_type));
5567        }
5568        if let Some(content_type) = &self.content_type {
5569            item.insert("content_type".to_string(), json!(content_type));
5570        }
5571        if let Some(key) = derived_idempotency_key
5572            .as_ref()
5573            .or(self.idempotency_key.as_ref())
5574        {
5575            item.insert("idempotency_key".to_string(), json!(key));
5576        }
5577        Value::Object(item)
5578    }
5579}
5580
5581/// One durable item at its stable zero-based offset.
5582#[derive(Clone, Debug)]
5583pub struct WorkflowStreamItem {
5584    pub offset: u64,
5585    pub payload: Option<Value>,
5586    pub payload_envelope: Option<Value>,
5587    pub payload_reference: Option<String>,
5588    pub payload_codec: Option<String>,
5589    pub idempotency_key: Option<String>,
5590    pub item_type: Option<String>,
5591    pub content_type: Option<String>,
5592    pub origin: Option<String>,
5593    pub origin_reference: Option<String>,
5594    pub emitted_at: Option<String>,
5595    pub raw: Value,
5596}
5597
5598/// One bounded at-least-once subscription page.
5599#[derive(Clone, Debug)]
5600pub struct WorkflowStreamPage {
5601    pub stream: WorkflowStreamDescription,
5602    pub items: Vec<WorkflowStreamItem>,
5603    pub next_offset: u64,
5604    pub terminal: bool,
5605}
5606
5607/// Durable acceptance and deduplication outcome for an append request.
5608#[derive(Clone, Debug)]
5609pub struct WorkflowStreamAppendResult {
5610    pub stream: WorkflowStreamDescription,
5611    pub accepted_offsets: Vec<u64>,
5612    pub accepted: u64,
5613    pub deduped: u64,
5614}
5615
5616#[derive(Deserialize)]
5617struct WorkflowStreamListResponse {
5618    #[serde(default)]
5619    streams: Vec<WorkflowStreamDescription>,
5620}
5621
5622#[derive(Deserialize)]
5623struct WorkflowStreamDescriptionResponse {
5624    stream: WorkflowStreamDescription,
5625}
5626
5627#[derive(Deserialize)]
5628struct WorkflowStreamPageResponse {
5629    stream: WorkflowStreamDescription,
5630    #[serde(default)]
5631    items: Vec<Value>,
5632    next_offset: u64,
5633    terminal: bool,
5634}
5635
5636#[derive(Deserialize)]
5637struct WorkflowStreamAppendResponse {
5638    stream: WorkflowStreamDescription,
5639    #[serde(default)]
5640    accepted_offsets: Vec<u64>,
5641    accepted: u64,
5642    deduped: u64,
5643}
5644
5645impl WorkflowDescription {
5646    pub fn is_completed(&self) -> bool {
5647        matches!(self.status.as_deref(), Some("completed" | "Completed"))
5648    }
5649
5650    pub fn is_terminal(&self) -> bool {
5651        matches!(
5652            self.status.as_deref(),
5653            Some(
5654                "completed"
5655                    | "Completed"
5656                    | "failed"
5657                    | "Failed"
5658                    | "cancelled"
5659                    | "Cancelled"
5660                    | "terminated"
5661                    | "Terminated"
5662                    | "timed_out"
5663                    | "TimedOut",
5664            )
5665        )
5666    }
5667
5668    fn decode_payloads(&mut self) -> Result<()> {
5669        if let Some(envelope) = &self.output_envelope {
5670            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
5671            self.output = Some(value.clone().into_json()?);
5672            self.output_avro_value = Some(value);
5673        }
5674
5675        Ok(())
5676    }
5677
5678    fn raw_value(&self) -> Value {
5679        let mut data = self.raw.clone();
5680        data.insert(
5681            "workflow_id".to_string(),
5682            self.workflow_id
5683                .clone()
5684                .map(Value::String)
5685                .unwrap_or(Value::Null),
5686        );
5687        data.insert(
5688            "run_id".to_string(),
5689            self.run_id
5690                .clone()
5691                .map(Value::String)
5692                .unwrap_or(Value::Null),
5693        );
5694        data.insert(
5695            "workflow_type".to_string(),
5696            self.workflow_type
5697                .clone()
5698                .map(Value::String)
5699                .unwrap_or(Value::Null),
5700        );
5701        data.insert(
5702            "status".to_string(),
5703            self.status
5704                .clone()
5705                .map(Value::String)
5706                .unwrap_or(Value::Null),
5707        );
5708        data.insert(
5709            "closed_reason".to_string(),
5710            self.closed_reason
5711                .clone()
5712                .map(Value::String)
5713                .unwrap_or(Value::Null),
5714        );
5715        if let Some(failure) = &self.failure {
5716            data.insert("failure".to_string(), failure.clone());
5717        }
5718        if let Some(exception) = &self.exception {
5719            data.insert("exception".to_string(), exception.clone());
5720        }
5721        Value::Object(data.into_iter().collect())
5722    }
5723}
5724
5725fn workflow_terminal_outcome(
5726    description: &WorkflowDescription,
5727    workflow_id: &str,
5728    run_id: Option<&str>,
5729) -> WorkflowTerminalOutcome {
5730    let terminal_kind = description
5731        .closed_reason
5732        .as_deref()
5733        .or(description.status.as_deref())
5734        .unwrap_or("failed")
5735        .to_ascii_lowercase();
5736    let kind = match terminal_kind.as_str() {
5737        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
5738        "terminated" => WorkflowTerminalKind::Terminated,
5739        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
5740        _ => WorkflowTerminalKind::Failed,
5741    };
5742    let default_reason = match kind {
5743        WorkflowTerminalKind::Failed => "workflow_failed",
5744        WorkflowTerminalKind::Cancelled => "cancelled",
5745        WorkflowTerminalKind::Terminated => "terminated",
5746        WorkflowTerminalKind::TimedOut => "timed_out",
5747    };
5748    let failure = description
5749        .failure
5750        .as_ref()
5751        .filter(|value| value.is_object());
5752    let nested_failure = failure
5753        .and_then(|value| value.get("failures"))
5754        .and_then(Value::as_array)
5755        .and_then(|failures| failures.last())
5756        .or_else(|| description.failures.last());
5757    let exception = description
5758        .exception
5759        .clone()
5760        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
5761        .or_else(|| {
5762            nested_failure
5763                .and_then(|value| value.get("exception_payload"))
5764                .cloned()
5765        });
5766    let string_field = |name: &str| {
5767        failure
5768            .and_then(|value| value.get(name))
5769            .and_then(Value::as_str)
5770            .or_else(|| {
5771                nested_failure
5772                    .and_then(|value| value.get(name))
5773                    .and_then(Value::as_str)
5774            })
5775            .map(str::to_string)
5776    };
5777    let exception_field = |name: &str| {
5778        exception
5779            .as_ref()
5780            .and_then(|value| value.get(name))
5781            .and_then(Value::as_str)
5782            .map(str::to_string)
5783    };
5784    let message = description
5785        .error
5786        .clone()
5787        .or_else(|| string_field("message"))
5788        .or_else(|| exception_field("message"));
5789    let reason = description
5790        .raw
5791        .get("reason")
5792        .and_then(Value::as_str)
5793        .map(str::to_string)
5794        .or_else(|| {
5795            failure
5796                .and_then(|value| value.get("reason"))
5797                .and_then(Value::as_str)
5798                .map(str::to_string)
5799        })
5800        .or_else(|| description.closed_reason.clone())
5801        .unwrap_or_else(|| default_reason.to_string());
5802    let failure_id = string_field("failure_id").or_else(|| {
5803        nested_failure
5804            .and_then(|value| value.get("id"))
5805            .and_then(Value::as_str)
5806            .map(str::to_string)
5807    });
5808
5809    WorkflowTerminalOutcome {
5810        kind,
5811        workflow_id: description
5812            .workflow_id
5813            .clone()
5814            .unwrap_or_else(|| workflow_id.to_string()),
5815        run_id: description
5816            .run_id
5817            .clone()
5818            .or_else(|| run_id.map(str::to_string)),
5819        reason,
5820        failure_category: string_field("failure_category")
5821            .or_else(|| Some(default_reason.to_string())),
5822        failure_id,
5823        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
5824        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
5825        non_retryable: failure
5826            .and_then(|value| value.get("non_retryable"))
5827            .and_then(Value::as_bool)
5828            .or_else(|| {
5829                nested_failure
5830                    .and_then(|value| value.get("non_retryable"))
5831                    .and_then(Value::as_bool)
5832            }),
5833        message,
5834        exception,
5835        raw: description.raw_value(),
5836    }
5837}
5838
5839#[derive(Clone, Debug, Deserialize)]
5840pub struct RegisterWorkerResponse {
5841    pub worker_id: String,
5842    pub registered: bool,
5843    #[serde(default)]
5844    pub heartbeat_interval_seconds: Option<u64>,
5845    #[serde(default)]
5846    pub protocol_version: Option<String>,
5847    #[serde(default)]
5848    pub server_capabilities: Option<Value>,
5849}
5850
5851/// Result of gracefully removing a worker-plane registration.
5852#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5853pub struct WorkerDeregistrationEnvelope {
5854    pub worker_id: String,
5855    pub outcome: String,
5856    pub recovered_workflow_task_count: u64,
5857}
5858
5859#[derive(Clone, Debug, Deserialize)]
5860pub struct PollWorkflowTaskResponse {
5861    #[serde(default)]
5862    pub task: Option<WorkflowTask>,
5863    #[serde(default)]
5864    pub poll_status: Option<String>,
5865    #[serde(default)]
5866    pub reason: Option<String>,
5867    #[serde(default)]
5868    pub protocol_version: Option<String>,
5869    #[serde(default)]
5870    pub server_capabilities: Option<Value>,
5871}
5872
5873impl PollWorkflowTaskResponse {
5874    /// Classify this response without parsing server display text.
5875    pub fn outcome(&self) -> WorkerPollOutcome {
5876        worker_poll_outcome(
5877            self.task.is_some(),
5878            self.poll_status.as_deref(),
5879            self.reason.as_deref(),
5880        )
5881    }
5882}
5883
5884fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
5885    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
5886        return false;
5887    };
5888    let supported = capabilities
5889        .get("workflow_memo_updates")
5890        .and_then(Value::as_object)
5891        .and_then(|memo| memo.get("supported"))
5892        .and_then(Value::as_bool)
5893        == Some(true);
5894    let command_advertised = capabilities
5895        .get("supported_workflow_task_commands")
5896        .and_then(Value::as_array)
5897        .is_some_and(|commands| {
5898            commands
5899                .iter()
5900                .any(|command| command.as_str() == Some("upsert_memo"))
5901        });
5902    supported && command_advertised
5903}
5904
5905fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
5906    commands
5907        .iter()
5908        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
5909}
5910
5911#[derive(Clone, Debug, Deserialize)]
5912pub struct PollActivityTaskResponse {
5913    #[serde(default)]
5914    pub task: Option<ActivityTask>,
5915    #[serde(default)]
5916    pub poll_status: Option<String>,
5917    #[serde(default)]
5918    pub reason: Option<String>,
5919}
5920
5921impl PollActivityTaskResponse {
5922    /// Classify this response without parsing server display text.
5923    pub fn outcome(&self) -> WorkerPollOutcome {
5924        worker_poll_outcome(
5925            self.task.is_some(),
5926            self.poll_status.as_deref(),
5927            self.reason.as_deref(),
5928        )
5929    }
5930}
5931
5932#[derive(Clone, Debug, Deserialize)]
5933pub struct PollQueryTaskResponse {
5934    #[serde(default)]
5935    pub task: Option<QueryTask>,
5936    #[serde(default)]
5937    pub poll_status: Option<String>,
5938    #[serde(default)]
5939    pub reason: Option<String>,
5940}
5941
5942impl PollQueryTaskResponse {
5943    /// Classify this response without parsing server display text.
5944    pub fn outcome(&self) -> WorkerPollOutcome {
5945        worker_poll_outcome(
5946            self.task.is_some(),
5947            self.poll_status.as_deref(),
5948            self.reason.as_deref(),
5949        )
5950    }
5951}
5952
5953/// Stable classification for worker poll responses.
5954#[derive(Clone, Debug, PartialEq, Eq)]
5955pub enum WorkerPollOutcome {
5956    /// A task was leased and is available on the response.
5957    Task,
5958    /// No task was leased, but the worker should continue polling.
5959    Idle {
5960        poll_status: Option<String>,
5961        reason: Option<String>,
5962    },
5963    /// The server asked this worker to stop claiming new work.
5964    Stop {
5965        poll_status: Option<String>,
5966        reason: Option<String>,
5967    },
5968}
5969
5970impl WorkerPollOutcome {
5971    pub fn should_stop(&self) -> bool {
5972        matches!(self, Self::Stop { .. })
5973    }
5974}
5975
5976fn worker_poll_outcome(
5977    has_task: bool,
5978    poll_status: Option<&str>,
5979    reason: Option<&str>,
5980) -> WorkerPollOutcome {
5981    if worker_poll_is_stop(poll_status, reason) {
5982        return WorkerPollOutcome::Stop {
5983            poll_status: poll_status.map(str::to_string),
5984            reason: reason.map(str::to_string),
5985        };
5986    }
5987
5988    if has_task {
5989        WorkerPollOutcome::Task
5990    } else {
5991        WorkerPollOutcome::Idle {
5992            poll_status: poll_status.map(str::to_string),
5993            reason: reason.map(str::to_string),
5994        }
5995    }
5996}
5997
5998/// An ephemeral server-routed query task.
5999#[derive(Clone, Debug, Deserialize)]
6000pub struct QueryTask {
6001    pub query_task_id: String,
6002    #[serde(default = "default_workflow_task_attempt")]
6003    pub query_task_attempt: u64,
6004    #[serde(default)]
6005    pub lease_owner: Option<String>,
6006    #[serde(default)]
6007    pub workflow_id: Option<String>,
6008    #[serde(default)]
6009    pub run_id: Option<String>,
6010    pub workflow_type: String,
6011    pub query_name: 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 workflow_arguments: Option<Value>,
6019    #[serde(default)]
6020    pub query_arguments: Option<Value>,
6021    #[serde(default)]
6022    pub history_events: Vec<HistoryEvent>,
6023    #[serde(default)]
6024    pub history_export: Option<Value>,
6025    #[serde(default)]
6026    pub run_status: Option<String>,
6027}
6028
6029#[derive(Clone, Debug, Deserialize)]
6030pub struct WorkflowTask {
6031    pub task_id: String,
6032    #[serde(default)]
6033    pub workflow_command_id: Option<String>,
6034    #[serde(default)]
6035    pub workflow_id: Option<String>,
6036    #[serde(default)]
6037    pub run_id: Option<String>,
6038    pub workflow_type: String,
6039    #[serde(default)]
6040    pub cancel_requested: bool,
6041    #[serde(
6042        default = "missing_task_payload_codec",
6043        deserialize_with = "deserialize_task_payload_codec"
6044    )]
6045    pub payload_codec: String,
6046    #[serde(default)]
6047    pub arguments: Option<Value>,
6048    #[serde(default)]
6049    pub history_events: Vec<HistoryEvent>,
6050    #[serde(default)]
6051    pub total_history_events: Option<u64>,
6052    #[serde(default)]
6053    pub history_size_bytes: Option<u64>,
6054    #[serde(default)]
6055    pub continue_as_new_recommended: Option<bool>,
6056    #[serde(default)]
6057    pub history_budget_pressure: Option<String>,
6058    #[serde(default)]
6059    pub next_history_page_token: Option<String>,
6060    #[serde(default = "default_workflow_task_attempt")]
6061    pub workflow_task_attempt: u64,
6062    #[serde(default)]
6063    pub workflow_signal_id: Option<String>,
6064    #[serde(default)]
6065    pub signal_name: Option<String>,
6066    #[serde(default)]
6067    pub signal_arguments: Option<Value>,
6068    #[serde(default)]
6069    pub workflow_update_id: Option<String>,
6070    #[serde(default)]
6071    pub update_name: Option<String>,
6072    #[serde(default)]
6073    pub lease_owner: Option<String>,
6074}
6075
6076impl WorkflowTask {
6077    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6078        self.history_events.extend(page.history_events);
6079
6080        if page.total_history_events.is_some() {
6081            self.total_history_events = page.total_history_events;
6082        }
6083
6084        self.next_history_page_token = page
6085            .next_history_page_token
6086            .filter(|token| !token.is_empty());
6087    }
6088}
6089
6090#[derive(Clone, Debug, Deserialize)]
6091struct WorkflowTaskHistoryPage {
6092    #[serde(default)]
6093    history_events: Vec<HistoryEvent>,
6094    #[serde(default)]
6095    total_history_events: Option<u64>,
6096    #[serde(default)]
6097    next_history_page_token: Option<String>,
6098}
6099
6100#[derive(Clone, Debug, Deserialize)]
6101pub struct ActivityTask {
6102    pub task_id: String,
6103    #[serde(default)]
6104    pub activity_attempt_id: Option<String>,
6105    #[serde(default)]
6106    pub attempt_id: Option<String>,
6107    pub activity_type: String,
6108    #[serde(
6109        default = "missing_task_payload_codec",
6110        deserialize_with = "deserialize_task_payload_codec"
6111    )]
6112    pub payload_codec: String,
6113    #[serde(default)]
6114    pub arguments: Option<Value>,
6115    #[serde(default = "default_attempt_number")]
6116    pub attempt_number: u64,
6117    #[serde(default)]
6118    pub lease_owner: Option<String>,
6119}
6120
6121#[derive(Clone, Debug, Deserialize)]
6122pub struct HistoryEvent {
6123    #[serde(alias = "type")]
6124    pub event_type: String,
6125    #[serde(default)]
6126    pub payload: Value,
6127    #[serde(flatten)]
6128    pub raw: HashMap<String, Value>,
6129}
6130
6131/// One decoded signal in the committed workflow-history snapshot.
6132#[derive(Clone, Debug, PartialEq)]
6133pub struct QuerySignal {
6134    pub id: Option<String>,
6135    pub name: String,
6136    pub arguments: Vec<Value>,
6137    avro_arguments: Vec<AvroValue>,
6138    pub workflow_sequence: Option<u64>,
6139}
6140
6141impl QuerySignal {
6142    /// Lossless fixed Avro Value arguments for this committed signal.
6143    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6144        &self.avro_arguments
6145    }
6146}
6147
6148/// Immutable state supplied to a registered query handler.
6149///
6150/// This context intentionally exposes no activity, signal-wait, or command
6151/// APIs. Query handlers inspect committed history and return a value; query
6152/// completion does not append an event or advance deterministic execution.
6153#[derive(Clone, Debug)]
6154pub struct QueryContext {
6155    pub workflow_id: Option<String>,
6156    pub run_id: Option<String>,
6157    pub workflow_type: String,
6158    pub run_status: Option<String>,
6159    workflow_input: Value,
6160    workflow_input_avro_value: AvroValue,
6161    history_events: Arc<Vec<HistoryEvent>>,
6162    signal_events: Arc<Vec<QuerySignal>>,
6163}
6164
6165impl QueryContext {
6166    /// The normalized argument list used to start the workflow.
6167    pub fn workflow_input(&self) -> &Value {
6168        &self.workflow_input
6169    }
6170
6171    /// The lossless fixed Avro Value argument list used to start the workflow.
6172    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6173        &self.workflow_input_avro_value
6174    }
6175
6176    /// The immutable committed history used for this query snapshot.
6177    pub fn history_events(&self) -> &[HistoryEvent] {
6178        self.history_events.as_slice()
6179    }
6180
6181    /// All decoded signals in committed workflow order.
6182    pub fn signal_events(&self) -> &[QuerySignal] {
6183        self.signal_events.as_slice()
6184    }
6185
6186    /// Decoded argument lists for each committed signal with `signal_name`.
6187    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6188        self.signal_events
6189            .iter()
6190            .filter(|signal| signal.name == signal_name)
6191            .map(|signal| signal.arguments.clone())
6192            .collect()
6193    }
6194
6195    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6196    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6197        self.signal_events
6198            .iter()
6199            .filter(|signal| signal.name == signal_name)
6200            .map(|signal| signal.avro_arguments.clone())
6201            .collect()
6202    }
6203}
6204
6205#[derive(Clone, Debug, Deserialize)]
6206pub struct ActivityHeartbeatResponse {
6207    #[serde(default)]
6208    pub cancel_requested: bool,
6209    #[serde(default)]
6210    pub heartbeat_recorded: bool,
6211    #[serde(default)]
6212    pub can_continue: Option<bool>,
6213    #[serde(default)]
6214    pub reason: Option<String>,
6215    #[serde(default)]
6216    pub run_closed_reason: Option<String>,
6217    #[serde(default)]
6218    pub run_closed_at: Option<String>,
6219    #[serde(default)]
6220    pub lease_expires_at: Option<String>,
6221    #[serde(default)]
6222    pub last_heartbeat_at: Option<String>,
6223}
6224
6225impl ActivityHeartbeatResponse {
6226    /// Whether the activity should stop instead of attempting completion.
6227    pub fn should_stop(&self) -> bool {
6228        self.cancel_requested || self.can_continue == Some(false)
6229    }
6230}
6231
6232fn missing_task_payload_codec() -> String {
6233    MISSING_TASK_PAYLOAD_CODEC.to_string()
6234}
6235
6236fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6237where
6238    D: Deserializer<'de>,
6239{
6240    Ok(match Value::deserialize(deserializer)? {
6241        Value::String(codec) => codec,
6242        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6243        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6244    })
6245}
6246
6247fn default_workflow_task_attempt() -> u64 {
6248    1
6249}
6250
6251fn default_attempt_number() -> u64 {
6252    1
6253}
6254
6255type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6256type WorkflowHandler = Arc<dyn Fn(WorkflowContext, AvroValue) -> WorkflowFuture + Send + Sync>;
6257type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6258type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6259type ReplayedWorkflowHandler =
6260    Arc<dyn Fn(WorkflowContext, AvroValue) -> ReplayedWorkflowInvocation + Send + Sync>;
6261type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6262type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6263type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6264type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6265type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6266type ReplayedQueryHandler = Arc<
6267    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6268        + Send
6269        + Sync,
6270>;
6271type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6272
6273struct ReplayedWorkflowInvocation {
6274    future: WorkflowFuture,
6275    snapshot: WorkflowStateSnapshot,
6276}
6277
6278#[derive(Clone)]
6279struct RegisteredWorkflow {
6280    execute: WorkflowHandler,
6281    replay: Option<ReplayedWorkflowHandler>,
6282    state_type: Option<TypeId>,
6283    definition_fingerprint: Option<String>,
6284}
6285
6286#[derive(Debug)]
6287struct WorkflowTaskDecision {
6288    commands: Vec<Value>,
6289    message_stream_cursors: Vec<Value>,
6290    message_stream_waits: Vec<Value>,
6291    cancellation_delivery: Option<CancellationDelivery>,
6292    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6293    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6294}
6295
6296enum PreparedWorkflowTask {
6297    Decision(WorkflowTaskDecision),
6298    Execution {
6299        task: WorkflowTask,
6300        context: WorkflowContext,
6301        future: WorkflowFuture,
6302    },
6303}
6304
6305impl WorkflowTaskDecision {
6306    fn without_message_streams(commands: Vec<Value>) -> Self {
6307        Self {
6308            commands,
6309            message_stream_cursors: Vec::new(),
6310            message_stream_waits: Vec::new(),
6311            cancellation_delivery: None,
6312            cancellation_scope_opening: None,
6313            cancellation_scope_delivery: None,
6314        }
6315    }
6316}
6317
6318#[derive(Clone)]
6319enum RegisteredQuery {
6320    Snapshot(QueryHandler),
6321    Replayed {
6322        state_type: TypeId,
6323        handler: ReplayedQueryHandler,
6324    },
6325}
6326
6327#[derive(Clone, Debug)]
6328pub struct WorkerHeartbeatObservation {
6329    pub worker_id: String,
6330    pub task_queue: String,
6331    pub acknowledged_at_unix_millis: u64,
6332    pub acknowledgement: Value,
6333}
6334
6335/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6336///
6337/// Expected empty long polls and explicit Server capacity backpressure are
6338/// normal worker states. Capacity backpressure honors the advertised retry
6339/// delay without consuming this retry budget. Other transport failures,
6340/// retryable HTTP 408/429 responses, and server errors are retried with capped
6341/// exponential backoff. Authentication, protocol, codec, and handler failures
6342/// are never retried by the worker.
6343/// Explicit storage admission pauses also preserve the already-serialized worker
6344/// request without consuming this budget or rerunning its handler. The delay is
6345/// capped by `max_backoff`, and shutdown interrupts storage waits.
6346/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6347/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6348/// and `max_retries = 0` disables ordinary retries in either mode.
6349#[derive(Clone, Copy, Debug)]
6350pub struct WorkerRetryPolicy {
6351    /// Number of retries after the initial request fails.
6352    pub max_retries: usize,
6353    /// Delay before the first retry.
6354    pub initial_backoff: Duration,
6355    /// Maximum delay between retries.
6356    pub max_backoff: Duration,
6357}
6358
6359impl Default for WorkerRetryPolicy {
6360    fn default() -> Self {
6361        Self {
6362            max_retries: 5,
6363            initial_backoff: Duration::from_millis(100),
6364            max_backoff: Duration::from_secs(5),
6365        }
6366    }
6367}
6368
6369#[derive(Clone, Debug)]
6370struct WorkerStorageAdmission {
6371    policy: WorkerRetryPolicy,
6372    stop: Arc<AtomicBool>,
6373}
6374
6375struct StopWorkerOnDrop(Arc<AtomicBool>);
6376
6377impl Drop for StopWorkerOnDrop {
6378    fn drop(&mut self) {
6379        self.0.store(true, Ordering::SeqCst);
6380    }
6381}
6382
6383async fn wait_for_worker_stop(stop: &AtomicBool) {
6384    while !stop.load(Ordering::SeqCst) {
6385        tokio::time::sleep(Duration::from_millis(100)).await;
6386    }
6387}
6388
6389#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6390enum ManagedPollOutcome {
6391    Idle,
6392    Handled,
6393    Stop,
6394}
6395
6396#[derive(Clone)]
6397pub struct Worker {
6398    client: Client,
6399    worker_id: String,
6400    task_queue: String,
6401    workflows: HashMap<String, RegisteredWorkflow>,
6402    activities: HashMap<String, ActivityHandler>,
6403    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6404    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6405    max_concurrent_workflow_tasks: usize,
6406    max_concurrent_activity_tasks: usize,
6407    poll_timeout: Duration,
6408    heartbeat_interval: Duration,
6409    retry_policy: WorkerRetryPolicy,
6410    recover_transient_outages: bool,
6411    run_stop: Option<Arc<AtomicBool>>,
6412    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6413    cooperative_cancellation_enabled: bool,
6414    allow_cancellation_scope_authoring: bool,
6415    allow_cancellation_scope_delivery: bool,
6416    cooperative_registration_confirmed: Arc<AtomicBool>,
6417    local_registration_confirmed: Arc<AtomicBool>,
6418    session_registration_confirmed: Arc<AtomicBool>,
6419    resource_capabilities: Vec<String>,
6420    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6421}
6422
6423impl Worker {
6424    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6425        Self {
6426            client,
6427            worker_id: default_worker_id(),
6428            task_queue: task_queue.into(),
6429            workflows: HashMap::new(),
6430            activities: HashMap::new(),
6431            queries: HashMap::new(),
6432            updates: HashMap::new(),
6433            max_concurrent_workflow_tasks: 10,
6434            max_concurrent_activity_tasks: 10,
6435            poll_timeout: Duration::from_secs(30),
6436            heartbeat_interval: Duration::from_secs(60),
6437            retry_policy: WorkerRetryPolicy::default(),
6438            recover_transient_outages: false,
6439            run_stop: None,
6440            heartbeat_observer: None,
6441            cooperative_cancellation_enabled: false,
6442            allow_cancellation_scope_authoring: false,
6443            allow_cancellation_scope_delivery: false,
6444            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6445            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6446            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6447            resource_capabilities: Vec::new(),
6448            sessions: Arc::new(Mutex::new(HashMap::new())),
6449        }
6450    }
6451
6452    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6453        self.worker_id = worker_id.into();
6454        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6455        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6456        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6457        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6458        self
6459    }
6460
6461    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6462        self.poll_timeout = timeout;
6463        self
6464    }
6465
6466    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6467        self.heartbeat_interval = interval;
6468        self
6469    }
6470
6471    /// Explicitly enable inline local activities in this workflow worker.
6472    ///
6473    /// The worker advertises the capability to Server only when enabled.
6474    /// These callbacks must yield to Tokio and have idempotent side effects.
6475    /// Cooperative prepared local supervision is a separate capability.
6476    pub fn local_activities(mut self, enabled: bool) -> Self {
6477        self.client.local_activities_enabled = enabled;
6478        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6479        self
6480    }
6481
6482    /// Opt in to separate cooperative workflow cancellation requests.
6483    ///
6484    /// Registration requires the Server to acknowledge this exact worker,
6485    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6486    /// processing uses canonical delivery and activity ownership fences.
6487    /// Existing terminal cancel and terminate operations remain terminal.
6488    /// The default is disabled, preserving ordinary protocol 1.19 workers.
6489    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6490    /// and [`Worker::run_until`] register automatically.
6491    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6492        self.cooperative_cancellation_enabled = enabled;
6493        self.client.cooperative_worker_protocol = enabled;
6494        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6495        self
6496    }
6497
6498    /// Enable candidate scope authoring without advertising scoped execution.
6499    #[doc(hidden)]
6500    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6501        self.allow_cancellation_scope_authoring = enabled;
6502        self
6503    }
6504
6505    /// Enable the candidate scoped call consumer with canonical authoring.
6506    #[doc(hidden)]
6507    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6508        self.allow_cancellation_scope_delivery = enabled;
6509        self
6510    }
6511
6512    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6513    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6514        self.retry_policy = policy;
6515        self
6516    }
6517
6518    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6519    ///
6520    /// Retries preserve the poll request identity and use capped exponential
6521    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6522    /// An in-flight poll is allowed to finish so leased work is not discarded.
6523    /// Authentication, protocol, codec, handler and task settlement failures
6524    /// remain errors. Registration and deregistration are not retried here.
6525    ///
6526    /// The default is disabled, preserving the bounded retry contract.
6527    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6528    /// even when this option is enabled.
6529    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6530        self.recover_transient_outages = enabled;
6531        self
6532    }
6533
6534    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6535    where
6536        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6537    {
6538        self.heartbeat_observer = Some(Arc::new(observer));
6539        self
6540    }
6541
6542    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6543        self.max_concurrent_workflow_tasks = count.max(1);
6544        self
6545    }
6546
6547    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6548        self.max_concurrent_activity_tasks = count.max(1);
6549        self
6550    }
6551
6552    /// Register a workflow handler.
6553    ///
6554    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6555    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6556    /// while acquiring or decoding a worker task remain worker-operation
6557    /// failures and do not get converted into workflow outcomes.
6558    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6559    where
6560        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6561        Fut: Future<Output = Result<Value>> + Send + 'static,
6562    {
6563        let handler = Arc::new(handler);
6564        self.workflows.insert(
6565            workflow_type.into(),
6566            RegisteredWorkflow {
6567                execute: Arc::new(move |ctx, input| {
6568                    let handler = Arc::clone(&handler);
6569                    Box::pin(async move {
6570                        let result = handler(ctx, input.into_json()?).await?;
6571                        AvroValue::from_serialize(&result)
6572                    })
6573                }),
6574                replay: None,
6575                state_type: None,
6576                definition_fingerprint: None,
6577            },
6578        );
6579    }
6580
6581    /// Register a workflow with one Serde request value and a Serde result.
6582    ///
6583    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
6584    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
6585    /// workflow-specific schema. A task must contain zero arguments for a unit
6586    /// request or exactly one argument for every other request type.
6587    ///
6588    /// See the runnable
6589    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
6590    /// for typed workflow and activity contracts with retry and timeout policy.
6591    pub fn register_typed_workflow<I, O, F, Fut>(
6592        &mut self,
6593        workflow_type: impl Into<String>,
6594        handler: F,
6595    ) where
6596        I: DeserializeOwned + Send + 'static,
6597        O: Serialize + Send + 'static,
6598        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
6599        Fut: Future<Output = Result<O>> + Send + 'static,
6600    {
6601        let workflow_type = workflow_type.into();
6602        let handler_name = workflow_type.clone();
6603        let handler = Arc::new(handler);
6604        self.workflows.insert(
6605            workflow_type,
6606            RegisteredWorkflow {
6607                execute: Arc::new(move |ctx, input| {
6608                    let handler = Arc::clone(&handler);
6609                    let handler_name = handler_name.clone();
6610                    Box::pin(async move {
6611                        let input =
6612                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6613                        let result = handler(ctx, input).await?;
6614                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6615                    })
6616                }),
6617                replay: None,
6618                state_type: None,
6619                definition_fingerprint: None,
6620            },
6621        );
6622    }
6623
6624    /// Register a workflow on the lossless fixed Avro Value surface.
6625    pub fn register_workflow_avro_value<F, Fut>(
6626        &mut self,
6627        workflow_type: impl Into<String>,
6628        handler: F,
6629    ) where
6630        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
6631        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6632    {
6633        self.workflows.insert(
6634            workflow_type.into(),
6635            RegisteredWorkflow {
6636                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
6637                replay: None,
6638                state_type: None,
6639                definition_fingerprint: None,
6640            },
6641        );
6642    }
6643
6644    /// Register a workflow whose typed instance state can be reconstructed for queries.
6645    ///
6646    /// `state_factory` creates a fresh instance for every normal workflow task and
6647    /// query replay. The workflow handler is the single source of truth for state
6648    /// transitions: it updates [`WorkflowInstance`] after activities and signals
6649    /// resolve. Query replay runs this same handler over committed history and
6650    /// discards any commands it would emit.
6651    pub fn register_replayed_workflow<S, Factory, F, Fut>(
6652        &mut self,
6653        workflow_type: impl Into<String>,
6654        state_factory: Factory,
6655        handler: F,
6656    ) where
6657        S: Clone + Send + Sync + 'static,
6658        Factory: Fn() -> S + Send + Sync + 'static,
6659        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6660        Fut: Future<Output = Result<Value>> + Send + 'static,
6661    {
6662        let state_factory = Arc::new(state_factory);
6663        let handler = Arc::new(handler);
6664
6665        let execute_factory = Arc::clone(&state_factory);
6666        let execute_handler = Arc::clone(&handler);
6667        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6668            let state = WorkflowInstance::new(execute_factory());
6669            let handler = Arc::clone(&execute_handler);
6670            Box::pin(async move {
6671                let result = handler(ctx, input.into_json()?, state).await?;
6672                AvroValue::from_serialize(&result)
6673            }) as WorkflowFuture
6674        });
6675
6676        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6677            let state = WorkflowInstance::new(state_factory());
6678            let snapshot_state = state.clone();
6679            let snapshot: WorkflowStateSnapshot =
6680                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6681            let replay_handler = Arc::clone(&handler);
6682            let future = async move {
6683                let result = replay_handler(ctx, input.into_json()?, state).await?;
6684                AvroValue::from_serialize(&result)
6685            };
6686            ReplayedWorkflowInvocation {
6687                future: Box::pin(future),
6688                snapshot,
6689            }
6690        });
6691
6692        self.workflows.insert(
6693            workflow_type.into(),
6694            RegisteredWorkflow {
6695                execute,
6696                replay: Some(replay),
6697                state_type: Some(TypeId::of::<S>()),
6698                definition_fingerprint: None,
6699            },
6700        );
6701    }
6702
6703    /// Register a replayable workflow with one Serde request value and result.
6704    ///
6705    /// Normal task execution and instance-state query replay both decode and
6706    /// encode through the fixed Avro Value codec. The state factory and handler
6707    /// otherwise follow [`Worker::register_replayed_workflow`].
6708    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
6709        &mut self,
6710        workflow_type: impl Into<String>,
6711        state_factory: Factory,
6712        handler: F,
6713    ) where
6714        I: DeserializeOwned + Send + 'static,
6715        O: Serialize + Send + 'static,
6716        S: Clone + Send + Sync + 'static,
6717        Factory: Fn() -> S + Send + Sync + 'static,
6718        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6719        Fut: Future<Output = Result<O>> + Send + 'static,
6720    {
6721        let workflow_type = workflow_type.into();
6722        let state_factory = Arc::new(state_factory);
6723        let handler = Arc::new(handler);
6724
6725        let execute_name = workflow_type.clone();
6726        let execute_factory = Arc::clone(&state_factory);
6727        let execute_handler = Arc::clone(&handler);
6728        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6729            let state = WorkflowInstance::new(execute_factory());
6730            let handler = Arc::clone(&execute_handler);
6731            let handler_name = execute_name.clone();
6732            Box::pin(async move {
6733                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6734                let result = handler(ctx, input, state).await?;
6735                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6736            }) as WorkflowFuture
6737        });
6738
6739        let replay_name = workflow_type.clone();
6740        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6741            let state = WorkflowInstance::new(state_factory());
6742            let snapshot_state = state.clone();
6743            let snapshot: WorkflowStateSnapshot =
6744                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6745            let handler = Arc::clone(&handler);
6746            let handler_name = replay_name.clone();
6747            let future = async move {
6748                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6749                let result = handler(ctx, input, state).await?;
6750                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6751            };
6752            ReplayedWorkflowInvocation {
6753                future: Box::pin(future),
6754                snapshot,
6755            }
6756        });
6757
6758        self.workflows.insert(
6759            workflow_type,
6760            RegisteredWorkflow {
6761                execute,
6762                replay: Some(replay),
6763                state_type: Some(TypeId::of::<S>()),
6764                definition_fingerprint: None,
6765            },
6766        );
6767    }
6768
6769    /// Bind a registered workflow to compile-time embedded source for safe redrive.
6770    ///
6771    /// Supply `include_str!` values for the workflow body and every helper whose
6772    /// behavior can affect replay. A handler re-registration clears the local
6773    /// identity; call this after registering the final handler. The server
6774    /// rejects reusing a worker ID when its prior fingerprint disappears.
6775    /// Workflows without source identity remain runnable but cannot be safely redriven.
6776    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
6777    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
6778    pub fn set_workflow_definition_sources(
6779        &mut self,
6780        workflow_type: &str,
6781        sources: &[&str],
6782    ) -> Result<()> {
6783        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
6784            return Err(Error::Codec(
6785                "workflow definition sources must be non-empty".to_string(),
6786            ));
6787        }
6788        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
6789            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
6790        })?;
6791        let mut hasher = Sha256::new();
6792        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
6793        hasher.update((workflow_type.len() as u64).to_be_bytes());
6794        hasher.update(workflow_type.as_bytes());
6795        for source in sources {
6796            hasher.update((source.len() as u64).to_be_bytes());
6797            hasher.update(source.as_bytes());
6798        }
6799        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
6800        Ok(())
6801    }
6802
6803    /// Register a replayable workflow on the lossless fixed Avro Value surface.
6804    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
6805        &mut self,
6806        workflow_type: impl Into<String>,
6807        state_factory: Factory,
6808        handler: F,
6809    ) where
6810        S: Clone + Send + Sync + 'static,
6811        Factory: Fn() -> S + Send + Sync + 'static,
6812        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6813        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6814    {
6815        let state_factory = Arc::new(state_factory);
6816        let handler = Arc::new(handler);
6817
6818        let execute_factory = Arc::clone(&state_factory);
6819        let execute_handler = Arc::clone(&handler);
6820        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6821            let state = WorkflowInstance::new(execute_factory());
6822            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
6823        });
6824
6825        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6826            let state = WorkflowInstance::new(state_factory());
6827            let snapshot_state = state.clone();
6828            let snapshot: WorkflowStateSnapshot =
6829                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6830            ReplayedWorkflowInvocation {
6831                future: Box::pin(handler(ctx, input, state)),
6832                snapshot,
6833            }
6834        });
6835
6836        self.workflows.insert(
6837            workflow_type.into(),
6838            RegisteredWorkflow {
6839                execute,
6840                replay: Some(replay),
6841                state_type: Some(TypeId::of::<S>()),
6842                definition_fingerprint: None,
6843            },
6844        );
6845    }
6846
6847    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
6848    where
6849        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
6850        Fut: Future<Output = Result<Value>> + Send + 'static,
6851    {
6852        let handler = Arc::new(handler);
6853        self.activities.insert(
6854            activity_type.into(),
6855            Arc::new(move |ctx, args| {
6856                let handler = Arc::clone(&handler);
6857                Box::pin(async move {
6858                    let result = handler(ctx, args.into_json()?).await?;
6859                    AvroValue::from_serialize(&result)
6860                })
6861            }),
6862        );
6863    }
6864
6865    /// Register an activity with one Serde request value and a Serde result.
6866    ///
6867    /// Inputs and results use the platform's fixed Avro Value schema. Shape
6868    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
6869    /// with the activity name and Rust type.
6870    pub fn register_typed_activity<I, O, F, Fut>(
6871        &mut self,
6872        activity_type: impl Into<String>,
6873        handler: F,
6874    ) where
6875        I: DeserializeOwned + Send + 'static,
6876        O: Serialize + Send + 'static,
6877        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
6878        Fut: Future<Output = Result<O>> + Send + 'static,
6879    {
6880        let activity_type = activity_type.into();
6881        let handler_name = activity_type.clone();
6882        let handler = Arc::new(handler);
6883        self.activities.insert(
6884            activity_type,
6885            Arc::new(move |ctx, input| {
6886                let handler = Arc::clone(&handler);
6887                let handler_name = handler_name.clone();
6888                Box::pin(async move {
6889                    let input =
6890                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
6891                    let result = handler(ctx, input).await?;
6892                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
6893                })
6894            }),
6895        );
6896    }
6897
6898    /// Register an activity on the lossless fixed Avro Value surface.
6899    pub fn register_activity_avro_value<F, Fut>(
6900        &mut self,
6901        activity_type: impl Into<String>,
6902        handler: F,
6903    ) where
6904        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
6905        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6906    {
6907        self.activities.insert(
6908            activity_type.into(),
6909            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
6910        );
6911    }
6912
6913    /// Register a named, read-only query handler for a workflow type.
6914    ///
6915    /// The workflow type must also be registered with [`Worker::register_workflow`]
6916    /// before the worker runs. The handler receives only an immutable committed
6917    /// state snapshot and normalized query arguments.
6918    pub fn register_query<F, Fut>(
6919        &mut self,
6920        workflow_type: impl Into<String>,
6921        query_name: impl Into<String>,
6922        handler: F,
6923    ) where
6924        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
6925        Fut: Future<Output = Result<Value>> + Send + 'static,
6926    {
6927        let handler = Arc::new(handler);
6928        self.queries
6929            .entry(workflow_type.into())
6930            .or_default()
6931            .insert(
6932                query_name.into(),
6933                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
6934                    let handler = Arc::clone(&handler);
6935                    Box::pin(async move {
6936                        let result = handler(ctx, args.into_json()?).await?;
6937                        AvroValue::from_serialize(&result)
6938                    })
6939                })),
6940            );
6941    }
6942
6943    /// Register a query handler on the lossless fixed Avro Value surface.
6944    pub fn register_query_avro_value<F, Fut>(
6945        &mut self,
6946        workflow_type: impl Into<String>,
6947        query_name: impl Into<String>,
6948        handler: F,
6949    ) where
6950        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
6951        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6952    {
6953        self.queries
6954            .entry(workflow_type.into())
6955            .or_default()
6956            .insert(
6957                query_name.into(),
6958                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
6959            );
6960    }
6961
6962    /// Register a named query against deterministically replayed instance state.
6963    ///
6964    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
6965    /// same state type `S`. The handler receives an immutable, detached state
6966    /// clone, so successful and failed queries cannot affect workflow execution
6967    /// or the state reconstructed by a later query.
6968    pub fn register_replayed_query<S, F, Fut>(
6969        &mut self,
6970        workflow_type: impl Into<String>,
6971        query_name: impl Into<String>,
6972        handler: F,
6973    ) where
6974        S: Clone + Send + Sync + 'static,
6975        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
6976        Fut: Future<Output = Result<Value>> + Send + 'static,
6977    {
6978        let handler = Arc::new(handler);
6979        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
6980            let state = state.downcast::<S>().map_err(|_| {
6981                "registered query state type does not match the replayed workflow state".to_string()
6982            })?;
6983            let handler = Arc::clone(&handler);
6984            Ok(Box::pin(async move {
6985                let result = handler(ctx, state, args.into_json()?).await?;
6986                AvroValue::from_serialize(&result)
6987            }))
6988        });
6989
6990        self.queries
6991            .entry(workflow_type.into())
6992            .or_default()
6993            .insert(
6994                query_name.into(),
6995                RegisteredQuery::Replayed {
6996                    state_type: TypeId::of::<S>(),
6997                    handler: erased_handler,
6998                },
6999            );
7000    }
7001
7002    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7003    pub fn register_replayed_query_avro_value<S, F, Fut>(
7004        &mut self,
7005        workflow_type: impl Into<String>,
7006        query_name: impl Into<String>,
7007        handler: F,
7008    ) where
7009        S: Clone + Send + Sync + 'static,
7010        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7011        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7012    {
7013        let handler = Arc::new(handler);
7014        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7015            let state = state.downcast::<S>().map_err(|_| {
7016                "registered query state type does not match the replayed workflow state".to_string()
7017            })?;
7018            Ok(Box::pin(handler(ctx, state, args)))
7019        });
7020
7021        self.queries
7022            .entry(workflow_type.into())
7023            .or_default()
7024            .insert(
7025                query_name.into(),
7026                RegisteredQuery::Replayed {
7027                    state_type: TypeId::of::<S>(),
7028                    handler: erased_handler,
7029                },
7030            );
7031    }
7032
7033    /// Register a synchronous workflow update handler.
7034    pub fn register_update<F, Fut>(
7035        &mut self,
7036        workflow_type: impl Into<String>,
7037        update_name: impl Into<String>,
7038        handler: F,
7039    ) where
7040        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7041        Fut: Future<Output = Result<Value>> + Send + 'static,
7042    {
7043        let handler = Arc::new(handler);
7044        self.updates
7045            .entry(workflow_type.into())
7046            .or_default()
7047            .insert(
7048                update_name.into(),
7049                Arc::new(move |ctx, args| {
7050                    let handler = Arc::clone(&handler);
7051                    Box::pin(async move {
7052                        let result = handler(ctx, args.into_json()?).await?;
7053                        AvroValue::from_serialize(&result)
7054                    })
7055                }),
7056            );
7057    }
7058
7059    /// Register an update handler on the lossless fixed Avro Value surface.
7060    pub fn register_update_avro_value<F, Fut>(
7061        &mut self,
7062        workflow_type: impl Into<String>,
7063        update_name: impl Into<String>,
7064        handler: F,
7065    ) where
7066        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7067        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7068    {
7069        self.updates
7070            .entry(workflow_type.into())
7071            .or_default()
7072            .insert(
7073                update_name.into(),
7074                Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7075            );
7076    }
7077
7078    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7079        self.session_registration_confirmed
7080            .store(false, Ordering::SeqCst);
7081        for capability in &self.resource_capabilities {
7082            worker_session::validate_resource_capability(capability)?;
7083        }
7084        self.local_registration_confirmed
7085            .store(false, Ordering::SeqCst);
7086        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7087            return Err(Error::CooperativeCancellationUnavailable(
7088                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7089            ));
7090        }
7091        let mut command_contracts = serde_json::Map::new();
7092        for workflow_type in self.workflows.keys() {
7093            let mut queries = self
7094                .queries
7095                .get(workflow_type)
7096                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7097                .unwrap_or_default();
7098            queries.sort();
7099            let mut updates = self
7100                .updates
7101                .get(workflow_type)
7102                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7103                .unwrap_or_default();
7104            updates.sort();
7105            command_contracts.insert(
7106                workflow_type.clone(),
7107                json!({
7108                    "queries": queries,
7109                    "query_contracts": [],
7110                    "signals": [],
7111                    "signal_contracts": [],
7112                    "updates": updates,
7113                    "update_contracts": [],
7114                    "update_validators": [],
7115                }),
7116            );
7117        }
7118
7119        self.cooperative_registration_confirmed
7120            .store(false, Ordering::SeqCst);
7121        let response = self
7122            .client
7123            .register_worker_with_definition_fingerprints(
7124                &self.worker_id,
7125                &self.task_queue,
7126                self.workflows.keys().cloned().collect(),
7127                self.activities.keys().cloned().collect(),
7128                self.max_concurrent_workflow_tasks,
7129                self.max_concurrent_activity_tasks,
7130                [
7131                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7132                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7133                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7134                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7135                    self.client
7136                        .local_activities_enabled
7137                        .then(|| "local_activities".to_string()),
7138                    self.client
7139                        .worker_sessions_enabled
7140                        .then(|| "worker_sessions".to_string()),
7141                    self.cooperative_cancellation_enabled
7142                        .then(|| "cooperative_cancellation".to_string()),
7143                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7144                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7145                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7146                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7147                ]
7148                .into_iter()
7149                .flatten()
7150                .chain(self.resource_capabilities.iter().cloned())
7151                .collect(),
7152                Value::Object(command_contracts),
7153                Some(
7154                    self.workflows
7155                        .iter()
7156                        .filter_map(|(workflow_type, workflow)| {
7157                            workflow
7158                                .definition_fingerprint
7159                                .as_ref()
7160                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7161                        })
7162                        .collect(),
7163                ),
7164            )
7165            .await?;
7166        if self.cooperative_cancellation_enabled && response.registered {
7167            self.cooperative_registration_confirmed
7168                .store(true, Ordering::SeqCst);
7169        }
7170        if self.client.local_activities_enabled && response.registered {
7171            self.local_registration_confirmed
7172                .store(true, Ordering::SeqCst);
7173        }
7174        if self.client.worker_sessions_enabled && response.registered {
7175            self.session_registration_confirmed
7176                .store(true, Ordering::SeqCst);
7177        }
7178        Ok(response)
7179    }
7180
7181    /// Run until shutdown or a terminal worker error occurs.
7182    ///
7183    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7184    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7185    /// authentication, protocol, and other non-retryable failures are returned.
7186    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7187    /// poll and heartbeat outages beyond the ordinary retry budget.
7188    pub async fn run(&self) -> Result<()> {
7189        self.run_until(std::future::pending::<()>()).await
7190    }
7191
7192    /// Run until `shutdown` resolves or a terminal worker error occurs.
7193    ///
7194    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7195    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7196    where
7197        F: Future<Output = ()>,
7198    {
7199        let stop = Arc::new(AtomicBool::new(false));
7200        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7201        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7202        worker.run_stop = Some(Arc::clone(&stop));
7203        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7204        tokio::pin!(run);
7205        tokio::pin!(shutdown);
7206        tokio::select! {
7207            result = &mut run => result,
7208            _ = &mut shutdown => {
7209                stop.store(true, Ordering::SeqCst);
7210                run.await
7211            }
7212        }
7213    }
7214
7215    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7216        let mut worker = self.clone();
7217        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7218            policy: self.retry_policy,
7219            stop,
7220        });
7221        worker
7222    }
7223
7224    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7225        let registration = self.register().await?;
7226        if !registration.registered {
7227            return Err(Error::WorkerLoop(format!(
7228                "worker registration for {:?} was not accepted",
7229                self.worker_id
7230            )));
7231        }
7232        let registered_worker_id = registration.worker_id.clone();
7233        let primary = self.run_registered_until(stop, registration).await;
7234        let primary = match (primary, self.close_worker_sessions().await) {
7235            (Ok(()), result) => result,
7236            (Err(error), Ok(())) => Err(error),
7237            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7238                primary: Box::new(primary),
7239                deregistration: Box::new(close),
7240            }),
7241        };
7242        self.session_registration_confirmed
7243            .store(false, Ordering::SeqCst);
7244        self.cooperative_registration_confirmed
7245            .store(false, Ordering::SeqCst);
7246        self.local_registration_confirmed
7247            .store(false, Ordering::SeqCst);
7248        let deregistration = self
7249            .client
7250            .deregister_worker_registration(&registered_worker_id)
7251            .await;
7252
7253        match (primary, deregistration) {
7254            (Ok(()), Ok(_)) => Ok(()),
7255            (Ok(()), Err(deregistration)) => Err(deregistration),
7256            (Err(primary), Ok(_)) => Err(primary),
7257            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7258                primary: Box::new(primary),
7259                deregistration: Box::new(deregistration),
7260            }),
7261        }
7262    }
7263
7264    async fn run_registered_until(
7265        &self,
7266        stop: Arc<AtomicBool>,
7267        registration: RegisterWorkerResponse,
7268    ) -> Result<()> {
7269        let heartbeat_interval = Duration::from_secs(
7270            registration
7271                .heartbeat_interval_seconds
7272                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7273        );
7274        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7275        // from the completion of the preceding attempt, including its bounded
7276        // retries. A fixed-epoch interval can leave an already-due tick queued
7277        // while an acknowledgement is slow, producing a catch-up heartbeat as
7278        // soon as that request completes.
7279        let heartbeat = tokio::time::sleep(Duration::ZERO);
7280        tokio::pin!(heartbeat);
7281        // Poll responses may already have leased server-side work by the time
7282        // they become ready, so each poller owns its responses through
7283        // completion or failure instead of racing raw polls in this select.
7284        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7285            let worker = self.clone();
7286            let stop = Arc::clone(&stop);
7287            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7288        });
7289        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7290            let worker = self.clone();
7291            let stop = Arc::clone(&stop);
7292            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7293        });
7294        let mut query_poller = (!self.queries.is_empty()).then(|| {
7295            let worker = self.clone();
7296            let stop = Arc::clone(&stop);
7297            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7298        });
7299
7300        loop {
7301            tokio::select! {
7302                _ = wait_for_worker_stop(&stop) => {
7303                    stop.store(true, Ordering::SeqCst);
7304                    break;
7305                }
7306                _ = &mut heartbeat => {
7307                    let result = self.retry_worker_operation(|| {
7308                        self.client.heartbeat_worker_with_sessions(
7309                            &self.worker_id,
7310                            self.max_concurrent_workflow_tasks,
7311                            self.max_concurrent_activity_tasks,
7312                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7313                        )
7314                    }).await;
7315                    heartbeat
7316                        .as_mut()
7317                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7318                    match result {
7319                        Ok(Some(acknowledgement)) => {
7320                            if let Some(observer) = &self.heartbeat_observer {
7321                                observer(&WorkerHeartbeatObservation {
7322                                    worker_id: self.worker_id.clone(),
7323                                    task_queue: self.task_queue.clone(),
7324                                    acknowledged_at_unix_millis: SystemTime::now()
7325                                        .duration_since(UNIX_EPOCH)
7326                                        .unwrap_or_default()
7327                                        .as_millis()
7328                                        .min(u64::MAX as u128)
7329                                        as u64,
7330                                    acknowledgement,
7331                                });
7332                            }
7333                        }
7334                        Ok(None) => break,
7335                        Err(error) => {
7336                            stop.store(true, Ordering::SeqCst);
7337                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7338                            return Err(error);
7339                        }
7340                    }
7341                }
7342                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7343                    workflow_poller = None;
7344                    let stopped_by_server = stop.load(Ordering::SeqCst);
7345                    stop.store(true, Ordering::SeqCst);
7346                    let poller_result = optional_poller_result("workflow", result);
7347                    let join_result =
7348                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7349                    poller_result?;
7350                    join_result?;
7351                    if stopped_by_server {
7352                        return Ok(());
7353                    }
7354                    return Err(Error::WorkerLoop(
7355                        "workflow poller stopped unexpectedly".to_string(),
7356                    ));
7357                }
7358                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7359                    activity_poller = None;
7360                    let stopped_by_server = stop.load(Ordering::SeqCst);
7361                    stop.store(true, Ordering::SeqCst);
7362                    let poller_result = optional_poller_result("activity", result);
7363                    let join_result =
7364                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7365                    poller_result?;
7366                    join_result?;
7367                    if stopped_by_server {
7368                        return Ok(());
7369                    }
7370                    return Err(Error::WorkerLoop(
7371                        "activity poller stopped unexpectedly".to_string(),
7372                    ));
7373                }
7374                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7375                    query_poller = None;
7376                    let stopped_by_server = stop.load(Ordering::SeqCst);
7377                    stop.store(true, Ordering::SeqCst);
7378                    let poller_result = optional_poller_result("query", result);
7379                    let join_result =
7380                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7381                    poller_result?;
7382                    join_result?;
7383                    if stopped_by_server {
7384                        return Ok(());
7385                    }
7386                    return Err(Error::WorkerLoop(
7387                        "query poller stopped unexpectedly".to_string(),
7388                    ));
7389                }
7390            }
7391        }
7392
7393        join_pollers(
7394            workflow_poller.take(),
7395            activity_poller.take(),
7396            query_poller.take(),
7397        )
7398        .await
7399    }
7400
7401    /// Poll and settle at most one task from each enabled task family.
7402    ///
7403    /// A workflow may reach its server-enforced run deadline while this worker
7404    /// holds a task. When the completion endpoint authoritatively rejects that
7405    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
7406    /// terminal `run_status=failed`, the workflow tick is considered settled:
7407    /// the late command was not recorded and cannot replace the terminal run.
7408    /// Every other completion rejection remains an error. This worker-level
7409    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
7410    /// only bounds how long a client waits for a result.
7411    ///
7412    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
7413    /// the original [`Error::Http`] status and response body.
7414    pub async fn run_once(&self) -> Result<usize> {
7415        if self.client.worker_sessions_enabled {
7416            self.require_session_registration()?;
7417        }
7418        if self.cooperative_cancellation_enabled
7419            && !self
7420                .cooperative_registration_confirmed
7421                .load(Ordering::SeqCst)
7422        {
7423            return Err(Error::CooperativeCancellationUnavailable(
7424                "register this cooperative worker before polling tasks".into(),
7425            ));
7426        }
7427        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
7428        let mut handled = 0;
7429        match worker.poll_workflow_once().await? {
7430            ManagedPollOutcome::Handled => handled += 1,
7431            ManagedPollOutcome::Stop => return Ok(handled),
7432            ManagedPollOutcome::Idle => {}
7433        }
7434        match worker.poll_activity_once().await? {
7435            ManagedPollOutcome::Handled => handled += 1,
7436            ManagedPollOutcome::Stop => return Ok(handled),
7437            ManagedPollOutcome::Idle => {}
7438        }
7439        if !self.queries.is_empty() {
7440            match worker.poll_query_once().await? {
7441                ManagedPollOutcome::Handled => handled += 1,
7442                ManagedPollOutcome::Stop => return Ok(handled),
7443                ManagedPollOutcome::Idle => {}
7444            }
7445        }
7446        Ok(handled)
7447    }
7448
7449    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
7450        if self.client.local_activities_enabled
7451            && !self.local_registration_confirmed.load(Ordering::SeqCst)
7452        {
7453            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
7454        }
7455        if self.cooperative_cancellation_enabled {
7456            return self.poll_cooperative_workflow_once().await;
7457        }
7458        let poll_request_id = unique_request_id("rust-workflow-poll");
7459        let response = self
7460            .retry_worker_operation(|| {
7461                self.client.poll_workflow_task_response_with_request_id(
7462                    &self.worker_id,
7463                    &self.task_queue,
7464                    self.poll_timeout,
7465                    &poll_request_id,
7466                    0,
7467                )
7468            })
7469            .await;
7470        let Some(response) = self.settle_worker_poll_response(response).await? else {
7471            return Ok(ManagedPollOutcome::Idle);
7472        };
7473        if response.outcome().should_stop() {
7474            return Ok(ManagedPollOutcome::Stop);
7475        }
7476        let memo_updates_supported =
7477            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
7478        let Some(task) = response.task else {
7479            return Ok(ManagedPollOutcome::Idle);
7480        };
7481
7482        let task_id = task.task_id.clone();
7483        let attempt = task.workflow_task_attempt;
7484        let run_id = task.run_id.clone();
7485        let lease_owner = task
7486            .lease_owner
7487            .clone()
7488            .unwrap_or_else(|| self.worker_id.clone());
7489
7490        let decision = match self.execute_workflow_with_local_activities(task).await {
7491            Ok(Some(decision)) => Ok(decision),
7492            Ok(None) => return Ok(ManagedPollOutcome::Handled),
7493            Err(error) => Err(error),
7494        };
7495        self.settle_workflow_task_decision(
7496            &task_id,
7497            &lease_owner,
7498            attempt,
7499            run_id.as_deref(),
7500            decision,
7501            memo_updates_supported,
7502        )
7503        .await
7504    }
7505
7506    async fn settle_workflow_task_decision(
7507        &self,
7508        task_id: &str,
7509        lease_owner: &str,
7510        attempt: u64,
7511        run_id: Option<&str>,
7512        decision: Result<WorkflowTaskDecision>,
7513        memo_updates_supported: bool,
7514    ) -> Result<ManagedPollOutcome> {
7515        match decision {
7516            Ok(decision)
7517                if decision.cancellation_delivery.is_some()
7518                    || decision.cancellation_scope_delivery.is_some()
7519                    || decision.cancellation_scope_opening.is_some() =>
7520            {
7521                return Err(Error::CooperativeCancellationUnavailable(
7522                    "worker cancellation delivery has not been negotiated".into(),
7523                ));
7524            }
7525            Ok(decision)
7526                if commands_use_workflow_memo_updates(&decision.commands)
7527                    && !memo_updates_supported =>
7528            {
7529                self.client
7530                    .fail_workflow_task(
7531                        task_id,
7532                        lease_owner,
7533                        attempt,
7534                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
7535                    )
7536                    .await?;
7537            }
7538            Ok(decision) if decision.commands.is_empty() => {
7539                // A replay can consume a recorded pending durable command
7540                // without producing a new command. The standalone protocol
7541                // acknowledges that state through the typed waiting outcome;
7542                // an empty completion is rejected by servers that require at
7543                // least one executable command.
7544                self.client
7545                    .fail_workflow_task_with_type(
7546                        task_id,
7547                        lease_owner,
7548                        attempt,
7549                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
7550                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
7551                    )
7552                    .await?;
7553            }
7554            Ok(decision) => {
7555                let completion = self
7556                    .client
7557                    .complete_workflow_task_with_message_streams(
7558                        task_id,
7559                        lease_owner,
7560                        attempt,
7561                        decision.commands,
7562                        decision.message_stream_cursors,
7563                        decision.message_stream_waits,
7564                    )
7565                    .await;
7566                if let Err(error) = completion {
7567                    if !workflow_task_completion_is_terminal_timeout(
7568                        &error, task_id, attempt, run_id,
7569                    ) {
7570                        return Err(error);
7571                    }
7572                }
7573            }
7574            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
7575            Err(error) => {
7576                self.client
7577                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
7578                    .await?;
7579            }
7580        }
7581
7582        Ok(ManagedPollOutcome::Handled)
7583    }
7584
7585    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7586        while !stop.load(Ordering::SeqCst) {
7587            match self.poll_workflow_once().await {
7588                Ok(ManagedPollOutcome::Stop) => {
7589                    stop.store(true, Ordering::SeqCst);
7590                    break;
7591                }
7592                Err(error) => {
7593                    stop.store(true, Ordering::SeqCst);
7594                    return Err(error);
7595                }
7596                _ => {}
7597            }
7598        }
7599
7600        Ok(())
7601    }
7602
7603    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
7604        if self.client.worker_sessions_enabled {
7605            self.require_session_registration()?;
7606        }
7607        if self.cooperative_cancellation_enabled {
7608            return self.poll_cooperative_activity_once().await;
7609        }
7610        let poll_request_id = unique_request_id("rust-activity-poll");
7611        let response = self
7612            .retry_worker_operation(|| {
7613                self.client.poll_activity_task_response_with_request_id(
7614                    &self.worker_id,
7615                    &self.task_queue,
7616                    self.poll_timeout,
7617                    &poll_request_id,
7618                    0,
7619                )
7620            })
7621            .await;
7622        let Some(response) = self.settle_worker_poll_response(response).await? else {
7623            return Ok(ManagedPollOutcome::Idle);
7624        };
7625        if response.outcome().should_stop() {
7626            return Ok(ManagedPollOutcome::Stop);
7627        }
7628        let Some(task) = response.task else {
7629            return Ok(ManagedPollOutcome::Idle);
7630        };
7631
7632        let session = self.track_session_task(task.worker_session.as_ref())?;
7633        let task = task.task;
7634
7635        let task_id = task.task_id.clone();
7636        let attempt_id = task
7637            .activity_attempt_id
7638            .clone()
7639            .or(task.attempt_id.clone())
7640            .unwrap_or_default();
7641        let lease_owner = task
7642            .lease_owner
7643            .clone()
7644            .unwrap_or_else(|| self.worker_id.clone());
7645        let codec = task.payload_codec.clone();
7646        let result = self.execute_session_activity_task(task, session).await;
7647        match result {
7648            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
7649            Ok(value) => {
7650                let completion = self
7651                    .client
7652                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
7653                    .await;
7654                if let Err(error) = completion {
7655                    if !activity_task_rejection_is_final(&error) {
7656                        return Err(error);
7657                    }
7658                }
7659            }
7660            Err(error) => {
7661                let failure = self
7662                    .client
7663                    .fail_activity_task(
7664                        &task_id,
7665                        &attempt_id,
7666                        &lease_owner,
7667                        error.to_string(),
7668                        false,
7669                    )
7670                    .await;
7671                if let Err(error) = failure {
7672                    if !activity_task_rejection_is_final(&error) {
7673                        return Err(error);
7674                    }
7675                }
7676            }
7677        }
7678
7679        Ok(ManagedPollOutcome::Handled)
7680    }
7681
7682    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7683        // Each lane retains its leased response through callback settlement.
7684        // A bounded independent activity must not occupy the cleanup lane too.
7685        // Preserve the existing serial loop for default protocol 1.19 workers.
7686        let lane_count = if self.cooperative_cancellation_enabled {
7687            self.max_concurrent_activity_tasks
7688        } else {
7689            1
7690        };
7691        let mut lanes = FuturesUnordered::new();
7692        for _ in 0..lane_count {
7693            let worker = self.clone();
7694            let stop = Arc::clone(&stop);
7695            lanes.push(async move {
7696                while !stop.load(Ordering::SeqCst) {
7697                    match worker.poll_activity_once().await {
7698                        Ok(ManagedPollOutcome::Stop) => {
7699                            stop.store(true, Ordering::SeqCst);
7700                            break;
7701                        }
7702                        Err(error) => {
7703                            stop.store(true, Ordering::SeqCst);
7704                            return Err(error);
7705                        }
7706                        _ => {}
7707                    }
7708                }
7709                Ok(())
7710            });
7711        }
7712        // Join every lane before deregistration, including after one fails.
7713        let mut first_error = None;
7714        while let Some(result) = lanes.next().await {
7715            if let Err(error) = result {
7716                first_error.get_or_insert(error);
7717            }
7718        }
7719        first_error.map_or(Ok(()), Err)
7720    }
7721
7722    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
7723        let poll_request_id = unique_request_id("rust-query-poll");
7724        let response = self
7725            .retry_worker_operation(|| {
7726                self.client.poll_query_task_response_with_request_id(
7727                    &self.worker_id,
7728                    &self.task_queue,
7729                    self.poll_timeout,
7730                    &poll_request_id,
7731                    0,
7732                )
7733            })
7734            .await;
7735        let Some(response) = self.settle_worker_poll_response(response).await? else {
7736            return Ok(ManagedPollOutcome::Idle);
7737        };
7738        if response.outcome().should_stop() {
7739            return Ok(ManagedPollOutcome::Stop);
7740        }
7741        let Some(task) = response.task else {
7742            return Ok(ManagedPollOutcome::Idle);
7743        };
7744
7745        let query_task_id = task.query_task_id.clone();
7746        let attempt = task.query_task_attempt;
7747        let lease_owner = task
7748            .lease_owner
7749            .clone()
7750            .unwrap_or_else(|| self.worker_id.clone());
7751        let codec = task.payload_codec.clone();
7752
7753        match self.execute_query_task(task).await {
7754            Ok(value) => {
7755                let result_envelope = match encode_typed_envelope(&value, &codec) {
7756                    Ok(result_envelope) => result_envelope,
7757                    Err(error) => {
7758                        let failure = self
7759                            .client
7760                            .fail_query_task(
7761                                &query_task_id,
7762                                &lease_owner,
7763                                attempt,
7764                                error.to_string(),
7765                                "query_result_encode_failed",
7766                                "QueryResultEncodeFailed",
7767                            )
7768                            .await;
7769                        if let Err(error) = failure {
7770                            if !query_task_rejection_is_final(&error) {
7771                                return Err(error);
7772                            }
7773                        }
7774                        return Ok(ManagedPollOutcome::Handled);
7775                    }
7776                };
7777
7778                if let Err(error) = self
7779                    .client
7780                    .complete_query_task_with_envelope(
7781                        &query_task_id,
7782                        &lease_owner,
7783                        attempt,
7784                        value.clone().into_json()?,
7785                        result_envelope,
7786                    )
7787                    .await
7788                {
7789                    if !query_task_rejection_is_final(&error) {
7790                        return Err(error);
7791                    }
7792                }
7793            }
7794            Err(failure) => {
7795                let result = self
7796                    .client
7797                    .fail_query_task(
7798                        &query_task_id,
7799                        &lease_owner,
7800                        attempt,
7801                        failure.message,
7802                        failure.reason,
7803                        failure.failure_type,
7804                    )
7805                    .await;
7806                if let Err(error) = result {
7807                    if !query_task_rejection_is_final(&error) {
7808                        return Err(error);
7809                    }
7810                }
7811            }
7812        }
7813
7814        Ok(ManagedPollOutcome::Handled)
7815    }
7816
7817    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7818        while !stop.load(Ordering::SeqCst) {
7819            match self.poll_query_once().await {
7820                Ok(ManagedPollOutcome::Stop) => {
7821                    stop.store(true, Ordering::SeqCst);
7822                    break;
7823                }
7824                Err(error) => {
7825                    stop.store(true, Ordering::SeqCst);
7826                    return Err(error);
7827                }
7828                _ => {}
7829            }
7830        }
7831
7832        Ok(())
7833    }
7834
7835    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
7836    where
7837        F: FnMut() -> Fut,
7838        Fut: Future<Output = Result<T>>,
7839    {
7840        let mut retries = 0;
7841
7842        loop {
7843            if self
7844                .run_stop
7845                .as_ref()
7846                .is_some_and(|stop| stop.load(Ordering::SeqCst))
7847            {
7848                return Ok(None);
7849            }
7850            match operation().await {
7851                Err(error)
7852                    if worker_operation_is_retryable(&error)
7853                        && (retries < self.retry_policy.max_retries
7854                            || (self.recover_transient_outages
7855                                && self.run_stop.is_some()
7856                                && self.retry_policy.max_retries > 0)) =>
7857                {
7858                    retries = retries.saturating_add(1);
7859                    let delay = worker_retry_delay(self.retry_policy, retries)
7860                        .max(Duration::from_millis(1));
7861                    if let Some(stop) = &self.run_stop {
7862                        tokio::select! {
7863                            _ = tokio::time::sleep(delay) => {}
7864                            _ = wait_for_worker_stop(stop) => return Ok(None),
7865                        }
7866                    } else {
7867                        tokio::time::sleep(delay).await;
7868                    }
7869                }
7870                result => return result.map(Some),
7871            }
7872        }
7873    }
7874
7875    async fn settle_worker_poll_response<T>(
7876        &self,
7877        response: Result<Option<T>>,
7878    ) -> Result<Option<T>> {
7879        match response {
7880            Ok(response) => Ok(response),
7881            Err(error) => {
7882                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
7883                    return Err(error);
7884                };
7885                let minimum_delay = self
7886                    .retry_policy
7887                    .initial_backoff
7888                    .max(Duration::from_millis(1));
7889                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
7890                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
7891                Ok(None)
7892            }
7893        }
7894    }
7895
7896    async fn execute_query_task(
7897        &self,
7898        mut task: QueryTask,
7899    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
7900        validate_query_task_payloads(&task).map_err(|error| {
7901            QueryTaskExecutionFailure::new(
7902                "query_payload_decode_failed",
7903                error.to_string(),
7904                "QueryPayloadDecodeFailed",
7905            )
7906        })?;
7907
7908        if !self.workflows.contains_key(&task.workflow_type) {
7909            return Err(QueryTaskExecutionFailure::new(
7910                "query_workflow_type_not_registered",
7911                format!("no workflow registered for type {:?}", task.workflow_type),
7912                "WorkflowTypeNotRegistered",
7913            ));
7914        }
7915
7916        let Some(handlers) = self.queries.get(&task.workflow_type) else {
7917            return Err(QueryTaskExecutionFailure::new(
7918                "query_handler_unavailable",
7919                format!(
7920                    "query handlers are unavailable for workflow type {:?}",
7921                    task.workflow_type
7922                ),
7923                "QueryHandlerUnavailable",
7924            ));
7925        };
7926        let Some(query) = handlers.get(&task.query_name) else {
7927            return Err(QueryTaskExecutionFailure::new(
7928                "rejected_unknown_query",
7929                format!("unknown query {:?}", task.query_name),
7930                "QueryFailed",
7931            ));
7932        };
7933
7934        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
7935            .map_err(|error| {
7936            QueryTaskExecutionFailure::new(
7937                "query_payload_decode_failed",
7938                format!("cannot decode query arguments: {error}"),
7939                "QueryPayloadDecodeFailed",
7940            )
7941        })?;
7942        let workflow_input_typed =
7943            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
7944                .map_err(|error| {
7945                    QueryTaskExecutionFailure::new(
7946                        "query_workflow_state_unavailable",
7947                        format!("cannot decode workflow start input: {error}"),
7948                        "QueryWorkflowStateUnavailable",
7949                    )
7950                })?;
7951        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
7952            QueryTaskExecutionFailure::new(
7953                "query_workflow_state_unavailable",
7954                format!("cannot project workflow start input: {error}"),
7955                "QueryWorkflowStateUnavailable",
7956            )
7957        })?;
7958        hydrate_query_history_from_export(&mut task).map_err(|error| {
7959            QueryTaskExecutionFailure::new(
7960                "query_workflow_state_unavailable",
7961                format!("cannot restore query history snapshot: {error}"),
7962                "QueryWorkflowStateUnavailable",
7963            )
7964        })?;
7965        enrich_query_history_from_export(&mut task).map_err(|error| {
7966            QueryTaskExecutionFailure::new(
7967                "query_workflow_state_unavailable",
7968                format!("cannot restore compact query history payloads: {error}"),
7969                "QueryWorkflowStateUnavailable",
7970            )
7971        })?;
7972        let signal_events = query_signal_events(&task).map_err(|error| {
7973            QueryTaskExecutionFailure::new(
7974                "query_workflow_state_unavailable",
7975                format!("cannot decode committed workflow signals: {error}"),
7976                "QueryWorkflowStateUnavailable",
7977            )
7978        })?;
7979        let history_events = Arc::new(std::mem::take(&mut task.history_events));
7980        let context = QueryContext {
7981            workflow_id: task.workflow_id,
7982            run_id: task.run_id,
7983            workflow_type: task.workflow_type.clone(),
7984            run_status: task.run_status,
7985            workflow_input,
7986            workflow_input_avro_value: workflow_input_typed.clone(),
7987            history_events: Arc::clone(&history_events),
7988            signal_events: Arc::new(signal_events),
7989        };
7990
7991        let future = match query {
7992            RegisteredQuery::Snapshot(handler) => handler(context, args),
7993            RegisteredQuery::Replayed {
7994                state_type,
7995                handler,
7996            } => {
7997                let workflow = self
7998                    .workflows
7999                    .get(&task.workflow_type)
8000                    .expect("workflow registration was checked above");
8001                if workflow.state_type != Some(*state_type) {
8002                    return Err(QueryTaskExecutionFailure::new(
8003                        "query_workflow_state_unavailable",
8004                        "replayed query state type does not match its workflow registration",
8005                        "QueryWorkflowStateUnavailable",
8006                    ));
8007                }
8008                let replay = workflow.replay.as_ref().ok_or_else(|| {
8009                    QueryTaskExecutionFailure::new(
8010                        "query_workflow_state_unavailable",
8011                        format!(
8012                            "workflow type {:?} is not registered for instance-state replay",
8013                            task.workflow_type
8014                        ),
8015                        "QueryWorkflowStateUnavailable",
8016                    )
8017                })?;
8018                let workflow_state = Arc::new(Mutex::new(
8019                    WorkflowState::new_with_identity(
8020                        history_events.as_ref().clone(),
8021                        context.workflow_id.clone(),
8022                        context.run_id.clone(),
8023                        self.task_queue.clone(),
8024                        task.payload_codec,
8025                        None,
8026                    )
8027                    .map_err(|error| {
8028                        QueryTaskExecutionFailure::new(
8029                            "query_workflow_state_unavailable",
8030                            format!("workflow replay failed before query: {error}"),
8031                            "QueryWorkflowStateUnavailable",
8032                        )
8033                    })?,
8034                ));
8035                let workflow_context = WorkflowContext {
8036                    state: workflow_state,
8037                    cancellation_scope_id: "root".into(),
8038                };
8039                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8040                let mut cx = TaskContext::from_waker(noop_waker_ref());
8041                let outcome = {
8042                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8043                        .map_err(|error| {
8044                            QueryTaskExecutionFailure::new(
8045                                "query_workflow_state_unavailable",
8046                                error.to_string(),
8047                                "QueryWorkflowStateUnavailable",
8048                            )
8049                        })?;
8050                    invocation.future.as_mut().poll(&mut cx)
8051                };
8052                match outcome {
8053                    Poll::Ready(Ok(_)) => {
8054                        workflow_context
8055                            .ensure_history_consumed()
8056                            .map_err(|error| {
8057                                QueryTaskExecutionFailure::new(
8058                                    "query_workflow_state_unavailable",
8059                                    format!("workflow replay failed before query: {error}"),
8060                                    "QueryWorkflowStateUnavailable",
8061                                )
8062                            })?;
8063                    }
8064                    Poll::Ready(Err(error)) => {
8065                        return Err(QueryTaskExecutionFailure::new(
8066                            "query_workflow_state_unavailable",
8067                            format!("workflow replay failed before query: {error}"),
8068                            "QueryWorkflowStateUnavailable",
8069                        ));
8070                    }
8071                    Poll::Pending => {
8072                        let commands = workflow_context.take_commands().map_err(|error| {
8073                            QueryTaskExecutionFailure::new(
8074                                "query_workflow_state_unavailable",
8075                                format!("workflow replay failed before query: {error}"),
8076                                "QueryWorkflowStateUnavailable",
8077                            )
8078                        })?;
8079                        if commands.is_empty()
8080                            && !workflow_context
8081                                .matched_recorded_pending()
8082                                .map_err(|error| {
8083                                    QueryTaskExecutionFailure::new(
8084                                        "query_workflow_state_unavailable",
8085                                        format!("workflow replay failed before query: {error}"),
8086                                        "QueryWorkflowStateUnavailable",
8087                                    )
8088                                })?
8089                        {
8090                            return Err(QueryTaskExecutionFailure::new(
8091                                "query_workflow_state_unavailable",
8092                                "workflow replay yielded without a durable command",
8093                                "QueryWorkflowStateUnavailable",
8094                            ));
8095                        }
8096                    }
8097                }
8098                let state = (invocation.snapshot)().map_err(|error| {
8099                    QueryTaskExecutionFailure::new(
8100                        "query_workflow_state_unavailable",
8101                        format!("cannot snapshot replayed workflow state: {error}"),
8102                        "QueryWorkflowStateUnavailable",
8103                    )
8104                })?;
8105                handler(context, state, args).map_err(|message| {
8106                    QueryTaskExecutionFailure::new(
8107                        "query_workflow_state_unavailable",
8108                        message,
8109                        "QueryWorkflowStateUnavailable",
8110                    )
8111                })?
8112            }
8113        };
8114
8115        future.await.map_err(|error| {
8116            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8117        })
8118    }
8119
8120    #[cfg(test)]
8121    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8122        Ok(self.execute_workflow_task_decision(task)?.commands)
8123    }
8124
8125    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8126        self.execute_workflow_task_decision_with_cancellation(task, None)
8127    }
8128
8129    fn execute_workflow_task_decision_with_cancellation(
8130        &self,
8131        task: WorkflowTask,
8132        observation: Option<&CancellationRequest>,
8133    ) -> Result<WorkflowTaskDecision> {
8134        match self.prepare_workflow_task_execution(task, observation)? {
8135            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8136            PreparedWorkflowTask::Execution {
8137                task,
8138                context,
8139                mut future,
8140            } => {
8141                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8142                self.finish_workflow_task_execution(&task, &context, outcome)
8143            }
8144        }
8145    }
8146
8147    fn prepare_workflow_task_execution(
8148        &self,
8149        task: WorkflowTask,
8150        observation: Option<&CancellationRequest>,
8151    ) -> Result<PreparedWorkflowTask> {
8152        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8153            && !self.cooperative_cancellation_enabled
8154        {
8155            return Err(Error::CancellationScopeExecutionUnavailable);
8156        }
8157        validate_workflow_task_payloads(&task)?;
8158        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8159            &task.history_events,
8160            self.allow_cancellation_scope_authoring,
8161            self.allow_cancellation_scope_delivery,
8162        )?;
8163        let cancellation_history = if let Some(observation) = observation {
8164            observation.validate_observation()?;
8165            cooperative_cancellation::cancellation_claim(&task)?;
8166            let canonical = CancellationHistory::from_events(
8167                &task.history_events,
8168                task.run_id.as_deref().unwrap_or_default(),
8169                Some(observation),
8170            )?;
8171            if canonical.request_index >= task.history_events.len() {
8172                return Err(Error::InvalidCooperativeCancellation(
8173                    "workflow replay requires the observed canonical request".into(),
8174                ));
8175            }
8176            Some(canonical)
8177        } else {
8178            None
8179        };
8180        if let Some(update_id) = task
8181            .workflow_update_id
8182            .as_deref()
8183            .filter(|update_id| !update_id.is_empty())
8184        {
8185            if self.allow_cancellation_scope_delivery {
8186                return Err(Error::CancellationScopeExecutionUnavailable);
8187            }
8188            CancellationHistory::from_events(
8189                &task.history_events,
8190                task.run_id.as_deref().unwrap_or_default(),
8191                None,
8192            )?;
8193            return self
8194                .execute_update_task(&task, update_id)
8195                .map(WorkflowTaskDecision::without_message_streams)
8196                .map(PreparedWorkflowTask::Decision);
8197        }
8198
8199        let workflow = self
8200            .workflows
8201            .get(&task.workflow_type)
8202            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8203        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8204        let resume_signal = decode_resume_signal(&task)?;
8205        let history_budget = WorkflowHistoryBudget {
8206            event_count: task
8207                .total_history_events
8208                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8209            size_bytes: task.history_size_bytes,
8210            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8211            pressure: task.history_budget_pressure.clone(),
8212        };
8213        let workflow_command_identity = task
8214            .workflow_command_id
8215            .clone()
8216            .filter(|identity| !identity.is_empty())
8217            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8218            .unwrap_or_default();
8219        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8220            task.history_events.clone(),
8221            task.workflow_id.clone(),
8222            task.run_id.clone(),
8223            self.task_queue.clone(),
8224            task.payload_codec.clone(),
8225            resume_signal,
8226            self.allow_cancellation_scope_authoring,
8227            self.allow_cancellation_scope_delivery,
8228        )?;
8229        workflow_state.history_budget = history_budget;
8230        workflow_state.workflow_command_identity = workflow_command_identity;
8231        if let Some(canonical) = cancellation_history {
8232            workflow_state.cancellation_history = canonical;
8233            workflow_state.cancellation_delivery_enabled = true;
8234        }
8235        if workflow_state.cancellation_history.request.is_none() {
8236            workflow_state.cancel_requested = task.cancel_requested;
8237        }
8238        let state = Arc::new(Mutex::new(workflow_state));
8239        let ctx = WorkflowContext {
8240            state,
8241            cancellation_scope_id: "root".into(),
8242        };
8243        let future = (workflow.execute)(ctx.clone(), input);
8244        Ok(PreparedWorkflowTask::Execution {
8245            task,
8246            context: ctx,
8247            future,
8248        })
8249    }
8250
8251    fn poll_workflow_future(
8252        ctx: &WorkflowContext,
8253        future: &mut WorkflowFuture,
8254    ) -> Result<Poll<Result<AvroValue>>> {
8255        let mut cx = TaskContext::from_waker(noop_waker_ref());
8256        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
8257        Ok(future.as_mut().poll(&mut cx))
8258    }
8259
8260    fn finish_workflow_task_execution(
8261        &self,
8262        task: &WorkflowTask,
8263        ctx: &WorkflowContext,
8264        outcome: Poll<Result<AvroValue>>,
8265    ) -> Result<WorkflowTaskDecision> {
8266        if !ctx
8267            .state
8268            .lock()
8269            .map_err(|_| Error::WorkflowStatePoisoned)?
8270            .local_activity_requests
8271            .is_empty()
8272        {
8273            return Err(Error::CooperativeCancellationUnavailable(
8274                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
8275            ));
8276        }
8277        let awaiting_canonical_boundary = {
8278            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8279            state.cancellation_delivery_intent.is_some()
8280                || state.cancellation_scope_opening.is_some()
8281                || state
8282                    .scope_delivery
8283                    .as_ref()
8284                    .is_some_and(|replay| replay.intent.is_some())
8285        };
8286        if awaiting_canonical_boundary {
8287            // A private delivery intent never becomes an application error.
8288            // Even a custom future which ignores a pending durable call cannot
8289            // publish terminal commands before canonical delivery and replay.
8290            if let Poll::Ready(Err(error)) = outcome {
8291                if workflow_task_integrity_error(&error) {
8292                    return Err(error);
8293                }
8294            }
8295            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8296        }
8297
8298        match outcome {
8299            Poll::Ready(Ok(result)) => {
8300                ctx.ensure_history_consumed()?;
8301                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8302                let mut commands = ctx.take_commands()?;
8303                commands.push(json!({
8304                    "type": "complete_workflow",
8305                    "result": result
8306                }));
8307                self.message_stream_decision(&ctx, commands)
8308            }
8309            Poll::Ready(Err(error)) => {
8310                if let Error::ContinueAsNew(request) = error {
8311                    let mut commands = ctx.take_commands()?;
8312                    if let Some(command) = ctx.continue_as_new_command(request)? {
8313                        commands.push(command);
8314                    }
8315                    ctx.ensure_history_consumed()?;
8316                    return self.message_stream_decision(&ctx, commands);
8317                }
8318                if workflow_task_integrity_error(&error) {
8319                    // Replay and protocol failures describe the workflow-task
8320                    // decision itself. Preserve their specific failure reason
8321                    // instead of replacing it with the derivative fact that
8322                    // recorded commands remain unconsumed.
8323                    return Err(error);
8324                }
8325                // A handler error must not hide a committed durable command that
8326                // upgraded workflow code no longer consumes.
8327                ctx.ensure_history_consumed()?;
8328                let mut commands = ctx.take_commands()?;
8329                commands.push(workflow_failure_command(
8330                    &error,
8331                    recorded_activity_failure_boundary(&ctx, &error),
8332                ));
8333                self.message_stream_decision(&ctx, commands)
8334            }
8335            Poll::Pending => {
8336                let commands = ctx.take_commands()?;
8337                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8338                    Err(Error::WorkflowYieldedWithoutCommand)
8339                } else {
8340                    self.message_stream_decision(&ctx, commands)
8341                }
8342            }
8343        }
8344    }
8345
8346    fn message_stream_decision(
8347        &self,
8348        ctx: &WorkflowContext,
8349        commands: Vec<Value>,
8350    ) -> Result<WorkflowTaskDecision> {
8351        if !self.cooperative_cancellation_enabled
8352            && commands.iter().any(|command| {
8353                command["type"] == "schedule_activity"
8354                    && command.get("cancellation_policy").is_some()
8355            })
8356        {
8357            return Err(Error::CooperativeCancellationUnavailable(format!(
8358                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8359                self.worker_id,
8360            )));
8361        }
8362        if !self.cooperative_cancellation_enabled
8363            && commands.iter().any(|command| {
8364                command["type"] == "start_child_workflow"
8365                    && (command["parent_close_policy"] == "request_cancellation"
8366                        || matches!(
8367                            command["cancellation_policy"].as_str(),
8368                            Some("try_cancel" | "wait_cancellation_completed")
8369                        ))
8370            })
8371        {
8372            return Err(Error::CooperativeCancellationUnavailable(format!(
8373                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8374                self.worker_id,
8375            )));
8376        }
8377        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
8378        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8379        let scope_delivery = state
8380            .scope_delivery
8381            .as_ref()
8382            .and_then(|replay| replay.intent.clone());
8383        if scope_delivery
8384            .as_ref()
8385            .is_some_and(|intent| commands.len() != intent.command_count)
8386        {
8387            return Err(invalid_recorded_history(
8388                "cancellation_scope_pending_call_escaped",
8389                scope_delivery.as_ref().unwrap().boundary.sequence,
8390                "commands preceding the pending scoped call",
8391                "commands after suspension",
8392                "workflow cannot publish beyond an uncommitted scope delivery",
8393            ));
8394        }
8395        if let Some(opening) = &state.cancellation_scope_opening {
8396            if commands.len() != opening.command_count {
8397                return Err(invalid_recorded_history(
8398                    "cancellation_scope_pending_call_escaped",
8399                    opening.sequence,
8400                    "commands before original scope opening",
8401                    "commands after suspended opening",
8402                    "workflow cannot publish beyond an uncommitted scope opening",
8403                ));
8404            }
8405        }
8406        if state.cancellation_delivery_intent.is_some()
8407            && commands.len() != state.cancellation_delivery_command_count
8408        {
8409            return Err(invalid_recorded_history(
8410                "cooperative_cancellation_pending_call_escaped",
8411                state
8412                    .cancellation_delivery_intent
8413                    .as_ref()
8414                    .expect("pending delivery")
8415                    .sequence,
8416                "only commands preceding the pending cancellation call",
8417                "commands authored after a suspended call",
8418                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
8419            ));
8420        }
8421        Ok(WorkflowTaskDecision {
8422            commands,
8423            message_stream_cursors,
8424            message_stream_waits,
8425            cancellation_delivery: state.cancellation_delivery_intent.clone(),
8426            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
8427            cancellation_scope_delivery: scope_delivery,
8428        })
8429    }
8430
8431    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
8432        if !self.workflows.contains_key(&task.workflow_type) {
8433            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
8434        }
8435
8436        let accepted = task.history_events.iter().rev().find_map(|event| {
8437            (event.event_type == "UpdateAccepted"
8438                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
8439            .then_some(&event.payload)
8440        });
8441        let update_name = accepted
8442            .and_then(|payload| payload.get("update_name"))
8443            .and_then(Value::as_str)
8444            .or(task.update_name.as_deref())
8445            .unwrap_or_default();
8446        let Some(handler) = self
8447            .updates
8448            .get(&task.workflow_type)
8449            .and_then(|handlers| handlers.get(update_name))
8450        else {
8451            return Ok(vec![json!({
8452                "type": "fail_update",
8453                "update_id": update_id,
8454                "message": format!(
8455                    "no update handler is registered for {}.{update_name}",
8456                    task.workflow_type
8457                ),
8458                "exception_type": "UnknownUpdate",
8459                "non_retryable": true,
8460            })]);
8461        };
8462        let arguments = accepted
8463            .and_then(|payload| payload.get("arguments"))
8464            .or(task.arguments.as_ref());
8465        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
8466        let context = QueryContext {
8467            workflow_id: task.workflow_id.clone(),
8468            run_id: task.run_id.clone(),
8469            workflow_type: task.workflow_type.clone(),
8470            run_status: Some("running".to_string()),
8471            workflow_input: Value::Null,
8472            workflow_input_avro_value: AvroValue::Null,
8473            history_events: Arc::new(task.history_events.clone()),
8474            signal_events: Arc::new(Vec::new()),
8475        };
8476        let mut future = handler(context, arguments);
8477        let mut cx = TaskContext::from_waker(noop_waker_ref());
8478
8479        match future.as_mut().poll(&mut cx) {
8480            Poll::Ready(Ok(result)) => Ok(vec![json!({
8481                "type": "complete_update",
8482                "update_id": update_id,
8483                "result": encode_typed_envelope(&result, &task.payload_codec)?,
8484            })]),
8485            Poll::Ready(Err(error)) => Ok(vec![json!({
8486                "type": "fail_update",
8487                "update_id": update_id,
8488                "message": error.to_string(),
8489                "exception_type": "UpdateFailed",
8490                "non_retryable": true,
8491            })]),
8492            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
8493        }
8494    }
8495
8496    #[cfg(test)]
8497    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
8498        self.execute_session_activity_task(task, None).await
8499    }
8500
8501    async fn execute_session_activity_task(
8502        &self,
8503        task: ActivityTask,
8504        worker_session: Option<WorkerSession>,
8505    ) -> Result<AvroValue> {
8506        validate_activity_task_payloads(&task)?;
8507        if worker_session.is_some() {
8508            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
8509                || task
8510                    .activity_attempt_id
8511                    .as_deref()
8512                    .or(task.attempt_id.as_deref())
8513                    .is_none_or(str::is_empty)
8514                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
8515            {
8516                return Err(Error::ActivityExecutionAbandoned(
8517                    "session activity requires this worker's exact immutable claim".into(),
8518                ));
8519            }
8520        }
8521
8522        let handler = self
8523            .activities
8524            .get(&task.activity_type)
8525            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
8526        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8527        let attempt_id = task
8528            .activity_attempt_id
8529            .clone()
8530            .or(task.attempt_id.clone())
8531            .unwrap_or_default();
8532        let lease_owner = task
8533            .lease_owner
8534            .clone()
8535            .unwrap_or_else(|| self.worker_id.clone());
8536        let session = worker_session.clone();
8537        let ctx = ActivityContext {
8538            client: self.client.clone(),
8539            task_id: task.task_id,
8540            activity_attempt_id: attempt_id,
8541            lease_owner,
8542            activity_type: task.activity_type,
8543            attempt_number: task.attempt_number,
8544            task_queue: self.task_queue.clone(),
8545            worker_id: self.worker_id.clone(),
8546            claim_guard: None,
8547            local_heartbeats: None,
8548            worker_session,
8549        };
8550
8551        let callback = handler(ctx, args);
8552        if let Some(session) = session {
8553            tokio::select! {
8554                biased;
8555                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
8556                result = callback => if session.active() { result } else {
8557                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
8558                },
8559            }
8560        } else {
8561            callback.await
8562        }
8563    }
8564}
8565
8566fn poller_result(
8567    kind: &str,
8568    result: std::result::Result<Result<()>, tokio::task::JoinError>,
8569) -> Result<()> {
8570    match result {
8571        Ok(result) => result,
8572        Err(error) => Err(Error::WorkerLoop(format!(
8573            "{kind} poller join error: {error}"
8574        ))),
8575    }
8576}
8577
8578fn optional_poller_result(
8579    kind: &str,
8580    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
8581) -> Result<()> {
8582    match result {
8583        Some(result) => poller_result(kind, result),
8584        None => Ok(()),
8585    }
8586}
8587
8588async fn join_pollers(
8589    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8590    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8591    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8592) -> Result<()> {
8593    let mut first_error = None;
8594
8595    if let Some(handle) = workflow_poller {
8596        if let Err(error) = poller_result("workflow", handle.await) {
8597            first_error.get_or_insert(error);
8598        }
8599    }
8600
8601    if let Some(handle) = activity_poller {
8602        if let Err(error) = poller_result("activity", handle.await) {
8603            first_error.get_or_insert(error);
8604        }
8605    }
8606
8607    if let Some(handle) = query_poller {
8608        if let Err(error) = poller_result("query", handle.await) {
8609            first_error.get_or_insert(error);
8610        }
8611    }
8612
8613    if let Some(error) = first_error {
8614        Err(error)
8615    } else {
8616        Ok(())
8617    }
8618}
8619
8620fn default_worker_id() -> String {
8621    let millis = SystemTime::now()
8622        .duration_since(UNIX_EPOCH)
8623        .unwrap_or_default()
8624        .as_millis();
8625    format!("rust-worker-{}-{millis}", std::process::id())
8626}
8627
8628fn percent_encode_path_segment(segment: &str) -> String {
8629    const HEX: &[u8; 16] = b"0123456789ABCDEF";
8630    let mut encoded = String::with_capacity(segment.len());
8631
8632    for byte in segment.bytes() {
8633        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
8634            encoded.push(char::from(byte));
8635        } else {
8636            encoded.push('%');
8637            encoded.push(char::from(HEX[(byte >> 4) as usize]));
8638            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
8639        }
8640    }
8641
8642    encoded
8643}
8644
8645fn unique_request_id(prefix: &str) -> String {
8646    let nanos = SystemTime::now()
8647        .duration_since(UNIX_EPOCH)
8648        .unwrap_or_default()
8649        .as_nanos();
8650    format!("{prefix}-{}-{nanos}", std::process::id())
8651}
8652
8653#[derive(Debug)]
8654struct QueryTaskExecutionFailure {
8655    reason: String,
8656    message: String,
8657    failure_type: String,
8658}
8659
8660impl QueryTaskExecutionFailure {
8661    fn new(
8662        reason: impl Into<String>,
8663        message: impl Into<String>,
8664        failure_type: impl Into<String>,
8665    ) -> Self {
8666        Self {
8667            reason: reason.into(),
8668            message: message.into(),
8669            failure_type: failure_type.into(),
8670        }
8671    }
8672}
8673
8674/// Typed local state owned by one deterministic workflow invocation.
8675///
8676/// Use [`WorkflowInstance::update`] for the same state transitions during
8677/// ordinary execution and replay. A replayed query receives a detached
8678/// immutable `Arc<S>` rather than this mutation-capable handle.
8679#[derive(Clone, Debug)]
8680pub struct WorkflowInstance<S> {
8681    state: Arc<Mutex<S>>,
8682}
8683
8684impl<S> WorkflowInstance<S> {
8685    fn new(state: S) -> Self {
8686        Self {
8687            state: Arc::new(Mutex::new(state)),
8688        }
8689    }
8690
8691    /// Read the current workflow-instance state without changing it.
8692    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
8693        let state = self
8694            .state
8695            .lock()
8696            .map_err(|_| Error::WorkflowStatePoisoned)?;
8697        Ok(reader(&state))
8698    }
8699
8700    /// Apply one deterministic workflow-instance state transition.
8701    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
8702        let mut state = self
8703            .state
8704            .lock()
8705            .map_err(|_| Error::WorkflowStatePoisoned)?;
8706        Ok(transition(&mut state))
8707    }
8708}
8709
8710impl<S: Clone> WorkflowInstance<S> {
8711    fn snapshot(&self) -> Result<S> {
8712        self.read(Clone::clone)
8713    }
8714}
8715
8716#[derive(Clone, Debug, PartialEq)]
8717pub struct MessageStreamMessage {
8718    pub stream_name: String,
8719    pub message_id: String,
8720    pub position: u64,
8721    pub arguments: Vec<AvroValue>,
8722}
8723
8724#[derive(Clone, Debug)]
8725pub struct MessageStream {
8726    ctx: WorkflowContext,
8727    name: String,
8728}
8729
8730impl MessageStream {
8731    /// Wait for one message, then return a bounded currently-available batch.
8732    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
8733        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
8734            return Err(Error::Codec(format!(
8735                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
8736            )));
8737        }
8738        loop {
8739            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
8740                return Ok(batch);
8741            }
8742
8743            self.ctx.record_message_stream_wait(&self.name)?;
8744            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
8745            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
8746            self.ctx.buffer_message_stream_delivery(arguments)?;
8747            if let Some(sequence) = replay_wait_sequence {
8748                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
8749            }
8750        }
8751    }
8752
8753    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
8754        self.receive(1)
8755            .await?
8756            .into_iter()
8757            .next()
8758            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
8759    }
8760}
8761
8762#[derive(Clone, Debug)]
8763pub struct WorkflowContext {
8764    state: Arc<Mutex<WorkflowState>>,
8765    cancellation_scope_id: String,
8766}
8767
8768fn valid_memo_key(key: &str) -> bool {
8769    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
8770
8771    !key.is_empty()
8772        && key.len() <= 64
8773        && (numeric_candidate.is_empty()
8774            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
8775        && key
8776            .bytes()
8777            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
8778}
8779
8780fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
8781    BASE64
8782        .decode(encode_avro_value(value)?.blob)
8783        .map(|bytes| bytes.len())
8784        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
8785}
8786
8787fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
8788    let AvroValue::Map(entries) = value else {
8789        return Err(Error::InvalidMemoUpdate(
8790            "entries must serialize to an Avro string-keyed map".to_string(),
8791        ));
8792    };
8793    if require_entries && entries.is_empty() {
8794        return Err(Error::InvalidMemoUpdate(
8795            "at least one entry is required".to_string(),
8796        ));
8797    }
8798    if entries.len() > MAX_MEMO_ENTRIES {
8799        return Err(Error::InvalidMemoUpdate(format!(
8800            "at most {MAX_MEMO_ENTRIES} entries are allowed"
8801        )));
8802    }
8803
8804    for (key, value) in &entries {
8805        if !valid_memo_key(&key) {
8806            return Err(Error::InvalidMemoUpdate(
8807                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
8808            ));
8809        }
8810        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
8811            return Err(Error::InvalidMemoUpdate(format!(
8812                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
8813            )));
8814        }
8815    }
8816
8817    let value = AvroValue::Map(entries);
8818    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
8819        return Err(Error::InvalidMemoUpdate(format!(
8820            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
8821        )));
8822    }
8823    Ok(value)
8824}
8825
8826fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
8827    let object = envelope.as_object().ok_or_else(|| {
8828        Error::InvalidMemoUpdate(
8829            "history field must use the public {codec, blob} payload envelope".to_string(),
8830        )
8831    })?;
8832    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
8833        return Err(Error::InvalidMemoUpdate(
8834            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
8835        ));
8836    }
8837
8838    canonical_memo_entries(
8839        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
8840        require_entries,
8841    )
8842}
8843
8844impl WorkflowContext {
8845    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
8846        let name = name.into();
8847        if name.is_empty()
8848            || name.len() > 128
8849            || !name.bytes().all(|byte| {
8850                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
8851            })
8852        {
8853            return Err(Error::Codec(
8854                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
8855                    .to_string(),
8856            ));
8857        }
8858        Ok(MessageStream {
8859            ctx: self.clone(),
8860            name,
8861        })
8862    }
8863
8864    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
8865        let mut state = self
8866            .state
8867            .lock()
8868            .map_err(|_| Error::WorkflowStatePoisoned)?;
8869        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
8870        state
8871            .message_stream_waits
8872            .insert(name.to_string(), position);
8873        Ok(())
8874    }
8875
8876    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
8877        let mut state = self
8878            .state
8879            .lock()
8880            .map_err(|_| Error::WorkflowStatePoisoned)?;
8881        let cursor = state
8882            .message_stream_cursors
8883            .get(&message.stream_name)
8884            .copied()
8885            .unwrap_or(0);
8886        if message.position <= cursor {
8887            return Ok(());
8888        }
8889        let pending = state
8890            .message_stream_messages
8891            .entry(message.stream_name.clone())
8892            .or_default();
8893        if pending.iter().any(|candidate| {
8894            candidate.position == message.position || candidate.message_id == message.message_id
8895        }) {
8896            return Ok(());
8897        }
8898        pending.push(message);
8899        pending.sort_by_key(|candidate| candidate.position);
8900        Ok(())
8901    }
8902
8903    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
8904        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
8905            match delivery {
8906                MessageStreamDelivery::Message(message) => {
8907                    let stream_name = message.stream_name.clone();
8908                    self.buffer_message_stream(message)?;
8909                    return Ok(Some(stream_name));
8910                }
8911                MessageStreamDelivery::Cursor {
8912                    stream_name,
8913                    through_position,
8914                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
8915            }
8916        }
8917        Ok(None)
8918    }
8919
8920    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
8921        let state = self
8922            .state
8923            .lock()
8924            .map_err(|_| Error::WorkflowStatePoisoned)?;
8925        Ok(match state.recorded_commands.get(state.command_cursor) {
8926            Some(RecordedCommand::SignalWait {
8927                sequence,
8928                signal_name,
8929                ..
8930            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
8931            _ => None,
8932        })
8933    }
8934
8935    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
8936        let (history, payload_codec) = {
8937            let state = self
8938                .state
8939                .lock()
8940                .map_err(|_| Error::WorkflowStatePoisoned)?;
8941            (
8942                Arc::clone(&state.history_events),
8943                state.payload_codec.clone(),
8944            )
8945        };
8946
8947        let Some(opened_index) = history.iter().position(|event| {
8948            event.event_type == "SignalWaitOpened"
8949                && durable_event_sequence(event) == Some(wait_sequence)
8950                && event.payload.get("signal_name").and_then(Value::as_str)
8951                    == Some(MESSAGE_STREAM_SIGNAL)
8952        }) else {
8953            return Ok(());
8954        };
8955        let boundary_index = history
8956            .iter()
8957            .enumerate()
8958            .skip(opened_index + 1)
8959            .find_map(|(index, event)| {
8960                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
8961                    && is_authored_command_open_event(event))
8962                .then_some(index)
8963            })
8964            .unwrap_or(history.len());
8965
8966        for event in history[opened_index + 1..boundary_index]
8967            .iter()
8968            .filter(|event| {
8969                event.event_type == "SignalReceived"
8970                    && event.payload.get("signal_name").and_then(Value::as_str)
8971                        == Some(MESSAGE_STREAM_SIGNAL)
8972            })
8973        {
8974            let arguments = decode_signal_event_arguments(event, &payload_codec)?
8975                .into_iter()
8976                .map(AvroValue::into_json)
8977                .collect::<Result<Vec<_>>>()?;
8978            self.buffer_message_stream_delivery(arguments)?;
8979        }
8980        Ok(())
8981    }
8982
8983    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
8984        let mut state = self
8985            .state
8986            .lock()
8987            .map_err(|_| Error::WorkflowStatePoisoned)?;
8988        let cursor = state
8989            .message_stream_cursors
8990            .entry(name.to_string())
8991            .or_default();
8992        *cursor = (*cursor).max(through_position);
8993        if let Some(pending) = state.message_stream_messages.get_mut(name) {
8994            pending.retain(|message| message.position > through_position);
8995        }
8996        Ok(())
8997    }
8998
8999    fn take_message_stream_batch(
9000        &self,
9001        name: &str,
9002        max_items: usize,
9003    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9004        let mut state = self
9005            .state
9006            .lock()
9007            .map_err(|_| Error::WorkflowStatePoisoned)?;
9008        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9009        let pending = state
9010            .message_stream_messages
9011            .entry(name.to_string())
9012            .or_default();
9013        let count = contiguous_message_stream_count(pending, cursor, max_items);
9014        if count == 0 {
9015            return Ok(None);
9016        }
9017        let batch = pending.drain(..count).collect::<Vec<_>>();
9018        let position = batch.last().map(|message| message.position).unwrap_or(0);
9019        state
9020            .message_stream_cursors
9021            .insert(name.to_string(), position);
9022        state.message_stream_waits.remove(name);
9023        Ok(Some(batch))
9024    }
9025
9026    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9027        let state = self
9028            .state
9029            .lock()
9030            .map_err(|_| Error::WorkflowStatePoisoned)?;
9031        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9032        cursors.sort_by_key(|(name, _)| *name);
9033        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9034        waits.sort_by_key(|(name, _)| *name);
9035        Ok((
9036            cursors
9037                .into_iter()
9038                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9039                .collect(),
9040            waits
9041                .into_iter()
9042                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9043                .collect(),
9044        ))
9045    }
9046    /// Identity of the parent workflow currently being replayed.
9047    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9048        let state = self
9049            .state
9050            .lock()
9051            .map_err(|_| Error::WorkflowStatePoisoned)?;
9052        Ok(WorkflowIdentity {
9053            workflow_id: state.workflow_id.clone(),
9054            run_id: state.run_id.clone(),
9055        })
9056    }
9057
9058    /// Return the server-published history budget for this workflow task.
9059    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9060        let state = self
9061            .state
9062            .lock()
9063            .map_err(|_| Error::WorkflowStatePoisoned)?;
9064        Ok(state.history_budget.clone())
9065    }
9066
9067    /// Continue this workflow instance as a fresh run with replacement arguments.
9068    ///
9069    /// Return this value directly from the workflow handler. The worker converts
9070    /// it to the terminal protocol command only after replay has consumed every
9071    /// recorded durable command.
9072    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9073        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9074    }
9075
9076    /// Continue as new with optional workflow-type and task-queue overrides.
9077    pub fn continue_as_new_with_options<T: Serialize>(
9078        &self,
9079        options: ContinueAsNewOptions,
9080        args: T,
9081    ) -> Result<Value> {
9082        options.validate()?;
9083        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9084            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9085            options,
9086        }))
9087    }
9088
9089    pub fn activity<T: Serialize>(
9090        &self,
9091        activity_type: impl Into<String>,
9092        args: T,
9093    ) -> ActivityCall {
9094        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9095    }
9096
9097    pub fn activity_on_queue<T, Q>(
9098        &self,
9099        activity_type: impl Into<String>,
9100        task_queue: Option<Q>,
9101        args: T,
9102    ) -> ActivityCall
9103    where
9104        T: Serialize,
9105        Q: Into<String>,
9106    {
9107        let mut options = ActivityOptions::new();
9108        options.task_queue = task_queue.map(Into::into);
9109        self.activity_with_options(activity_type, options, args)
9110    }
9111
9112    /// Schedule one durable activity with retry, routing, and timeout options.
9113    ///
9114    /// Options are validated before the command is emitted. Once the command is
9115    /// recorded, replay consumes the same activity lifecycle at this command
9116    /// position and never emits a duplicate schedule.
9117    ///
9118    /// ```no_run
9119    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9120    /// # use std::time::Duration;
9121    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9122    /// let result = ctx
9123    ///     .activity_with_options(
9124    ///         "charge-card",
9125    ///         ActivityOptions::new()
9126    ///             .task_queue("payments")
9127    ///             .retry_policy(
9128    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9129    ///                     Duration::from_secs(1),
9130    ///                     2,
9131    ///                     Some(Duration::from_secs(30)),
9132    ///                 ),
9133    ///             )
9134    ///             .start_to_close_timeout(Duration::from_secs(60))
9135    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9136    ///             .heartbeat_timeout(Duration::from_secs(15)),
9137    ///         json!([{"order_id": "order-42"}]),
9138    ///     )
9139    ///     .await;
9140    /// match result {
9141    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9142    ///         "reason": failure.reason,
9143    ///         "timeout_kind": failure.timeout_kind,
9144    ///     })),
9145    ///     other => other,
9146    /// }
9147    /// # }
9148    /// ```
9149    pub fn activity_with_options<T: Serialize>(
9150        &self,
9151        activity_type: impl Into<String>,
9152        options: ActivityOptions,
9153        args: T,
9154    ) -> ActivityCall {
9155        ActivityCall {
9156            ctx: self.clone(),
9157            activity_type: activity_type.into(),
9158            options,
9159            worker_session: None,
9160            args: Some(AvroValue::from_serialize(&args)),
9161            scheduled: false,
9162            local: false,
9163            local_result: None,
9164            parallel_group_path: Vec::new(),
9165        }
9166    }
9167
9168    pub async fn activity_avro_value<T: Serialize>(
9169        &self,
9170        activity_type: impl Into<String>,
9171        args: T,
9172    ) -> Result<AvroValue> {
9173        let mut call = self.activity(activity_type, args);
9174        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9175    }
9176
9177    pub async fn activity_avro_value_with_options<T: Serialize>(
9178        &self,
9179        activity_type: impl Into<String>,
9180        options: ActivityOptions,
9181        args: T,
9182    ) -> Result<AvroValue> {
9183        let mut call = self.activity_with_options(activity_type, options, args);
9184        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9185    }
9186
9187    /// Schedule an activity with a Serde request and decode its Serde result.
9188    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9189    where
9190        I: Serialize,
9191        O: DeserializeOwned,
9192    {
9193        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9194            .await
9195    }
9196
9197    /// Schedule an activity with options and decode its result into `O`.
9198    ///
9199    /// Both directions use the fixed Avro Value codec. In particular, this
9200    /// method does not deserialize the JSON-safe inspection projection returned
9201    /// by the dynamic [`ActivityCall`] future.
9202    pub async fn activity_typed_with_options<I, O>(
9203        &self,
9204        activity_type: impl Into<String>,
9205        options: ActivityOptions,
9206        args: I,
9207    ) -> Result<O>
9208    where
9209        I: Serialize,
9210        O: DeserializeOwned,
9211    {
9212        let activity_type = activity_type.into();
9213        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9214            handler_type_error::<I>(
9215                HandlerKind::Activity,
9216                &activity_type,
9217                HandlerValueKind::Input,
9218                error.to_string(),
9219            )
9220        });
9221        let mut call = ActivityCall {
9222            ctx: self.clone(),
9223            activity_type: activity_type.clone(),
9224            options,
9225            worker_session: None,
9226            args: Some(encoded),
9227            scheduled: false,
9228            local: false,
9229            local_result: None,
9230            parallel_group_path: Vec::new(),
9231        };
9232        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9233        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9234    }
9235
9236    /// Schedule and join a deterministic activity/child/timer group.
9237    ///
9238    /// Nested groups retain their input shape. Every durable leaf is scheduled
9239    /// before this future yields, results are assembled by declaration order,
9240    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9241    /// declaration path, stable group metadata, and completed siblings.
9242    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9243        ParallelCall::new(self.clone(), operations)
9244    }
9245
9246    /// Alias for [`WorkflowContext::parallel`].
9247    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9248        self.parallel(operations)
9249    }
9250
9251    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
9252    pub async fn parallel_avro_value(
9253        &self,
9254        operations: Vec<ParallelOperation>,
9255    ) -> Result<Vec<ParallelAvroResult>> {
9256        let mut call = self.parallel(operations);
9257        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9258    }
9259
9260    /// Start every durable operation and resume from the one winner persisted
9261    /// by Server. Non-winning operations continue and remain addressable.
9262    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
9263        let operations = operations
9264            .into_iter()
9265            .enumerate()
9266            .map(|(index, operation)| (SelectionKey::Index(index), operation))
9267            .collect();
9268        SelectCall::new(self.clone(), operations)
9269    }
9270
9271    /// Named-key variant of [`WorkflowContext::select`].
9272    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
9273    where
9274        K: Into<SelectionKey>,
9275    {
9276        SelectCall::new(
9277            self.clone(),
9278            operations
9279                .into_iter()
9280                .map(|(key, operation)| (key.into(), operation))
9281                .collect(),
9282        )
9283    }
9284
9285    /// Create a workflow-local deterministic compensation registry.
9286    pub fn saga(&self) -> Saga {
9287        Saga::new(self.clone())
9288    }
9289
9290    /// Whether cancellation has reached this replay's authored boundary.
9291    ///
9292    /// Server's current `/cancel` route is terminal and does not set this flag.
9293    /// A canonical service request remains pending until its committed delivery
9294    /// is consumed. Request observation alone does not authorize an exception.
9295    pub fn is_cancellation_requested(&self) -> Result<bool> {
9296        let state = self
9297            .state
9298            .lock()
9299            .map_err(|_| Error::WorkflowStatePoisoned)?;
9300        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9301            return Ok(state
9302                .scope_delivery
9303                .as_ref()
9304                .unwrap()
9305                .contexts
9306                .contains_key(&self.cancellation_scope_id));
9307        }
9308        Ok(state.cancel_requested
9309            || state
9310                .scope_delivery
9311                .as_ref()
9312                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
9313    }
9314
9315    /// Raise a typed cooperative cancellation at an author-controlled point.
9316    ///
9317    /// Passing this result to [`Saga::finish`] compensates already registered
9318    /// forward steps before the cancellation remains the initiating outcome.
9319    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
9320        let mut state = self
9321            .state
9322            .lock()
9323            .map_err(|_| Error::WorkflowStatePoisoned)?;
9324        if state.cancellation_shield_depth == 0 {
9325            if let Some(replay) = &state.scope_delivery {
9326                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
9327                    let delivered = replay
9328                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
9329                        .ok_or_else(|| {
9330                            Error::InvalidCooperativeCancellation(
9331                                "scoped request lacks its consumed original delivery".into(),
9332                            )
9333                        })?;
9334                    return Err(Error::CancellationScopeRequested(
9335                        CancellationScopeRequested {
9336                            context: context
9337                                .clone()
9338                                .with_replay(Some(Arc::downgrade(&self.state))),
9339                            delivery: delivered.boundary.clone(),
9340                        },
9341                    ));
9342                }
9343            }
9344        }
9345        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9346            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9347                return Ok(());
9348            }
9349            return Err(state.cancellation_error());
9350        }
9351        Ok(())
9352    }
9353
9354    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9355        SignalCall {
9356            ctx: self.clone(),
9357            signal_name: signal_name.into(),
9358            runtime_reserved_allowed: false,
9359            opened_wait: false,
9360            matched_pending: false,
9361            parallel_group_path: Vec::new(),
9362        }
9363    }
9364
9365    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9366        SignalCall {
9367            ctx: self.clone(),
9368            signal_name: signal_name.into(),
9369            runtime_reserved_allowed: true,
9370            opened_wait: false,
9371            matched_pending: false,
9372            parallel_group_path: Vec::new(),
9373        }
9374    }
9375
9376    pub async fn wait_signal_avro_value(
9377        &self,
9378        signal_name: impl Into<String>,
9379    ) -> Result<Vec<AvroValue>> {
9380        let mut call = self.wait_signal(signal_name);
9381        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9382    }
9383
9384    /// Return every committed signal argument list with the given name.
9385    ///
9386    /// This history-backed view is deterministic and is intended for
9387    /// condition predicates that must be re-evaluated after a signal while the
9388    /// workflow is blocked on [`WorkflowContext::wait_condition`].
9389    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
9390        self.signals_avro_value(signal_name)?
9391            .into_iter()
9392            .map(|arguments| {
9393                arguments
9394                    .into_iter()
9395                    .map(AvroValue::into_json)
9396                    .collect::<Result<Vec<_>>>()
9397            })
9398            .collect()
9399    }
9400
9401    /// Lossless fixed Avro Value view of committed signals with the given name.
9402    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9403        let state = self
9404            .state
9405            .lock()
9406            .map_err(|_| Error::WorkflowStatePoisoned)?;
9407        state
9408            .history_events
9409            .iter()
9410            .filter(|event| {
9411                event.event_type == "SignalReceived"
9412                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
9413            })
9414            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
9415            .collect()
9416    }
9417
9418    /// Return every committed update argument list with the given name.
9419    ///
9420    /// Accepted and applied records for the same update ID are de-duplicated.
9421    /// A Server task created after an update therefore replays the workflow and
9422    /// re-evaluates an open condition without application polling.
9423    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
9424        self.updates_avro_value(update_name)?
9425            .into_iter()
9426            .map(|arguments| {
9427                arguments
9428                    .into_iter()
9429                    .map(AvroValue::into_json)
9430                    .collect::<Result<Vec<_>>>()
9431            })
9432            .collect()
9433    }
9434
9435    /// Lossless fixed Avro Value view of committed updates with the given name.
9436    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9437        let state = self
9438            .state
9439            .lock()
9440            .map_err(|_| Error::WorkflowStatePoisoned)?;
9441        let mut seen = Vec::new();
9442        let mut updates = Vec::new();
9443        for event in state.history_events.iter() {
9444            if !matches!(
9445                event.event_type.as_str(),
9446                "UpdateAccepted" | "UpdateApplied"
9447            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
9448                || event.payload.get("arguments").is_none()
9449            {
9450                continue;
9451            }
9452            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
9453                if seen.iter().any(|recorded| recorded == update_id) {
9454                    continue;
9455                }
9456                seen.push(update_id.to_string());
9457            }
9458            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
9459        }
9460        Ok(updates)
9461    }
9462
9463    /// Wait for a deterministic predicate to become true or for its durable
9464    /// timeout to elapse.
9465    ///
9466    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
9467    /// predicate tokens automatically change the recorded definition
9468    /// fingerprint. Direct callers must provide an equally stable identity in
9469    /// [`ConditionWaitOptions`].
9470    pub fn wait_condition<F>(
9471        &self,
9472        options: ConditionWaitOptions,
9473        predicate: F,
9474    ) -> ConditionWaitCall
9475    where
9476        F: Fn() -> Result<bool> + Send + 'static,
9477    {
9478        ConditionWaitCall {
9479            ctx: self.clone(),
9480            options,
9481            predicate: Box::new(predicate),
9482            occurrence_id: None,
9483            opened_wait: false,
9484            parallel_group_path: Vec::new(),
9485        }
9486    }
9487
9488    /// Wait for server-backed durable time without blocking the worker executor.
9489    ///
9490    /// Polling this future emits one `start_timer` command and yields. The
9491    /// server records the deadline, so neither worker nor server restarts reset
9492    /// the wait. Replay resolves the future only from a `TimerScheduled` and
9493    /// `TimerFired` pair at the same position in the shared durable-command
9494    /// stream, with matching sequence, timer identity, and delay. Sub-second
9495    /// durations round up because protocol deadlines use whole seconds.
9496    ///
9497    /// ```no_run
9498    /// # use durable_workflow::{json, Client, Worker};
9499    /// # use std::time::Duration;
9500    /// # fn configure(client: Client) {
9501    /// let mut worker = Worker::new(client, "rust-workers");
9502    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
9503    ///     ctx.sleep(Duration::from_secs(5)).await?;
9504    ///     Ok(json!({"status": "timer fired"}))
9505    /// });
9506    /// # }
9507    /// ```
9508    pub fn sleep(&self, duration: Duration) -> TimerCall {
9509        let delay_seconds = duration
9510            .as_secs()
9511            .checked_add(u64::from(duration.subsec_nanos() > 0));
9512        TimerCall {
9513            ctx: self.clone(),
9514            delay_seconds,
9515            scheduled: false,
9516            matched_pending: false,
9517            parallel_group_path: Vec::new(),
9518        }
9519    }
9520
9521    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
9522    pub fn start_timer(&self, duration: Duration) -> TimerCall {
9523        self.sleep(duration)
9524    }
9525
9526    /// Evaluate a non-deterministic callback once and durably record its typed value.
9527    ///
9528    /// On replay the callback is not invoked: the value is decoded from the
9529    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
9530    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
9531    /// small values that must remain fixed for the lifetime of a workflow run.
9532    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
9533    where
9534        T: Serialize + DeserializeOwned,
9535        F: FnOnce() -> T,
9536    {
9537        {
9538            let mut state = self
9539                .state
9540                .lock()
9541                .map_err(|_| Error::WorkflowStatePoisoned)?;
9542            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9543                return match recorded {
9544                    RecordedCommand::SideEffect { sequence, value } => {
9545                        state.command_cursor += 1;
9546                        value.deserialize().map_err(|error| {
9547                            Error::NonDeterministicReplay(ReplayFailure::new(
9548                                "side_effect_type_mismatch",
9549                                Some(sequence),
9550                                Some(std::any::type_name::<T>().to_string()),
9551                                Some(error.to_string()),
9552                                "recorded side-effect value is incompatible with the requested Rust type",
9553                            ))
9554                        })
9555                    }
9556                    other => Err(command_mismatch(&other, "side effect")),
9557                };
9558            }
9559        }
9560
9561        let value = callback();
9562        let avro_value = AvroValue::from_serialize(&value)?;
9563        let mut state = self
9564            .state
9565            .lock()
9566            .map_err(|_| Error::WorkflowStatePoisoned)?;
9567        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
9568        state.commands.push(json!({
9569            "type": "record_side_effect",
9570            "result": result,
9571        }));
9572        Ok(value)
9573    }
9574
9575    /// Record or replay a lossless fixed Avro Value side effect.
9576    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
9577    where
9578        F: FnOnce() -> AvroValue,
9579    {
9580        {
9581            let mut state = self
9582                .state
9583                .lock()
9584                .map_err(|_| Error::WorkflowStatePoisoned)?;
9585            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9586                return match recorded {
9587                    RecordedCommand::SideEffect { value, .. } => {
9588                        state.command_cursor += 1;
9589                        Ok(value)
9590                    }
9591                    other => Err(command_mismatch(&other, "side effect")),
9592                };
9593            }
9594        }
9595
9596        let value = callback();
9597        let mut state = self
9598            .state
9599            .lock()
9600            .map_err(|_| Error::WorkflowStatePoisoned)?;
9601        let result = encode_typed_envelope(&value, &state.payload_codec)?;
9602        state.commands.push(json!({
9603            "type": "record_side_effect",
9604            "result": result,
9605        }));
9606        Ok(value)
9607    }
9608
9609    /// Append output items at a deterministic workflow command boundary.
9610    ///
9611    /// Stable idempotency keys are derived from the server-provided durable
9612    /// workflow command identity, command ordinal, and item index. Replay
9613    /// consumes the recorded side effect and never emits another append.
9614    pub fn append_workflow_stream(
9615        &self,
9616        stream_name: impl Into<String>,
9617        items: &[WorkflowStreamAppendItem],
9618        max_pending_items: Option<u64>,
9619    ) -> Result<()> {
9620        if items.is_empty() {
9621            return Err(Error::Codec(
9622                "workflow_stream_items_empty: append requires at least one item".to_string(),
9623            ));
9624        }
9625        if max_pending_items == Some(0) {
9626            return Err(Error::Codec(
9627                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
9628                    .to_string(),
9629            ));
9630        }
9631        let stream_name = stream_name.into();
9632        if stream_name.is_empty() {
9633            return Err(Error::Codec(
9634                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9635            ));
9636        }
9637
9638        let mut state = self
9639            .state
9640            .lock()
9641            .map_err(|_| Error::WorkflowStatePoisoned)?;
9642        let command_ordinal = state.workflow_stream_command_counter;
9643        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9644            state.workflow_stream_command_counter += 1;
9645            return match recorded {
9646                RecordedCommand::SideEffect { .. } => {
9647                    state.command_cursor += 1;
9648                    Ok(())
9649                }
9650                other => Err(command_mismatch(&other, "workflow stream append")),
9651            };
9652        }
9653
9654        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9655        state.workflow_stream_command_counter += 1;
9656        let wire_items = items
9657            .iter()
9658            .enumerate()
9659            .map(|(item_index, item)| {
9660                item.wire_value(Some(format!(
9661                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
9662                )))
9663            })
9664            .collect::<Vec<_>>();
9665        let mut directive = json!({
9666            "operation": "append",
9667            "stream_name": stream_name,
9668            "command_identity": identity,
9669            "command_ordinal": command_ordinal,
9670            "items": wire_items,
9671        });
9672        if let Some(max_pending_items) = max_pending_items {
9673            directive["max_pending_items"] = json!(max_pending_items);
9674        }
9675        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9676        state.commands.push(json!({
9677            "type": "record_side_effect",
9678            "result": result,
9679            "workflow_stream": directive,
9680        }));
9681        Ok(())
9682    }
9683
9684    /// Close a run-scoped output stream at a deterministic command boundary.
9685    pub fn close_workflow_stream(
9686        &self,
9687        stream_name: impl Into<String>,
9688        retention_seconds: Option<u64>,
9689    ) -> Result<()> {
9690        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
9691    }
9692
9693    /// Mark a run-scoped output stream errored at a deterministic command boundary.
9694    pub fn error_workflow_stream(
9695        &self,
9696        stream_name: impl Into<String>,
9697        error_reason: impl Into<String>,
9698        retention_seconds: Option<u64>,
9699    ) -> Result<()> {
9700        let error_reason = error_reason.into();
9701        if error_reason.is_empty() {
9702            return Err(Error::Codec(
9703                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
9704            ));
9705        }
9706        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
9707    }
9708
9709    fn finish_workflow_stream(
9710        &self,
9711        stream_name: String,
9712        error_reason: Option<String>,
9713        retention_seconds: Option<u64>,
9714    ) -> Result<()> {
9715        if stream_name.is_empty() {
9716            return Err(Error::Codec(
9717                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9718            ));
9719        }
9720        if retention_seconds == Some(0) {
9721            return Err(Error::Codec(
9722                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
9723            ));
9724        }
9725        let mut state = self
9726            .state
9727            .lock()
9728            .map_err(|_| Error::WorkflowStatePoisoned)?;
9729        let command_ordinal = state.workflow_stream_command_counter;
9730        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9731            state.workflow_stream_command_counter += 1;
9732            return match recorded {
9733                RecordedCommand::SideEffect { .. } => {
9734                    state.command_cursor += 1;
9735                    Ok(())
9736                }
9737                other => Err(command_mismatch(&other, "workflow stream close")),
9738            };
9739        }
9740        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9741        state.workflow_stream_command_counter += 1;
9742        let mut directive = json!({
9743            "operation": if error_reason.is_some() { "error" } else { "close" },
9744            "stream_name": stream_name,
9745            "command_identity": identity,
9746            "command_ordinal": command_ordinal,
9747        });
9748        if let Some(error_reason) = error_reason {
9749            directive["error_reason"] = json!(error_reason);
9750        }
9751        if let Some(retention_seconds) = retention_seconds {
9752            directive["retention_seconds"] = json!(retention_seconds);
9753        }
9754        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9755        state.commands.push(json!({
9756            "type": "record_side_effect",
9757            "result": result,
9758            "workflow_stream": directive,
9759        }));
9760        Ok(())
9761    }
9762
9763    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
9764        let identity = state.workflow_command_identity.as_str();
9765        if identity.is_empty() {
9766            return Err(Error::MissingWorkflowCommandIdentity);
9767        }
9768        Ok(identity)
9769    }
9770
9771    /// Validate, emit, or replay a typed workflow search-attribute update.
9772    ///
9773    /// The command is non-blocking within a workflow decision, but its
9774    /// `SearchAttributesUpserted` event occupies the same deterministic command
9775    /// stream as activities, timers, conditions, and other durable operations.
9776    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
9777        update.validate()?;
9778        let (attributes, attribute_types) = update.into_wire_parts();
9779        let mut state = self
9780            .state
9781            .lock()
9782            .map_err(|_| Error::WorkflowStatePoisoned)?;
9783
9784        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9785            return match recorded {
9786                RecordedCommand::SearchAttributes {
9787                    sequence,
9788                    attributes: recorded_attributes,
9789                    attribute_types: recorded_attribute_types,
9790                } => {
9791                    if recorded_attributes != attributes {
9792                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9793                            "search_attribute_value_mismatch",
9794                            Some(sequence),
9795                            Some(recorded_attributes.to_string()),
9796                            Some(attributes.to_string()),
9797                            "search-attribute values differ from the recorded durable command",
9798                        )));
9799                    }
9800                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
9801                        if recorded_types != attribute_types {
9802                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9803                                "search_attribute_type_mismatch",
9804                                Some(sequence),
9805                                Some(json!(recorded_types).to_string()),
9806                                Some(json!(attribute_types).to_string()),
9807                                "search-attribute declared types differ from the recorded durable command",
9808                            )));
9809                        }
9810                    }
9811                    state.command_cursor += 1;
9812                    Ok(())
9813                }
9814                other => Err(command_mismatch(&other, "search-attribute update")),
9815            };
9816        }
9817
9818        let mut command = serde_json::Map::from_iter([
9819            ("type".to_string(), json!("upsert_search_attributes")),
9820            ("attributes".to_string(), attributes),
9821        ]);
9822        if !attribute_types.is_empty() {
9823            command.insert("attribute_types".to_string(), json!(attribute_types));
9824        }
9825        state.commands.push(Value::Object(command));
9826        Ok(())
9827    }
9828
9829    /// Record a UUIDv4 once and return the same UUID on every replay.
9830    pub fn uuid_v4(&self) -> Result<Uuid> {
9831        self.side_effect(Uuid::new_v4)
9832    }
9833
9834    /// Select the newest supported version for a change, or replay the version
9835    /// already committed for that stable change ID.
9836    pub fn get_version(
9837        &self,
9838        change_id: impl Into<String>,
9839        min_supported: i32,
9840        max_supported: i32,
9841    ) -> Result<i32> {
9842        let change_id = change_id.into();
9843        if change_id.trim().is_empty() {
9844            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9845                "version_change_id_invalid",
9846                None,
9847                Some("non-empty change ID".to_string()),
9848                Some(change_id),
9849                "version markers require a stable non-empty change ID",
9850            )));
9851        }
9852        if min_supported > max_supported {
9853            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9854                "version_range_invalid",
9855                None,
9856                Some("min_supported <= max_supported".to_string()),
9857                Some(format!("{min_supported}..={max_supported}")),
9858                "version marker supported range is invalid",
9859            )));
9860        }
9861
9862        let mut state = self
9863            .state
9864            .lock()
9865            .map_err(|_| Error::WorkflowStatePoisoned)?;
9866        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
9867            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
9868            return Ok(version);
9869        }
9870
9871        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9872            return match recorded {
9873                RecordedCommand::VersionMarker {
9874                    sequence,
9875                    change_id: recorded_change_id,
9876                    version,
9877                    ..
9878                } => {
9879                    if recorded_change_id != change_id {
9880                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9881                            "version_change_id_mismatch",
9882                            Some(sequence),
9883                            Some(recorded_change_id),
9884                            Some(change_id),
9885                            "recorded version marker change ID differs from current workflow code",
9886                        )));
9887                    }
9888                    ensure_version_supported(
9889                        &change_id,
9890                        version,
9891                        min_supported,
9892                        max_supported,
9893                        sequence,
9894                    )?;
9895                    state.command_cursor += 1;
9896                    state.version_markers.insert(change_id, (version, sequence));
9897                    Ok(version)
9898                }
9899                other => Err(command_mismatch(
9900                    &other,
9901                    format!("version marker:{change_id}"),
9902                )),
9903            };
9904        }
9905
9906        let version = max_supported;
9907        state.commands.push(json!({
9908            "type": "record_version_marker",
9909            "change_id": change_id,
9910            "version": version,
9911            "min_supported": min_supported,
9912            "max_supported": max_supported,
9913        }));
9914        // Sequence numbers are assigned by the server. Zero identifies a marker
9915        // selected in this uncommitted decision batch for duplicate-call checks.
9916        state.version_markers.insert(change_id, (version, 0));
9917        Ok(version)
9918    }
9919
9920    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
9921    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
9922        Ok(self.get_version(change_id, -1, 1)? == 1)
9923    }
9924
9925    /// Keep a patch marker in history after the legacy branch has been removed.
9926    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
9927        self.get_version(change_id, -1, 1).map(|_| ())
9928    }
9929
9930    /// Merge non-indexed workflow memo metadata through durable history.
9931    ///
9932    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
9933    /// public Avro payload envelope consumed by Server and Cloud runtimes.
9934    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
9935        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
9936        let mut state = self
9937            .state
9938            .lock()
9939            .map_err(|_| Error::WorkflowStatePoisoned)?;
9940
9941        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9942            return match recorded {
9943                RecordedCommand::Memo {
9944                    sequence,
9945                    entries: recorded_entries,
9946                } => {
9947                    if recorded_entries != entries {
9948                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9949                            "memo_update_mismatch",
9950                            Some(sequence),
9951                            Some(format!("{recorded_entries:?}")),
9952                            Some(format!("{entries:?}")),
9953                            "recorded memo entries differ from the current workflow update",
9954                        )));
9955                    }
9956                    state.command_cursor += 1;
9957                    Ok(())
9958                }
9959                other => Err(command_mismatch(&other, "memo upsert")),
9960            };
9961        }
9962
9963        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
9964        state.commands.push(json!({
9965            "type": "upsert_memo",
9966            "entries": entries_envelope,
9967        }));
9968        Ok(())
9969    }
9970
9971    /// Start a named durable child on an explicit queue and await its result.
9972    ///
9973    /// The command is recorded in the parent's sequence-ordered durable command
9974    /// stream. Replay keeps a scheduled child pending without emitting another
9975    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
9976    /// values preserve the history payload codec and include both sides of the
9977    /// durable relationship; failures are returned as
9978    /// [`Error::ChildWorkflowFailed`].
9979    ///
9980    /// ```no_run
9981    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
9982    /// # fn configure(client: Client) {
9983    /// let mut worker = Worker::new(client, "parent-workers");
9984    /// worker.register_workflow("order-parent", |ctx, _input| async move {
9985    ///     let child = ctx
9986    ///         .start_child_workflow(
9987    ///             "fulfil-order",
9988    ///             ChildWorkflowOptions::new("fulfilment-workers")
9989    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
9990    ///             json!([{"order_id": "order-42"}]),
9991    ///         )
9992    ///         .await?;
9993    ///     Ok(child.result)
9994    /// });
9995    /// # }
9996    /// ```
9997    pub fn start_child_workflow<T: Serialize>(
9998        &self,
9999        workflow_type: impl Into<String>,
10000        options: ChildWorkflowOptions,
10001        args: T,
10002    ) -> ChildWorkflowCall {
10003        ChildWorkflowCall {
10004            ctx: self.clone(),
10005            workflow_type: workflow_type.into(),
10006            options,
10007            args: Some(AvroValue::from_serialize(&args)),
10008            scheduled: false,
10009            matched_pending: false,
10010            parallel_group_path: Vec::new(),
10011        }
10012    }
10013
10014    pub async fn start_child_workflow_avro_value<T: Serialize>(
10015        &self,
10016        workflow_type: impl Into<String>,
10017        options: ChildWorkflowOptions,
10018        args: T,
10019    ) -> Result<ChildWorkflowAvroResult> {
10020        let mut call = self.start_child_workflow(workflow_type, options, args);
10021        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10022    }
10023
10024    fn take_commands(&self) -> Result<Vec<Value>> {
10025        let mut state = self
10026            .state
10027            .lock()
10028            .map_err(|_| Error::WorkflowStatePoisoned)?;
10029        Ok(std::mem::take(&mut state.commands))
10030    }
10031
10032    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10033        let mut state = self
10034            .state
10035            .lock()
10036            .map_err(|_| Error::WorkflowStatePoisoned)?;
10037
10038        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10039            return Err(command_mismatch(&recorded, "continue as new"));
10040        }
10041        if state.recorded_continue_as_new_sequence.is_some() {
10042            state.continue_as_new_consumed = true;
10043            return Ok(None);
10044        }
10045
10046        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10047        let mut command = serde_json::Map::from_iter([
10048            ("type".to_string(), json!("continue_as_new")),
10049            ("arguments".to_string(), arguments),
10050            ("queue".to_string(), json!(state.task_queue.clone())),
10051        ]);
10052        if let Some(workflow_type) = request.options.workflow_type {
10053            command.insert("workflow_type".to_string(), json!(workflow_type));
10054        }
10055        if let Some(task_queue) = request.options.task_queue {
10056            command.insert("queue".to_string(), json!(task_queue));
10057        }
10058        Ok(Some(Value::Object(command)))
10059    }
10060
10061    fn matched_recorded_pending(&self) -> Result<bool> {
10062        let state = self
10063            .state
10064            .lock()
10065            .map_err(|_| Error::WorkflowStatePoisoned)?;
10066        Ok(state.matched_recorded_pending)
10067    }
10068
10069    fn ensure_history_consumed(&self) -> Result<()> {
10070        let state = self
10071            .state
10072            .lock()
10073            .map_err(|_| Error::WorkflowStatePoisoned)?;
10074        if let Some(replay) = &state.scope_delivery {
10075            if let Some((&sequence, _)) = replay
10076                .canonical
10077                .deliveries
10078                .iter()
10079                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10080            {
10081                return Err(invalid_recorded_history(
10082                    "cancellation_scope_delivery_unconsumed",
10083                    sequence,
10084                    "original scoped delivery",
10085                    "workflow completion",
10086                    "workflow completed without consuming its committed scope delivery",
10087                ));
10088            }
10089        }
10090        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10091            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10092                "recorded_commands_unconsumed",
10093                Some(command.sequence()),
10094                Some(command.shape().to_string()),
10095                Some("workflow completion".to_string()),
10096                "workflow completed before consuming all recorded durable commands",
10097            )));
10098        }
10099        if let Some(delivery) = state
10100            .cancellation_history
10101            .delivery
10102            .as_ref()
10103            .filter(|_| !state.cancellation_consumed)
10104        {
10105            return Err(invalid_recorded_history(
10106                "cooperative_cancellation_unconsumed",
10107                delivery.sequence,
10108                "committed cancellation call",
10109                "workflow completion",
10110                "workflow completed without reaching its committed cancellation boundary",
10111            ));
10112        }
10113        if let Some(sequence) = state
10114            .recorded_continue_as_new_sequence
10115            .filter(|_| !state.continue_as_new_consumed)
10116        {
10117            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10118                "recorded_continue_as_new_unconsumed",
10119                Some(sequence),
10120                Some("continue as new".to_string()),
10121                Some("workflow completion".to_string()),
10122                "workflow completed without consuming its recorded continue-as-new transition",
10123            )));
10124        }
10125        Ok(())
10126    }
10127}
10128
10129fn contiguous_message_stream_count(
10130    pending: &[MessageStreamMessage],
10131    cursor: u64,
10132    max_items: usize,
10133) -> usize {
10134    pending
10135        .iter()
10136        .take(max_items)
10137        .enumerate()
10138        .take_while(|(offset, message)| {
10139            u64::try_from(*offset)
10140                .ok()
10141                .and_then(|offset| cursor.checked_add(offset + 1))
10142                == Some(message.position)
10143        })
10144        .count()
10145}
10146
10147fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10148    matches!(
10149        event.event_type.as_str(),
10150        "ActivityScheduled"
10151            | "TimerScheduled"
10152            | "ChildWorkflowScheduled"
10153            | "SignalWaitOpened"
10154            | "ConditionWaitOpened"
10155            | "SearchAttributesUpserted"
10156            | "SideEffectRecorded"
10157            | "VersionMarkerRecorded"
10158            | "MemoUpserted"
10159            | "WorkflowContinuedAsNew"
10160    )
10161}
10162
10163#[derive(Debug)]
10164struct WorkflowState {
10165    workflow_id: Option<String>,
10166    run_id: Option<String>,
10167    task_queue: String,
10168    payload_codec: String,
10169    history_events: Arc<Vec<HistoryEvent>>,
10170    history_budget: WorkflowHistoryBudget,
10171    cancel_requested: bool,
10172    cancellation_history: CancellationHistory,
10173    cancellation_consumed: bool,
10174    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10175    cancellation_shield_depth: u64,
10176    cancellation_delivery_enabled: bool,
10177    cancellation_delivery_intent: Option<CancellationDelivery>,
10178    cancellation_delivery_command_count: usize,
10179    allow_cancellation_scope_authoring: bool,
10180    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10181    cancellation_scope_memberships: BTreeMap<u64, String>,
10182    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10183    resume_signal: Option<ResumeSignal>,
10184    recorded_commands: Vec<RecordedCommand>,
10185    selection_markers: Vec<SelectionMarker>,
10186    selection_marker_cursor: usize,
10187    cancelled_selection_members: Vec<SelectionCancellation>,
10188    recorded_continue_as_new_sequence: Option<u64>,
10189    continue_as_new_consumed: bool,
10190    command_cursor: usize,
10191    condition_wait_occurrence_counter: u64,
10192    matched_recorded_pending: bool,
10193    version_markers: HashMap<String, (i32, u64)>,
10194    workflow_command_identity: String,
10195    workflow_stream_command_counter: u64,
10196    commands: Vec<Value>,
10197    local_activity_requests: Vec<local_activity::Request>,
10198    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
10199    message_stream_cursors: HashMap<String, u64>,
10200    message_stream_waits: HashMap<String, u64>,
10201}
10202
10203impl WorkflowState {
10204    #[cfg(test)]
10205    fn new(
10206        history: Vec<HistoryEvent>,
10207        task_queue: String,
10208        payload_codec: String,
10209        resume_signal: Option<ResumeSignal>,
10210    ) -> Result<Self> {
10211        Self::new_with_identity(
10212            history,
10213            None,
10214            None,
10215            task_queue,
10216            payload_codec,
10217            resume_signal,
10218        )
10219    }
10220
10221    fn new_with_identity(
10222        history: Vec<HistoryEvent>,
10223        workflow_id: Option<String>,
10224        run_id: Option<String>,
10225        task_queue: String,
10226        payload_codec: String,
10227        resume_signal: Option<ResumeSignal>,
10228    ) -> Result<Self> {
10229        Self::new_with_identity_and_scopes(
10230            history,
10231            workflow_id,
10232            run_id,
10233            task_queue,
10234            payload_codec,
10235            resume_signal,
10236            false,
10237        )
10238    }
10239
10240    fn new_with_identity_and_scopes(
10241        history: Vec<HistoryEvent>,
10242        workflow_id: Option<String>,
10243        run_id: Option<String>,
10244        task_queue: String,
10245        payload_codec: String,
10246        resume_signal: Option<ResumeSignal>,
10247        allow_cancellation_scope_authoring: bool,
10248    ) -> Result<Self> {
10249        Self::new_with_identity_and_scope_delivery(
10250            history,
10251            workflow_id,
10252            run_id,
10253            task_queue,
10254            payload_codec,
10255            resume_signal,
10256            allow_cancellation_scope_authoring,
10257            false,
10258        )
10259    }
10260
10261    fn new_with_identity_and_scope_delivery(
10262        history: Vec<HistoryEvent>,
10263        workflow_id: Option<String>,
10264        run_id: Option<String>,
10265        task_queue: String,
10266        payload_codec: String,
10267        resume_signal: Option<ResumeSignal>,
10268        allow_cancellation_scope_authoring: bool,
10269        allow_cancellation_scope_delivery: bool,
10270    ) -> Result<Self> {
10271        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10272            &history,
10273            allow_cancellation_scope_authoring,
10274            allow_cancellation_scope_delivery,
10275        )?;
10276        let scopes = if allow_cancellation_scope_authoring {
10277            cancellation_scope::CancellationScopeHistory::read(
10278                &history,
10279                run_id.as_deref().unwrap_or_default(),
10280            )?
10281        } else {
10282            cancellation_scope::CancellationScopeHistory::default()
10283        };
10284        let cancellation_history = CancellationHistory::from_events(
10285            &history,
10286            run_id.as_deref().unwrap_or_default(),
10287            None,
10288        )?;
10289        if allow_cancellation_scope_authoring
10290            && cancellation_history.request.is_some()
10291            && !allow_cancellation_scope_delivery
10292        {
10293            return Err(Error::CancellationScopeExecutionUnavailable);
10294        }
10295        let scope_delivery = if allow_cancellation_scope_delivery {
10296            Some(cancellation_scope_replay::ScopeReplay::read(
10297                &history,
10298                &scopes,
10299                run_id.as_deref().unwrap_or_default(),
10300                workflow_id.as_deref().unwrap_or_default(),
10301            )?)
10302        } else {
10303            None
10304        };
10305        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
10306            &history,
10307            &payload_codec,
10308            WorkflowIdentity {
10309                workflow_id: workflow_id.clone(),
10310                run_id: run_id.clone(),
10311            },
10312        )?)?;
10313        for (sequence, opening) in &scopes.openings {
10314            if recorded_commands
10315                .iter()
10316                .any(|command| command.sequence() == *sequence)
10317            {
10318                return Err(invalid_recorded_history(
10319                    "invalid_cancellation_scope_history",
10320                    *sequence,
10321                    "distinct authored scope opening",
10322                    "operation collision",
10323                    "scope opening collides with a command",
10324                ));
10325            }
10326            recorded_commands.push(RecordedCommand::CancellationScope {
10327                sequence: *sequence,
10328                scope_id: opening.scope_id.clone(),
10329                parent_scope_id: opening.parent_scope_id.clone(),
10330                shield_parent: opening.shield_parent,
10331            });
10332        }
10333        recorded_commands.sort_by_key(RecordedCommand::sequence);
10334        if let Some(replay) = &scope_delivery {
10335            replay.bind_commands(&mut recorded_commands)?;
10336        }
10337        let selection_markers = recorded_selection_markers(&history)?;
10338        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
10339        let recorded_continue_as_new = history
10340            .iter()
10341            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
10342            .collect::<Vec<_>>();
10343        if recorded_continue_as_new.len() > 1 {
10344            return Err(invalid_recorded_history(
10345                "duplicate_continue_as_new_transition",
10346                recorded_continue_as_new
10347                    .last()
10348                    .and_then(|event| durable_event_sequence(event))
10349                    .unwrap_or(0),
10350                "one WorkflowContinuedAsNew event",
10351                &format!(
10352                    "{} WorkflowContinuedAsNew events",
10353                    recorded_continue_as_new.len()
10354                ),
10355                "workflow history records one continue-as-new transition more than once",
10356            ));
10357        }
10358        let recorded_continue_as_new_sequence = recorded_continue_as_new
10359            .first()
10360            .map(|event| {
10361                durable_event_sequence(event).ok_or_else(|| {
10362                    Error::NonDeterministicReplay(ReplayFailure::new(
10363                        "continue_as_new_sequence_missing",
10364                        None,
10365                        Some("recorded transition sequence".to_string()),
10366                        Some("missing sequence".to_string()),
10367                        "WorkflowContinuedAsNew history is missing its recorded sequence",
10368                    ))
10369                })
10370            })
10371            .transpose()?;
10372        let mut message_stream_cursors = HashMap::new();
10373        for event in &history {
10374            if !matches!(
10375                event.event_type.as_str(),
10376                "SignalReceived" | "SignalApplied"
10377            ) || event.payload.get("signal_name").and_then(Value::as_str)
10378                != Some(MESSAGE_STREAM_SIGNAL)
10379            {
10380                continue;
10381            }
10382            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
10383            if arguments.len() != 1 {
10384                continue;
10385            }
10386            let envelope = arguments[0].clone().into_json()?;
10387            let Some(envelope) = envelope.as_object() else {
10388                continue;
10389            };
10390            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
10391            {
10392                continue;
10393            }
10394            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10395                continue;
10396            };
10397            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10398            else {
10399                continue;
10400            };
10401            let cursor = message_stream_cursors
10402                .entry(stream_name.to_string())
10403                .or_insert(0);
10404            *cursor = (*cursor).max(through_position);
10405        }
10406        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
10407        let cancel_requested = history.iter().any(|event| {
10408            matches!(
10409                event.event_type.as_str(),
10410                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
10411            )
10412        });
10413        let cancellation_clock = cancellation_history
10414            .request
10415            .as_ref()
10416            .and_then(|request| request.context.as_ref())
10417            .map(|_| {
10418                cancellation_replay_clock::ReplayClock::new(
10419                    &history,
10420                    &recorded_commands,
10421                    cancellation_history.delivery_index,
10422                )
10423            })
10424            .or_else(|| {
10425                scope_delivery.as_ref().map(|_| {
10426                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
10427                })
10428            });
10429        Ok(Self {
10430            workflow_command_identity: String::new(),
10431            workflow_stream_command_counter: 0,
10432            workflow_id,
10433            run_id,
10434            task_queue,
10435            payload_codec,
10436            history_events: Arc::new(history),
10437            history_budget: WorkflowHistoryBudget {
10438                event_count,
10439                ..WorkflowHistoryBudget::default()
10440            },
10441            cancel_requested,
10442            cancellation_history,
10443            cancellation_consumed: false,
10444            cancellation_clock,
10445            cancellation_shield_depth: 0,
10446            cancellation_delivery_enabled: false,
10447            cancellation_delivery_intent: None,
10448            cancellation_delivery_command_count: 0,
10449            allow_cancellation_scope_authoring,
10450            cancellation_scope_opening: None,
10451            cancellation_scope_memberships: scopes.memberships,
10452            scope_delivery,
10453            resume_signal,
10454            recorded_commands,
10455            selection_markers,
10456            selection_marker_cursor: 0,
10457            cancelled_selection_members,
10458            recorded_continue_as_new_sequence,
10459            continue_as_new_consumed: false,
10460            command_cursor: 0,
10461            condition_wait_occurrence_counter: 0,
10462            matched_recorded_pending: false,
10463            version_markers: HashMap::new(),
10464            commands: Vec::new(),
10465            local_activity_requests: Vec::new(),
10466            message_stream_messages: HashMap::new(),
10467            message_stream_cursors,
10468            message_stream_waits: HashMap::new(),
10469        })
10470    }
10471}
10472
10473enum MessageStreamDelivery {
10474    Message(MessageStreamMessage),
10475    Cursor {
10476        stream_name: String,
10477        through_position: u64,
10478    },
10479}
10480
10481fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
10482    if arguments.len() != 1 {
10483        return Ok(None);
10484    }
10485    let envelope = arguments
10486        .into_iter()
10487        .next()
10488        .expect("one argument was checked");
10489    let Some(envelope) = envelope.as_object() else {
10490        return Ok(None);
10491    };
10492    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10493        return Ok(None);
10494    };
10495    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
10496        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10497        else {
10498            return Ok(None);
10499        };
10500        return Ok(Some(MessageStreamDelivery::Cursor {
10501            stream_name: stream_name.to_string(),
10502            through_position,
10503        }));
10504    }
10505    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
10506        return Ok(None);
10507    }
10508    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
10509        return Ok(None);
10510    };
10511    let Some(position) = envelope
10512        .get("position")
10513        .and_then(Value::as_u64)
10514        .filter(|value| *value > 0)
10515    else {
10516        return Ok(None);
10517    };
10518    let Some(payload_envelope) = envelope.get("payload_envelope") else {
10519        return Ok(None);
10520    };
10521    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
10522    else {
10523        return Ok(None);
10524    };
10525    let decoded = decode_avro_value(&payload_envelope)?;
10526    let AvroValue::Array(values) = decoded else {
10527        return Ok(None);
10528    };
10529    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
10530        stream_name: stream_name.to_string(),
10531        message_id: message_id.to_string(),
10532        position,
10533        arguments: values,
10534    })))
10535}
10536
10537#[derive(Clone, Debug)]
10538enum RecordedCommand {
10539    CancellationScope {
10540        sequence: u64,
10541        scope_id: String,
10542        parent_scope_id: String,
10543        shield_parent: bool,
10544    },
10545    CancellationGroup {
10546        sequence: u64,
10547        span: u64,
10548        original: Vec<RecordedCommand>,
10549    },
10550    CancellationBoundary {
10551        sequence: u64,
10552        call_kind: CancellationCallKind,
10553        original: Option<Box<RecordedCommand>>,
10554    },
10555    Activity {
10556        sequence: u64,
10557        activity_type: Option<String>,
10558        cancellation_policy: String,
10559        options: Option<RecordedActivityOptions>,
10560        outcome: Option<ActivityOutcome>,
10561        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10562    },
10563    Timer {
10564        sequence: u64,
10565        delay_seconds: u64,
10566        fired: bool,
10567        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10568    },
10569    ChildWorkflow {
10570        sequence: u64,
10571        workflow_type: Option<String>,
10572        policies: RecordedChildPolicies,
10573        outcome: Option<ChildWorkflowOutcome>,
10574        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10575    },
10576    SignalWait {
10577        sequence: u64,
10578        signal_name: String,
10579        value: Option<Vec<AvroValue>>,
10580        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10581    },
10582    ConditionWait {
10583        sequence: u64,
10584        occurrence_id: String,
10585        condition_key: Option<String>,
10586        predicate_identity: String,
10587        timeout_seconds: Option<u64>,
10588        result: Option<ConditionWaitResult>,
10589        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10590    },
10591    SearchAttributes {
10592        sequence: u64,
10593        attributes: Value,
10594        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
10595    },
10596    SideEffect {
10597        sequence: u64,
10598        value: AvroValue,
10599    },
10600    VersionMarker {
10601        sequence: u64,
10602        change_id: String,
10603        version: i32,
10604    },
10605    Memo {
10606        sequence: u64,
10607        entries: AvroValue,
10608    },
10609}
10610
10611#[derive(Clone, Debug, PartialEq, Eq)]
10612struct SelectionMarker {
10613    selection_group_id: String,
10614    selection_group_base_sequence: u64,
10615    selection_group_size: usize,
10616    member_key: SelectionKey,
10617    member_index: usize,
10618    member_base_sequence: u64,
10619    member_size: usize,
10620    operation_kind: String,
10621    operation_identity: String,
10622    outcome: String,
10623    resolution_event_id: String,
10624    resolution_event_type: String,
10625}
10626
10627#[derive(Clone, Debug, PartialEq, Eq)]
10628struct SelectionCancellation {
10629    selection_group_id: String,
10630    member_key: SelectionKey,
10631    member_index: usize,
10632    member_base_sequence: u64,
10633    member_size: usize,
10634    operation_kind: String,
10635    operation_identity: String,
10636}
10637
10638fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
10639    let mut markers: Vec<SelectionMarker> = Vec::new();
10640    for event in events
10641        .iter()
10642        .filter(|event| event.event_type == "SelectionResolved")
10643    {
10644        let payload = &event.payload;
10645        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
10646        let group_size = required_selection_usize(payload, "selection_group_size")?;
10647        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
10648        let member_size = required_selection_usize(payload, "member_size")?;
10649        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
10650        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
10651            invalid_recorded_history(
10652                "selection_marker_invalid",
10653                base_sequence,
10654                "non-empty selection_group_id",
10655                &payload.to_string(),
10656                "selection winner history is missing its durable group identity",
10657            )
10658        })?;
10659        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
10660        if group_id != expected_group_id {
10661            return Err(invalid_recorded_history(
10662                "selection_marker_invalid",
10663                base_sequence,
10664                &expected_group_id,
10665                &group_id,
10666                "selection winner history contains an incompatible group identity",
10667            ));
10668        }
10669        let group_end = base_sequence
10670            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
10671            .unwrap_or(u64::MAX);
10672        let member_end = member_base_sequence
10673            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
10674            .unwrap_or(u64::MAX);
10675        if member_index >= group_size
10676            || member_base_sequence < base_sequence
10677            || member_end > group_end
10678        {
10679            return Err(invalid_recorded_history(
10680                "selection_marker_invalid",
10681                base_sequence,
10682                "winner member within selection group bounds",
10683                &payload.to_string(),
10684                "selection winner history contains an invalid member range",
10685            ));
10686        }
10687        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
10688            invalid_recorded_history(
10689                "selection_marker_invalid",
10690                base_sequence,
10691                "selection operation kind",
10692                &payload.to_string(),
10693                "selection winner history is missing its operation kind",
10694            )
10695        })?;
10696        if !matches!(
10697            operation_kind.as_str(),
10698            "activity" | "child" | "timer" | "signal" | "condition" | "group"
10699        ) {
10700            return Err(invalid_recorded_history(
10701                "selection_marker_invalid",
10702                base_sequence,
10703                "activity, child, timer, signal, condition, or group",
10704                &operation_kind,
10705                "selection winner history contains an unsupported operation kind",
10706            ));
10707        }
10708        let operation_identity =
10709            payload_string(payload, "operation_identity").ok_or_else(|| {
10710                invalid_recorded_history(
10711                    "selection_marker_invalid",
10712                    base_sequence,
10713                    "non-empty operation identity",
10714                    &payload.to_string(),
10715                    "selection winner history is missing its durable operation identity",
10716                )
10717            })?;
10718        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
10719            invalid_recorded_history(
10720                "selection_marker_invalid",
10721                base_sequence,
10722                "completed or failed selection outcome",
10723                &payload.to_string(),
10724                "selection winner history is missing its outcome",
10725            )
10726        })?;
10727        if !matches!(outcome.as_str(), "completed" | "failed") {
10728            return Err(invalid_recorded_history(
10729                "selection_marker_invalid",
10730                base_sequence,
10731                "completed or failed selection outcome",
10732                &outcome,
10733                "selection winner history contains an unsupported outcome",
10734            ));
10735        }
10736        let marker = SelectionMarker {
10737            selection_group_id: group_id,
10738            selection_group_base_sequence: base_sequence,
10739            selection_group_size: group_size,
10740            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
10741            member_index,
10742            member_base_sequence,
10743            member_size,
10744            operation_kind,
10745            operation_identity,
10746            outcome,
10747            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
10748                || {
10749                    invalid_recorded_history(
10750                        "selection_marker_invalid",
10751                        base_sequence,
10752                        "durable resolution_event_id",
10753                        &payload.to_string(),
10754                        "selection winner history is missing its terminal event identity",
10755                    )
10756                },
10757            )?,
10758            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
10759                || {
10760                    invalid_recorded_history(
10761                        "selection_marker_invalid",
10762                        base_sequence,
10763                        "durable resolution_event_type",
10764                        &payload.to_string(),
10765                        "selection winner history is missing its terminal event type",
10766                    )
10767                },
10768            )?,
10769        };
10770        if let Some(existing) = markers
10771            .iter()
10772            .find(|existing| existing.selection_group_id == marker.selection_group_id)
10773        {
10774            if existing != &marker {
10775                return Err(invalid_recorded_history(
10776                    "selection_marker_conflict",
10777                    base_sequence,
10778                    &format!("one winner for {}", marker.selection_group_id),
10779                    &payload.to_string(),
10780                    "selection history records conflicting winners for one durable group",
10781                ));
10782            }
10783            continue;
10784        }
10785        markers.push(marker);
10786    }
10787    Ok(markers)
10788}
10789
10790fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
10791    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
10792    for event in events
10793        .iter()
10794        .filter(|event| event.event_type == "SelectionOperationCancelled")
10795    {
10796        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
10797            invalid_recorded_history(
10798                "selection_cancellation_invalid",
10799                0,
10800                "non-empty selection_group_id",
10801                &event.payload.to_string(),
10802                "selection cancellation history is missing its group identity",
10803            )
10804        })?;
10805        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
10806        let marker = SelectionCancellation {
10807            selection_group_id: group_id,
10808            member_key: selection_key_from_value(
10809                event.payload.get("member_key"),
10810                member_base_sequence,
10811            )?,
10812            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
10813            member_base_sequence,
10814            member_size: required_selection_usize(&event.payload, "member_size")?,
10815            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
10816                invalid_recorded_history(
10817                    "selection_cancellation_invalid",
10818                    member_base_sequence,
10819                    "selection operation kind",
10820                    &event.payload.to_string(),
10821                    "selection cancellation is missing its operation kind",
10822                )
10823            })?,
10824            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
10825                || {
10826                    invalid_recorded_history(
10827                        "selection_cancellation_invalid",
10828                        member_base_sequence,
10829                        "selection operation identity",
10830                        &event.payload.to_string(),
10831                        "selection cancellation is missing its operation identity",
10832                    )
10833                },
10834            )?,
10835        };
10836        if let Some(existing) = cancelled.iter().find(|recorded| {
10837            recorded.selection_group_id == marker.selection_group_id
10838                && recorded.member_base_sequence == marker.member_base_sequence
10839        }) {
10840            if existing != &marker {
10841                return Err(invalid_recorded_history(
10842                    "selection_cancellation_conflict",
10843                    member_base_sequence,
10844                    "one stable SelectionOperationCancelled marker",
10845                    &event.payload.to_string(),
10846                    "selection cancellation history contains conflicting member metadata",
10847                ));
10848            }
10849        } else {
10850            cancelled.push(marker);
10851        }
10852    }
10853    Ok(cancelled)
10854}
10855
10856fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
10857    payload
10858        .get(field)
10859        .and_then(value_as_u64)
10860        .filter(|value| *value > 0)
10861        .ok_or_else(|| {
10862            invalid_recorded_history(
10863                "selection_marker_invalid",
10864                0,
10865                &format!("positive integer {field}"),
10866                &payload.to_string(),
10867                "selection history contains invalid durable identity metadata",
10868            )
10869        })
10870}
10871
10872fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
10873    required_selection_usize_allow_zero(payload, field).and_then(|value| {
10874        if value > 0 {
10875            Ok(value)
10876        } else {
10877            Err(invalid_recorded_history(
10878                "selection_marker_invalid",
10879                0,
10880                &format!("positive integer {field}"),
10881                &payload.to_string(),
10882                "selection history contains invalid durable identity metadata",
10883            ))
10884        }
10885    })
10886}
10887
10888fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
10889    payload
10890        .get(field)
10891        .and_then(value_as_u64)
10892        .and_then(|value| usize::try_from(value).ok())
10893        .ok_or_else(|| {
10894            invalid_recorded_history(
10895                "selection_marker_invalid",
10896                0,
10897                &format!("non-negative integer {field}"),
10898                &payload.to_string(),
10899                "selection history contains invalid durable identity metadata",
10900            )
10901        })
10902}
10903
10904#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
10905struct RecordedActivityOptions {
10906    task_queue: RecordedSnapshotValue<Option<String>>,
10907    execution_mode: RecordedSnapshotValue<Option<String>>,
10908    retry_policy: ActivityRetrySnapshot,
10909    worker_session: Option<Value>,
10910}
10911
10912#[derive(Clone, Debug)]
10913struct RecordedChildPolicies {
10914    parent_close_policy: String,
10915    cancellation_policy: String,
10916}
10917
10918fn recorded_activity_cancellation_policy(
10919    events: &[&HistoryEvent],
10920    sequence: u64,
10921) -> Result<String> {
10922    let mut policy: Option<String> = None;
10923    for event in events.iter().filter(|event| {
10924        matches!(
10925            event.event_type.as_str(),
10926            "ActivityScheduled"
10927                | "ActivityStarted"
10928                | "ActivityCompleted"
10929                | "ActivityFailed"
10930                | "ActivityTimedOut"
10931                | "ActivityCancelled"
10932        )
10933    }) {
10934        for source in [Some(&event.payload), event.payload.get("activity")]
10935            .into_iter()
10936            .flatten()
10937        {
10938            let Some(value) = source.get("cancellation_policy") else {
10939                continue;
10940            };
10941            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
10942                value.as_str()
10943            else {
10944                return Err(invalid_recorded_history(
10945                    "invalid_activity_cancellation_policy_history",
10946                    sequence,
10947                    "supported Activity cancellation policy",
10948                    &value.to_string(),
10949                    "Activity history contains an invalid cancellation policy",
10950                ));
10951            };
10952            if let Some(previous) = policy.as_deref() {
10953                if previous != incoming {
10954                    return Err(invalid_recorded_history(
10955                        "activity_cancellation_policy_history_conflict",
10956                        sequence,
10957                        previous,
10958                        incoming,
10959                        "Activity cancellation policy changed between history events",
10960                    ));
10961                }
10962            }
10963            policy = Some(incoming.to_string());
10964        }
10965        policy.get_or_insert_with(|| "try_cancel".to_string());
10966    }
10967    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
10968}
10969
10970fn recorded_child_policy_value<'a>(
10971    payload: &'a Value,
10972    field: &str,
10973    sequence: u64,
10974) -> Result<Option<&'a str>> {
10975    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
10976        return Ok(None);
10977    };
10978    let valid = match (field, value.as_str()) {
10979        (
10980            "parent_close_policy",
10981            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
10982        ) => true,
10983        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
10984            true
10985        }
10986        _ => false,
10987    };
10988    if !valid {
10989        return Err(invalid_recorded_history(
10990            "invalid_child_workflow_policy_history",
10991            sequence,
10992            "supported child workflow policy",
10993            &value.to_string(),
10994            "child workflow history contains an invalid policy",
10995        ));
10996    }
10997    Ok(value.as_str())
10998}
10999
11000fn recorded_child_policies(
11001    events: &[&HistoryEvent],
11002    scheduled: &HistoryEvent,
11003    sequence: u64,
11004) -> Result<RecordedChildPolicies> {
11005    let parent_close_policy =
11006        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11007            .unwrap_or("abandon")
11008            .to_string();
11009    let cancellation_policy =
11010        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11011            .unwrap_or("abandon")
11012            .to_string();
11013    for event in events {
11014        for (field, expected) in [
11015            ("parent_close_policy", parent_close_policy.as_str()),
11016            ("cancellation_policy", cancellation_policy.as_str()),
11017        ] {
11018            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11019                if actual != expected {
11020                    return Err(invalid_recorded_history(
11021                        "child_workflow_policy_history_conflict",
11022                        sequence,
11023                        expected,
11024                        actual,
11025                        "child workflow policy changed between history events",
11026                    ));
11027                }
11028            }
11029        }
11030    }
11031    Ok(RecordedChildPolicies {
11032        parent_close_policy,
11033        cancellation_policy,
11034    })
11035}
11036
11037fn ensure_child_policies_match(
11038    sequence: u64,
11039    recorded: &RecordedChildPolicies,
11040    current: &ChildWorkflowOptions,
11041) -> Result<()> {
11042    for (field, expected, actual) in [
11043        (
11044            "parent_close_policy",
11045            recorded.parent_close_policy.as_str(),
11046            current.parent_close_policy.as_str(),
11047        ),
11048        (
11049            "cancellation_policy",
11050            recorded.cancellation_policy.as_str(),
11051            current.cancellation_policy.as_str(),
11052        ),
11053    ] {
11054        if expected != actual {
11055            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11056                "child_workflow_policy_changed",
11057                Some(sequence),
11058                Some(expected.to_string()),
11059                Some(actual.to_string()),
11060                format!("child workflow {field} changed during replay"),
11061            )));
11062        }
11063    }
11064    Ok(())
11065}
11066
11067#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11068enum RecordedSnapshotValue<T> {
11069    /// Older history did not persist this field, so it cannot constrain replay.
11070    Unknown,
11071    Known(T),
11072}
11073
11074impl<T: PartialEq> RecordedSnapshotValue<T> {
11075    fn matches_current(&self, current: &Self) -> bool {
11076        match self {
11077            Self::Unknown => true,
11078            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11079        }
11080    }
11081}
11082
11083#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11084struct ActivityRetrySnapshot {
11085    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11086    max_attempts: RecordedSnapshotValue<Option<u64>>,
11087    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11088    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11089    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11090    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11091    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11092    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11093}
11094
11095impl ActivityRetrySnapshot {
11096    fn matches_current(&self, current: &Self) -> bool {
11097        self.snapshot_version
11098            .matches_current(&current.snapshot_version)
11099            && self.max_attempts.matches_current(&current.max_attempts)
11100            && self
11101                .backoff_seconds
11102                .matches_current(&current.backoff_seconds)
11103            && self
11104                .start_to_close_timeout
11105                .matches_current(&current.start_to_close_timeout)
11106            && self
11107                .schedule_to_start_timeout
11108                .matches_current(&current.schedule_to_start_timeout)
11109            && self
11110                .schedule_to_close_timeout
11111                .matches_current(&current.schedule_to_close_timeout)
11112            && self
11113                .heartbeat_timeout
11114                .matches_current(&current.heartbeat_timeout)
11115            && self
11116                .non_retryable_error_types
11117                .matches_current(&current.non_retryable_error_types)
11118    }
11119}
11120
11121fn recorded_optional_u64(
11122    object: Option<&serde_json::Map<String, Value>>,
11123    field: &str,
11124) -> RecordedSnapshotValue<Option<u64>> {
11125    match object.and_then(|object| object.get(field)) {
11126        None => RecordedSnapshotValue::Unknown,
11127        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11128        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11129    }
11130}
11131
11132fn recorded_optional_string(
11133    object: &serde_json::Map<String, Value>,
11134    field: &str,
11135) -> RecordedSnapshotValue<Option<String>> {
11136    match object.get(field) {
11137        None => RecordedSnapshotValue::Unknown,
11138        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11139        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11140    }
11141}
11142
11143fn recorded_activity_execution_mode(
11144    events: &[&HistoryEvent],
11145    sequence: u64,
11146) -> Result<RecordedSnapshotValue<Option<String>>> {
11147    let mut recorded = RecordedSnapshotValue::Unknown;
11148    for event in events {
11149        for object in [
11150            event.payload.as_object(),
11151            event.payload.get("activity").and_then(Value::as_object),
11152        ]
11153        .into_iter()
11154        .flatten()
11155        {
11156            let mode = match object.get("execution_mode") {
11157                None => None,
11158                Some(Value::Null) => Some(None),
11159                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11160                Some(_) => {
11161                    return Err(invalid_recorded_history(
11162                        "activity_execution_mode_invalid",
11163                        sequence,
11164                        "null or a non-empty execution mode",
11165                        "invalid execution_mode",
11166                        "activity history contains an invalid execution mode",
11167                    ))
11168                }
11169            };
11170            let legacy_mode = match object.get("local_activity") {
11171                None => None,
11172                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11173                Some(_) => {
11174                    return Err(invalid_recorded_history(
11175                        "activity_execution_mode_invalid",
11176                        sequence,
11177                        "boolean local_activity",
11178                        "invalid local_activity",
11179                        "activity history contains an invalid local-activity marker",
11180                    ))
11181                }
11182            };
11183            for mode in [mode, legacy_mode].into_iter().flatten() {
11184                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
11185                {
11186                    return Err(invalid_recorded_history(
11187                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
11188                        "activity lifecycle events at one workflow sequence disagree on execution mode",
11189                    ));
11190                }
11191                recorded = RecordedSnapshotValue::Known(mode);
11192            }
11193        }
11194    }
11195    Ok(recorded)
11196}
11197
11198fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
11199    let policy = policy.and_then(Value::as_object);
11200    let backoff_seconds = policy
11201        .and_then(|policy| policy.get("backoff_seconds"))
11202        .and_then(Value::as_array)
11203        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11204        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
11205    let mut non_retryable_error_types = Vec::new();
11206    for error_type in policy
11207        .and_then(|policy| policy.get("non_retryable_error_types"))
11208        .and_then(Value::as_array)
11209        .into_iter()
11210        .flatten()
11211        .filter_map(Value::as_str)
11212        .map(str::trim)
11213        .filter(|error_type| !error_type.is_empty())
11214    {
11215        if !non_retryable_error_types
11216            .iter()
11217            .any(|recorded| recorded == error_type)
11218        {
11219            non_retryable_error_types.push(error_type.to_string());
11220        }
11221    }
11222
11223    ActivityRetrySnapshot {
11224        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
11225        max_attempts: recorded_optional_u64(policy, "max_attempts"),
11226        backoff_seconds,
11227        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
11228        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
11229        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
11230        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
11231        non_retryable_error_types: if policy
11232            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
11233        {
11234            RecordedSnapshotValue::Known(non_retryable_error_types)
11235        } else {
11236            RecordedSnapshotValue::Unknown
11237        },
11238    }
11239}
11240
11241fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
11242    let policy = options.retry_policy.as_ref();
11243    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
11244        Some(Value::Null) => None,
11245        Some(value) => value_as_u64(value),
11246        None => Some(1),
11247    };
11248    let backoff_seconds = policy
11249        .and_then(|policy| policy.get("backoff_seconds"))
11250        .and_then(Value::as_array)
11251        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11252        .unwrap_or_default();
11253    let non_retryable_error_types = policy
11254        .and_then(|policy| policy.get("non_retryable_error_types"))
11255        .and_then(Value::as_array)
11256        .into_iter()
11257        .flatten()
11258        .filter_map(Value::as_str)
11259        .map(str::to_string)
11260        .collect();
11261
11262    ActivityRetrySnapshot {
11263        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
11264        max_attempts: RecordedSnapshotValue::Known(max_attempts),
11265        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
11266        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
11267        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
11268        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
11269        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
11270        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
11271    }
11272}
11273
11274fn activity_options_description(options: &RecordedActivityOptions) -> String {
11275    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
11276}
11277
11278impl RecordedCommand {
11279    fn sequence(&self) -> u64 {
11280        match self {
11281            Self::CancellationGroup { sequence, .. }
11282            | Self::CancellationScope { sequence, .. }
11283            | Self::CancellationBoundary { sequence, .. }
11284            | Self::Activity { sequence, .. }
11285            | Self::Timer { sequence, .. }
11286            | Self::ChildWorkflow { sequence, .. }
11287            | Self::SignalWait { sequence, .. }
11288            | Self::ConditionWait { sequence, .. }
11289            | Self::SearchAttributes { sequence, .. }
11290            | Self::SideEffect { sequence, .. }
11291            | Self::VersionMarker { sequence, .. }
11292            | Self::Memo { sequence, .. } => *sequence,
11293        }
11294    }
11295
11296    fn shape(&self) -> &'static str {
11297        match self {
11298            Self::CancellationScope { .. } => "cancellation scope",
11299            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
11300                "cooperative cancellation"
11301            }
11302            Self::Activity { .. } => "activity",
11303            Self::Timer { .. } => "timer",
11304            Self::ChildWorkflow { .. } => "child workflow",
11305            Self::SignalWait { .. } => "signal wait",
11306            Self::ConditionWait { .. } => "condition wait",
11307            Self::SearchAttributes { .. } => "search-attribute update",
11308            Self::SideEffect { .. } => "side effect",
11309            Self::VersionMarker { .. } => "version marker",
11310            Self::Memo { .. } => "memo upsert",
11311        }
11312    }
11313}
11314
11315fn ensure_version_supported(
11316    change_id: &str,
11317    version: i32,
11318    min_supported: i32,
11319    max_supported: i32,
11320    sequence: u64,
11321) -> Result<()> {
11322    if (min_supported..=max_supported).contains(&version) {
11323        return Ok(());
11324    }
11325    Err(Error::NonDeterministicReplay(ReplayFailure::new(
11326        "version_marker_incompatible_range",
11327        (sequence != 0).then_some(sequence),
11328        Some(format!("{min_supported}..={max_supported}")),
11329        Some(format!("{change_id}:{version}")),
11330        "recorded workflow version is outside the range supported by current code",
11331    )))
11332}
11333
11334#[derive(Clone, Debug)]
11335struct ResumeSignal {
11336    signal_name: String,
11337    arguments: Vec<AvroValue>,
11338}
11339
11340const MAX_PARALLEL_OPERATIONS: usize = 1000;
11341
11342fn parallel_group_prefix(kind: &str) -> &'static str {
11343    match kind {
11344        "activity" => "parallel-activities",
11345        "child" => "parallel-children",
11346        "timer" => "parallel-timers",
11347        _ => "parallel-calls",
11348    }
11349}
11350
11351fn parallel_group_entry(
11352    base_sequence: u64,
11353    size: usize,
11354    index: usize,
11355    kind: &str,
11356) -> ParallelGroupMetadata {
11357    ParallelGroupMetadata {
11358        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
11359        parallel_group_kind: kind.to_string(),
11360        parallel_group_base_sequence: base_sequence,
11361        parallel_group_size: size,
11362        parallel_group_index: index,
11363        parallel_group_mode: None,
11364        selection_member_key: None,
11365        selection_member_index: None,
11366        selection_member_base_sequence: None,
11367        selection_member_size: None,
11368        selection_member_kind: None,
11369    }
11370}
11371
11372struct SelectionMemberMetadata {
11373    key: SelectionKey,
11374    index: usize,
11375    base_sequence: u64,
11376    size: usize,
11377    kind: String,
11378}
11379
11380fn selection_group_entry(
11381    base_sequence: u64,
11382    size: usize,
11383    index: usize,
11384    kind: &str,
11385    member: &SelectionMemberMetadata,
11386) -> ParallelGroupMetadata {
11387    ParallelGroupMetadata {
11388        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
11389        parallel_group_kind: kind.to_string(),
11390        parallel_group_base_sequence: base_sequence,
11391        parallel_group_size: size,
11392        parallel_group_index: index,
11393        parallel_group_mode: Some("select".to_string()),
11394        selection_member_key: Some(member.key.clone()),
11395        selection_member_index: Some(member.index),
11396        selection_member_base_sequence: Some(member.base_sequence),
11397        selection_member_size: Some(member.size),
11398        selection_member_kind: Some(member.kind.clone()),
11399    }
11400}
11401
11402fn apply_parallel_group_path(
11403    command: &mut serde_json::Map<String, Value>,
11404    path: &[ParallelGroupMetadata],
11405) {
11406    let Some(inner) = path.last() else {
11407        return;
11408    };
11409    command.insert(
11410        "parallel_group_id".to_string(),
11411        json!(inner.parallel_group_id),
11412    );
11413    command.insert(
11414        "parallel_group_kind".to_string(),
11415        json!(inner.parallel_group_kind),
11416    );
11417    command.insert(
11418        "parallel_group_base_sequence".to_string(),
11419        json!(inner.parallel_group_base_sequence),
11420    );
11421    command.insert(
11422        "parallel_group_size".to_string(),
11423        json!(inner.parallel_group_size),
11424    );
11425    command.insert(
11426        "parallel_group_index".to_string(),
11427        json!(inner.parallel_group_index),
11428    );
11429    if let Some(mode) = &inner.parallel_group_mode {
11430        command.insert("parallel_group_mode".to_string(), json!(mode));
11431    }
11432    if let Some(key) = &inner.selection_member_key {
11433        command.insert("selection_member_key".to_string(), json!(key));
11434    }
11435    if let Some(index) = inner.selection_member_index {
11436        command.insert("selection_member_index".to_string(), json!(index));
11437    }
11438    if let Some(base_sequence) = inner.selection_member_base_sequence {
11439        command.insert(
11440            "selection_member_base_sequence".to_string(),
11441            json!(base_sequence),
11442        );
11443    }
11444    if let Some(size) = inner.selection_member_size {
11445        command.insert("selection_member_size".to_string(), json!(size));
11446    }
11447    if let Some(kind) = &inner.selection_member_kind {
11448        command.insert("selection_member_kind".to_string(), json!(kind));
11449    }
11450    command.insert("parallel_group_path".to_string(), json!(path));
11451}
11452
11453fn ensure_parallel_path_matches(
11454    sequence: u64,
11455    recorded: Option<&[ParallelGroupMetadata]>,
11456    expected: &[ParallelGroupMetadata],
11457) -> Result<()> {
11458    match (recorded, expected.is_empty()) {
11459        (None, true) => Ok(()),
11460        (Some(recorded), false) if recorded == expected => Ok(()),
11461        (None, false) => Err(invalid_recorded_history(
11462            "parallel_group_metadata_missing",
11463            sequence,
11464            &serde_json::to_string(expected).unwrap_or_default(),
11465            "<missing>",
11466            "recorded parallel member is missing its durable group path",
11467        )),
11468        (Some(recorded), true) => Err(invalid_recorded_history(
11469            "parallel_group_shape_mismatch",
11470            sequence,
11471            "sequential command",
11472            &serde_json::to_string(recorded).unwrap_or_default(),
11473            "recorded command belonged to a parallel group but current code schedules it sequentially",
11474        )),
11475        (Some(recorded), false) => Err(invalid_recorded_history(
11476            "parallel_group_shape_mismatch",
11477            sequence,
11478            &serde_json::to_string(recorded).unwrap_or_default(),
11479            &serde_json::to_string(expected).unwrap_or_default(),
11480            "recorded parallel-group identity or path changed during replay",
11481        )),
11482    }
11483}
11484
11485#[derive(Clone, Debug)]
11486enum ParallelShape {
11487    Leaf,
11488    Group(Vec<ParallelShape>),
11489}
11490
11491struct ParallelDescriptor {
11492    operation: ParallelOperation,
11493    offset: usize,
11494    member_path: Vec<usize>,
11495    group_path: Vec<ParallelGroupMetadata>,
11496}
11497
11498fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
11499    operations
11500        .iter()
11501        .map(|operation| match operation {
11502            ParallelOperation::Group(children) => parallel_leaf_count(children),
11503            _ => 1,
11504        })
11505        .sum()
11506}
11507
11508fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
11509    match operation {
11510        ParallelOperation::Activity { .. } => Some("activity"),
11511        ParallelOperation::ChildWorkflow { .. } => Some("child"),
11512        ParallelOperation::Timer(_) => Some("timer"),
11513        ParallelOperation::Signal(_) => Some("signal"),
11514        ParallelOperation::Condition { .. } => Some("condition"),
11515        ParallelOperation::Group(children) => parallel_group_kind(children),
11516    }
11517}
11518
11519fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
11520    let mut kind = None;
11521    for operation in operations {
11522        let Some(operation_kind) = parallel_operation_kind(operation) else {
11523            continue;
11524        };
11525        match kind {
11526            None => kind = Some(operation_kind),
11527            Some(current) if current == operation_kind => {}
11528            Some(_) => return Some("mixed"),
11529        }
11530    }
11531    kind
11532}
11533
11534fn validate_parallel_operations(
11535    operations: &[ParallelOperation],
11536    member_path: &mut Vec<usize>,
11537    root: bool,
11538) -> Result<()> {
11539    let leaves = parallel_leaf_count(operations);
11540    if leaves > MAX_PARALLEL_OPERATIONS {
11541        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11542            reason: "fan_out_limit_exceeded",
11543            member_path: member_path.clone(),
11544            message: format!(
11545                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
11546            ),
11547        }));
11548    }
11549    if !root && operations.is_empty() {
11550        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11551            reason: "nested_group_empty",
11552            member_path: member_path.clone(),
11553            message: "a nested group must contain at least one durable leaf".to_string(),
11554        }));
11555    }
11556
11557    for (index, operation) in operations.iter().enumerate() {
11558        member_path.push(index);
11559        match operation {
11560            ParallelOperation::Activity {
11561                options, arguments, ..
11562            } => {
11563                options
11564                    .validate()
11565                    .map_err(|error| Error::InvalidActivityOptions(error))?;
11566                if let Err(error) = arguments {
11567                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11568                        reason: "arguments_invalid",
11569                        member_path: member_path.clone(),
11570                        message: error.to_string(),
11571                    }));
11572                }
11573            }
11574            ParallelOperation::ChildWorkflow {
11575                options, arguments, ..
11576            } => {
11577                validate_parallel_child_options(options)?;
11578                if let Err(error) = arguments {
11579                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11580                        reason: "arguments_invalid",
11581                        member_path: member_path.clone(),
11582                        message: error.to_string(),
11583                    }));
11584                }
11585            }
11586            ParallelOperation::Timer(duration)
11587                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
11588            {
11589                return Err(Error::TimerDurationOverflow);
11590            }
11591            ParallelOperation::Timer(_) => {}
11592            ParallelOperation::Signal(signal_name) => {
11593                validate_user_signal_name(signal_name)?;
11594                if signal_name.trim().is_empty() {
11595                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11596                        reason: "signal_name_empty",
11597                        member_path: member_path.clone(),
11598                        message: "signal wait name must not be empty".to_string(),
11599                    }));
11600                }
11601            }
11602            ParallelOperation::Condition { options, .. } => {
11603                options.validate()?;
11604            }
11605            ParallelOperation::Group(children) => {
11606                validate_parallel_operations(children, member_path, false)?;
11607            }
11608        }
11609        member_path.pop();
11610    }
11611    Ok(())
11612}
11613
11614fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
11615    if options.task_queue.trim().is_empty() {
11616        return Err(Error::InvalidChildWorkflowOptions(
11617            "task_queue must not be empty".to_string(),
11618        ));
11619    }
11620    for (name, value) in [
11621        (
11622            "execution_timeout_seconds",
11623            options.execution_timeout_seconds,
11624        ),
11625        ("run_timeout_seconds", options.run_timeout_seconds),
11626    ] {
11627        if value == Some(0) {
11628            return Err(Error::InvalidChildWorkflowOptions(format!(
11629                "{name} must be at least 1"
11630            )));
11631        }
11632    }
11633    if options
11634        .retry_policy
11635        .as_ref()
11636        .is_some_and(|policy| policy.max_attempts == Some(0))
11637    {
11638        return Err(Error::InvalidChildWorkflowOptions(
11639            "retry_policy.max_attempts must be at least 1".to_string(),
11640        ));
11641    }
11642    Ok(())
11643}
11644
11645fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
11646    ParallelShape::Group(
11647        operations
11648            .iter()
11649            .map(|operation| match operation {
11650                ParallelOperation::Group(children) => parallel_shape(children),
11651                _ => ParallelShape::Leaf,
11652            })
11653            .collect(),
11654    )
11655}
11656
11657fn parallel_descriptors(
11658    operations: Vec<ParallelOperation>,
11659    base_sequence: u64,
11660) -> Result<Vec<ParallelDescriptor>> {
11661    let size = parallel_leaf_count(&operations);
11662    let kind = parallel_group_kind(&operations).unwrap_or("activity");
11663    let mut descriptors = Vec::with_capacity(size);
11664    let mut cursor = 0;
11665
11666    for (index, operation) in operations.into_iter().enumerate() {
11667        match operation {
11668            ParallelOperation::Group(children) => {
11669                let child_base = base_sequence
11670                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
11671                    .ok_or(Error::TimerDurationOverflow)?;
11672                for mut descriptor in parallel_descriptors(children, child_base)? {
11673                    let outer_index = cursor + descriptor.offset;
11674                    descriptor.group_path.insert(
11675                        0,
11676                        parallel_group_entry(base_sequence, size, outer_index, kind),
11677                    );
11678                    descriptor.member_path.insert(0, index);
11679                    descriptor.offset = outer_index;
11680                    descriptors.push(descriptor);
11681                }
11682                cursor = descriptors.len();
11683            }
11684            operation => {
11685                descriptors.push(ParallelDescriptor {
11686                    operation,
11687                    offset: cursor,
11688                    member_path: vec![index],
11689                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
11690                });
11691                cursor += 1;
11692            }
11693        }
11694    }
11695    Ok(descriptors)
11696}
11697
11698enum ParallelLeafCall {
11699    Activity(ActivityCall),
11700    ChildWorkflow(ChildWorkflowCall),
11701    Timer(TimerCall),
11702    Signal(SignalCall),
11703    Condition(ConditionWaitCall),
11704}
11705
11706fn parallel_leaf_call(
11707    ctx: &WorkflowContext,
11708    operation: ParallelOperation,
11709    parallel_group_path: Vec<ParallelGroupMetadata>,
11710) -> ParallelLeafCall {
11711    match operation {
11712        ParallelOperation::Activity {
11713            activity_type,
11714            options,
11715            arguments,
11716        } => ParallelLeafCall::Activity(ActivityCall {
11717            ctx: ctx.clone(),
11718            activity_type,
11719            options,
11720            worker_session: None,
11721            args: Some(arguments),
11722            scheduled: false,
11723            local: false,
11724            local_result: None,
11725            parallel_group_path,
11726        }),
11727        ParallelOperation::ChildWorkflow {
11728            workflow_type,
11729            options,
11730            arguments,
11731        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
11732            ctx: ctx.clone(),
11733            workflow_type,
11734            options,
11735            args: Some(arguments),
11736            scheduled: false,
11737            matched_pending: false,
11738            parallel_group_path,
11739        }),
11740        ParallelOperation::Timer(duration) => {
11741            let delay_seconds = duration
11742                .as_secs()
11743                .checked_add(u64::from(duration.subsec_nanos() > 0));
11744            ParallelLeafCall::Timer(TimerCall {
11745                ctx: ctx.clone(),
11746                delay_seconds,
11747                scheduled: false,
11748                matched_pending: false,
11749                parallel_group_path,
11750            })
11751        }
11752        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
11753            ctx: ctx.clone(),
11754            signal_name,
11755            runtime_reserved_allowed: false,
11756            opened_wait: false,
11757            matched_pending: false,
11758            parallel_group_path,
11759        }),
11760        ParallelOperation::Condition { options, predicate } => {
11761            ParallelLeafCall::Condition(ConditionWaitCall {
11762                ctx: ctx.clone(),
11763                options,
11764                predicate,
11765                occurrence_id: None,
11766                opened_wait: false,
11767                parallel_group_path,
11768            })
11769        }
11770        ParallelOperation::Group(_) => {
11771            unreachable!("parallel descriptors contain only durable leaves")
11772        }
11773    }
11774}
11775
11776impl ParallelLeafCall {
11777    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
11778        match self {
11779            Self::Activity(call) => Pin::new(call)
11780                .poll_avro_value(cx)
11781                .map_ok(ParallelAvroResult::Activity),
11782            Self::ChildWorkflow(call) => Pin::new(call)
11783                .poll_avro_value(cx)
11784                .map_ok(ParallelAvroResult::ChildWorkflow),
11785            Self::Timer(call) => Pin::new(call)
11786                .poll(cx)
11787                .map_ok(|()| ParallelAvroResult::Timer),
11788            Self::Signal(call) => Pin::new(call)
11789                .poll_avro_value(cx)
11790                .map_ok(ParallelAvroResult::Signal),
11791            Self::Condition(call) => Pin::new(call)
11792                .poll(cx)
11793                .map_ok(ParallelAvroResult::Condition),
11794        }
11795    }
11796}
11797
11798struct ParallelLeaf {
11799    call: ParallelLeafCall,
11800    sequence: u64,
11801    member_path: Vec<usize>,
11802    group_path: Vec<ParallelGroupMetadata>,
11803    result: Option<ParallelAvroResult>,
11804}
11805
11806/// Future returned by [`WorkflowContext::parallel`].
11807pub struct ParallelCall {
11808    ctx: WorkflowContext,
11809    operations: Option<Vec<ParallelOperation>>,
11810    shape: Option<ParallelShape>,
11811    leaves: Vec<ParallelLeaf>,
11812    pending_scope_delivery: bool,
11813    worker_session: Option<WorkerSessionOptions>,
11814}
11815
11816impl ParallelCall {
11817    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
11818        Self {
11819            ctx,
11820            operations: Some(operations),
11821            shape: None,
11822            leaves: Vec::new(),
11823            pending_scope_delivery: false,
11824            worker_session: None,
11825        }
11826    }
11827
11828    fn initialize(&mut self) -> Result<()> {
11829        if let Some(session) = &self.worker_session {
11830            session.to_wire()?;
11831        }
11832        let operations = self.operations.take().unwrap_or_default();
11833        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
11834        self.shape = Some(parallel_shape(&operations));
11835        if operations.is_empty() {
11836            return Ok(());
11837        }
11838
11839        let base_sequence = {
11840            let state = self
11841                .ctx
11842                .state
11843                .lock()
11844                .map_err(|_| Error::WorkflowStatePoisoned)?;
11845            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
11846                recorded.sequence()
11847            } else {
11848                let last = state
11849                    .recorded_commands
11850                    .last()
11851                    .map(RecordedCommand::sequence)
11852                    .unwrap_or(0);
11853                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
11854                    .and_then(|sequence| sequence.checked_add(1))
11855                    .ok_or_else(|| {
11856                        Error::InvalidParallelGroup(ParallelGroupError {
11857                            reason: "sequence_overflow",
11858                            member_path: Vec::new(),
11859                            message: "parallel group sequence identity overflowed u64".to_string(),
11860                        })
11861                    })?
11862            }
11863        };
11864
11865        let descriptors = parallel_descriptors(operations, base_sequence)?;
11866        {
11867            let mut state = self
11868                .ctx
11869                .state
11870                .lock()
11871                .map_err(|_| Error::WorkflowStatePoisoned)?;
11872            let cursor = state.command_cursor;
11873            self.ctx.validate_scope_membership(&mut state, cursor)?;
11874            if state.prepare_parallel_scope_cancellation(&descriptors)? {
11875                self.pending_scope_delivery = true;
11876                return Ok(());
11877            }
11878            state.expand_cancellation_group(&descriptors)?;
11879            state.prepare_group_cancellation(&descriptors)?;
11880        }
11881        self.leaves = descriptors
11882            .into_iter()
11883            .map(|descriptor| {
11884                let mut call = parallel_leaf_call(
11885                    &self.ctx,
11886                    descriptor.operation,
11887                    descriptor.group_path.clone(),
11888                );
11889                if let (Some(session), ParallelLeafCall::Activity(activity)) =
11890                    (&self.worker_session, &mut call)
11891                {
11892                    activity.worker_session = Some(session.clone());
11893                }
11894                ParallelLeaf {
11895                    call,
11896                    sequence: base_sequence + descriptor.offset as u64,
11897                    member_path: descriptor.member_path,
11898                    group_path: descriptor.group_path,
11899                    result: None,
11900                }
11901            })
11902            .collect();
11903        Ok(())
11904    }
11905
11906    fn poll_avro_value(
11907        mut self: Pin<&mut Self>,
11908        cx: &mut TaskContext<'_>,
11909    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
11910        if self.operations.is_some() {
11911            if let Err(error) = self.initialize() {
11912                return Poll::Ready(Err(error));
11913            }
11914        }
11915        if self.pending_scope_delivery {
11916            return Poll::Pending;
11917        }
11918        if self.leaves.is_empty() {
11919            return Poll::Ready(Ok(Vec::new()));
11920        }
11921
11922        let mut failures = Vec::new();
11923        let mut pending = false;
11924        for (index, leaf) in self.leaves.iter_mut().enumerate() {
11925            if leaf.result.is_some() {
11926                continue;
11927            }
11928            match leaf.call.poll_avro_value(cx) {
11929                Poll::Ready(Ok(result)) => leaf.result = Some(result),
11930                Poll::Ready(Err(error)) => failures.push((index, error)),
11931                Poll::Pending => pending = true,
11932            }
11933        }
11934
11935        if !failures.is_empty() {
11936            if let Some(position) = failures
11937                .iter()
11938                .position(|(_, error)| workflow_task_integrity_error(error))
11939            {
11940                return Poll::Ready(Err(failures.remove(position).1));
11941            }
11942            if self
11943                .ctx
11944                .state
11945                .lock()
11946                .map_err(|_| Error::WorkflowStatePoisoned)?
11947                .cancellation_delivery_intent
11948                .is_some()
11949            {
11950                return Poll::Pending;
11951            }
11952            if let Some(position) = failures
11953                .iter()
11954                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
11955            {
11956                return Poll::Ready(Err(failures.remove(position).1));
11957            }
11958            failures.sort_by_key(|(index, _)| *index);
11959            let (failed_index, cause) = failures.remove(0);
11960            let failed = &self.leaves[failed_index];
11961            let completed = self
11962                .leaves
11963                .iter()
11964                .filter_map(|leaf| {
11965                    leaf.result
11966                        .clone()
11967                        .and_then(|result| result.into_json_result().ok())
11968                        .map(|result| ParallelCompletion {
11969                            member_path: leaf.member_path.clone(),
11970                            result,
11971                        })
11972                })
11973                .collect();
11974            let group_id = failed
11975                .group_path
11976                .first()
11977                .map(|entry| entry.parallel_group_id.clone())
11978                .unwrap_or_default();
11979            let sequences = self
11980                .leaves
11981                .iter()
11982                .map(|leaf| leaf.sequence)
11983                .collect::<Vec<_>>();
11984            self.ctx
11985                .state
11986                .lock()
11987                .map_err(|_| Error::WorkflowStatePoisoned)?
11988                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
11989            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
11990                group_id,
11991                member_path: failed.member_path.clone(),
11992                group_path: failed.group_path.clone(),
11993                completed,
11994                cause: Box::new(cause),
11995            })));
11996        }
11997        if pending
11998            || self
11999                .ctx
12000                .state
12001                .lock()
12002                .map_err(|_| Error::WorkflowStatePoisoned)?
12003                .cancellation_delivery_intent
12004                .is_some()
12005        {
12006            return Poll::Pending;
12007        }
12008
12009        let mut flat_results = self
12010            .leaves
12011            .iter_mut()
12012            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12013            .collect::<Vec<_>>()
12014            .into_iter();
12015        let results = parallel_results_for_shape(
12016            self.shape.as_ref().expect("initialized parallel shape"),
12017            &mut flat_results,
12018        );
12019        let sequences = self
12020            .leaves
12021            .iter()
12022            .map(|leaf| leaf.sequence)
12023            .collect::<Vec<_>>();
12024        self.ctx
12025            .state
12026            .lock()
12027            .map_err(|_| Error::WorkflowStatePoisoned)?
12028            .advance_cancellation_sequences(&sequences, None);
12029        Poll::Ready(Ok(match results {
12030            ParallelAvroResult::Group(results) => results,
12031            ParallelAvroResult::Activity(_)
12032            | ParallelAvroResult::ChildWorkflow(_)
12033            | ParallelAvroResult::Timer
12034            | ParallelAvroResult::Signal(_)
12035            | ParallelAvroResult::Condition(_) => {
12036                unreachable!("root parallel shape is a group")
12037            }
12038        }))
12039    }
12040}
12041
12042fn parallel_results_for_shape(
12043    shape: &ParallelShape,
12044    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12045) -> ParallelAvroResult {
12046    match shape {
12047        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12048        ParallelShape::Group(children) => ParallelAvroResult::Group(
12049            children
12050                .iter()
12051                .map(|child| parallel_results_for_shape(child, flat_results))
12052                .collect(),
12053        ),
12054    }
12055}
12056
12057impl Future for ParallelCall {
12058    type Output = Result<Vec<ParallelResult>>;
12059
12060    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12061        self.poll_avro_value(cx)
12062            .map_ok(|results| {
12063                results
12064                    .into_iter()
12065                    .map(ParallelAvroResult::into_json_result)
12066                    .collect::<Result<Vec<_>>>()
12067            })
12068            .map_ok(|result| result)
12069            .flatten_result()
12070    }
12071}
12072
12073#[derive(Clone, Debug)]
12074struct SelectionMemberPlan {
12075    key: SelectionKey,
12076    index: usize,
12077    base_sequence: u64,
12078    size: usize,
12079    kind: String,
12080    shape: ParallelShape,
12081    leaf_start: usize,
12082}
12083
12084fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12085    match operation {
12086        ParallelOperation::Activity { .. } => "activity",
12087        ParallelOperation::ChildWorkflow { .. } => "child",
12088        ParallelOperation::Timer(_) => "timer",
12089        ParallelOperation::Signal(_) => "signal",
12090        ParallelOperation::Condition { .. } => "condition",
12091        ParallelOperation::Group(_) => "group",
12092    }
12093}
12094
12095fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12096    match operation {
12097        ParallelOperation::Group(children) => parallel_shape(children),
12098        _ => ParallelShape::Leaf,
12099    }
12100}
12101
12102fn selection_descriptors(
12103    operations: Vec<(SelectionKey, ParallelOperation)>,
12104    base_sequence: u64,
12105) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12106    if operations.is_empty() {
12107        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12108            reason: "selection_empty",
12109            member_path: Vec::new(),
12110            message: "durable selection requires at least one operation".to_string(),
12111        }));
12112    }
12113    let operation_refs = operations
12114        .iter()
12115        .map(|(_, operation)| operation)
12116        .collect::<Vec<_>>();
12117    let total_size = operation_refs
12118        .iter()
12119        .map(|operation| match operation {
12120            ParallelOperation::Group(children) => parallel_leaf_count(children),
12121            _ => 1,
12122        })
12123        .sum::<usize>();
12124    if total_size > MAX_PARALLEL_OPERATIONS {
12125        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12126            reason: "fan_out_limit_exceeded",
12127            member_path: Vec::new(),
12128            message: format!(
12129                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12130            ),
12131        }));
12132    }
12133    let group_kind = {
12134        let mut kind = None;
12135        for operation in &operation_refs {
12136            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12137            match kind {
12138                None => kind = Some(operation_kind),
12139                Some(current) if current == operation_kind => {}
12140                Some(_) => {
12141                    kind = Some("mixed");
12142                    break;
12143                }
12144            }
12145        }
12146        kind.unwrap_or("mixed")
12147    };
12148
12149    let mut descriptors = Vec::with_capacity(total_size);
12150    let mut members = Vec::with_capacity(operations.len());
12151    let mut cursor = 0usize;
12152    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12153    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12154        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12155            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12156                reason: "selection_key_invalid",
12157                member_path: vec![member_index],
12158                message: "selection member keys must be non-empty strings or non-negative integers"
12159                    .to_string(),
12160            }));
12161        }
12162        if seen_keys.contains(&key) {
12163            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12164                reason: "selection_key_duplicate",
12165                member_path: vec![member_index],
12166                message: format!("selection member key {key:?} is duplicated"),
12167            }));
12168        }
12169        seen_keys.push(key.clone());
12170        let member_size = match &operation {
12171            ParallelOperation::Group(children) => parallel_leaf_count(children),
12172            _ => 1,
12173        };
12174        if member_size == 0 {
12175            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12176                reason: "selection_member_empty",
12177                member_path: vec![member_index],
12178                message: "a selection member must contain at least one durable leaf".to_string(),
12179            }));
12180        }
12181        let member_base = base_sequence
12182            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12183            .ok_or(Error::TimerDurationOverflow)?;
12184        let member_kind = selection_operation_kind(&operation).to_string();
12185        let member_shape = selection_operation_shape(&operation);
12186        let leaf_start = descriptors.len();
12187        match operation {
12188            ParallelOperation::Group(children) => {
12189                validate_parallel_operations(&children, &mut vec![member_index], false)?;
12190                for mut descriptor in parallel_descriptors(children, member_base)? {
12191                    let flat_index = cursor + descriptor.offset;
12192                    descriptor.group_path.insert(
12193                        0,
12194                        selection_group_entry(
12195                            base_sequence,
12196                            total_size,
12197                            flat_index,
12198                            group_kind,
12199                            &SelectionMemberMetadata {
12200                                key: key.clone(),
12201                                index: member_index,
12202                                base_sequence: member_base,
12203                                size: member_size,
12204                                kind: member_kind.clone(),
12205                            },
12206                        ),
12207                    );
12208                    descriptor.member_path.insert(0, member_index);
12209                    descriptor.offset = flat_index;
12210                    descriptors.push(descriptor);
12211                }
12212            }
12213            operation => {
12214                validate_parallel_operations(
12215                    std::slice::from_ref(&operation),
12216                    &mut Vec::new(),
12217                    true,
12218                )?;
12219                descriptors.push(ParallelDescriptor {
12220                    operation,
12221                    offset: cursor,
12222                    member_path: vec![member_index],
12223                    group_path: vec![selection_group_entry(
12224                        base_sequence,
12225                        total_size,
12226                        cursor,
12227                        group_kind,
12228                        &SelectionMemberMetadata {
12229                            key: key.clone(),
12230                            index: member_index,
12231                            base_sequence: member_base,
12232                            size: member_size,
12233                            kind: member_kind.clone(),
12234                        },
12235                    )],
12236                });
12237            }
12238        }
12239        members.push(SelectionMemberPlan {
12240            key,
12241            index: member_index,
12242            base_sequence: member_base,
12243            size: member_size,
12244            kind: member_kind,
12245            shape: member_shape,
12246            leaf_start,
12247        });
12248        cursor += member_size;
12249    }
12250    Ok((descriptors, members))
12251}
12252
12253struct SelectionLeaf {
12254    call: ParallelLeafCall,
12255    outcome: Option<Result<ParallelAvroResult>>,
12256}
12257
12258/// Stable reference to one member of a durable selection group.
12259#[derive(Clone)]
12260pub struct DurableOperationHandle {
12261    ctx: WorkflowContext,
12262    pub key: SelectionKey,
12263    pub index: usize,
12264    pub kind: String,
12265    pub identity: String,
12266    pub base_sequence: u64,
12267    pub size: usize,
12268    pub selection_group_id: String,
12269    shape: ParallelShape,
12270}
12271
12272impl std::fmt::Debug for DurableOperationHandle {
12273    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12274        formatter
12275            .debug_struct("DurableOperationHandle")
12276            .field("key", &self.key)
12277            .field("index", &self.index)
12278            .field("kind", &self.kind)
12279            .field("identity", &self.identity)
12280            .field("base_sequence", &self.base_sequence)
12281            .field("size", &self.size)
12282            .field("selection_group_id", &self.selection_group_id)
12283            .finish()
12284    }
12285}
12286
12287impl DurableOperationHandle {
12288    /// Await this member after another member has already won the selection.
12289    pub fn await_result(&self) -> DurableOperationAwaitCall {
12290        DurableOperationAwaitCall {
12291            handle: self.clone(),
12292        }
12293    }
12294
12295    /// Request cancellation without affecting siblings. The future resolves
12296    /// to unit; only `SelectionOperationCancelled` history proves cancellation
12297    /// beat a concurrently committed terminal result.
12298    pub fn cancel(&self) -> CancelDurableOperationCall {
12299        CancelDurableOperationCall {
12300            handle: self.clone(),
12301            emitted: false,
12302        }
12303    }
12304}
12305
12306/// The one winner committed for a durable selection group.
12307#[derive(Debug)]
12308pub struct SelectionResult {
12309    pub key: SelectionKey,
12310    pub index: usize,
12311    pub kind: String,
12312    pub identity: String,
12313    pub value: Option<ParallelResult>,
12314    pub failure: Option<Error>,
12315    pub winner: DurableOperationHandle,
12316    pub handles: Vec<DurableOperationHandle>,
12317}
12318
12319impl SelectionResult {
12320    pub fn succeeded(&self) -> bool {
12321        self.failure.is_none()
12322    }
12323
12324    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
12325        self.handles.iter().find(|handle| &handle.key == key)
12326    }
12327
12328    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
12329        self.handles
12330            .iter()
12331            .filter(|handle| handle.index != self.index)
12332            .collect()
12333    }
12334
12335    pub fn into_result(self) -> Result<ParallelResult> {
12336        match (self.value, self.failure) {
12337            (Some(value), None) => Ok(value),
12338            (_, Some(error)) => Err(error),
12339            _ => Err(Error::WorkerLoop(
12340                "selection result contained neither a value nor a failure".to_string(),
12341            )),
12342        }
12343    }
12344}
12345
12346/// Future returned by [`WorkflowContext::select`].
12347pub struct SelectCall {
12348    ctx: WorkflowContext,
12349    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
12350    members: Vec<SelectionMemberPlan>,
12351    leaves: Vec<SelectionLeaf>,
12352    group_id: Option<String>,
12353}
12354
12355impl SelectCall {
12356    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
12357        Self {
12358            ctx,
12359            operations: Some(operations),
12360            members: Vec::new(),
12361            leaves: Vec::new(),
12362            group_id: None,
12363        }
12364    }
12365
12366    fn initialize(&mut self) -> Result<()> {
12367        let operations = self.operations.take().unwrap_or_default();
12368        let base_sequence = {
12369            let state = self
12370                .ctx
12371                .state
12372                .lock()
12373                .map_err(|_| Error::WorkflowStatePoisoned)?;
12374            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
12375                state.recorded_commands.get(state.command_cursor)
12376            {
12377                *sequence
12378            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
12379            {
12380                marker.selection_group_base_sequence
12381            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12382                recorded.sequence()
12383            } else {
12384                let last = state
12385                    .recorded_commands
12386                    .last()
12387                    .map(RecordedCommand::sequence)
12388                    .unwrap_or(0);
12389                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12390                    .and_then(|sequence| sequence.checked_add(1))
12391                    .ok_or(Error::TimerDurationOverflow)?
12392            }
12393        };
12394        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
12395        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
12396        {
12397            let mut state = self
12398                .ctx
12399                .state
12400                .lock()
12401                .map_err(|_| Error::WorkflowStatePoisoned)?;
12402            state.expand_cancellation_group(&descriptors)?;
12403            state.prepare_group_cancellation(&descriptors)?;
12404        }
12405        self.leaves = descriptors
12406            .into_iter()
12407            .map(|descriptor| SelectionLeaf {
12408                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
12409                outcome: None,
12410            })
12411            .collect();
12412        self.members = members;
12413        self.group_id = Some(group_id);
12414        Ok(())
12415    }
12416}
12417
12418impl Future for SelectCall {
12419    type Output = Result<SelectionResult>;
12420
12421    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12422        if self.operations.is_some() {
12423            if let Err(error) = self.initialize() {
12424                return Poll::Ready(Err(error));
12425            }
12426        }
12427
12428        for leaf in &mut self.leaves {
12429            if leaf.outcome.is_some() {
12430                continue;
12431            }
12432            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
12433                if outcome
12434                    .as_ref()
12435                    .err()
12436                    .is_some_and(workflow_task_integrity_error)
12437                {
12438                    return Poll::Ready(outcome.map(|_| unreachable!()));
12439                }
12440                leaf.outcome = Some(outcome);
12441            }
12442        }
12443
12444        if self
12445            .ctx
12446            .state
12447            .lock()
12448            .map_err(|_| Error::WorkflowStatePoisoned)?
12449            .cancellation_delivery_intent
12450            .is_some()
12451        {
12452            return Poll::Pending;
12453        }
12454
12455        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
12456            matches!(
12457                leaf.outcome,
12458                Some(Err(Error::CooperativeCancellationRequested(_)))
12459            )
12460        }) {
12461            return Poll::Ready(
12462                leaf.outcome
12463                    .take()
12464                    .expect("matched cancellation")
12465                    .map(|_| unreachable!()),
12466            );
12467        }
12468
12469        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
12470        let selection_member_range = self
12471            .members
12472            .first()
12473            .map(|member| member.base_sequence)
12474            .zip(self.leaves.len().try_into().ok())
12475            .map(|(base_sequence, size): (u64, u64)| {
12476                base_sequence..base_sequence.saturating_add(size)
12477            });
12478        let marker = {
12479            let mut state = match self.ctx.state.lock() {
12480                Ok(state) => state,
12481                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12482            };
12483            let marker = state
12484                .selection_markers
12485                .get(state.selection_marker_cursor)
12486                .cloned();
12487            if marker.is_none()
12488                && all_members_terminal
12489                && selection_member_range.as_ref().is_some_and(|member_range| {
12490                    state
12491                        .recorded_commands
12492                        .iter()
12493                        .any(|command| member_range.contains(&command.sequence()))
12494                })
12495            {
12496                // Terminal member history can be committed before the server's
12497                // SelectionResolved marker becomes visible to this task. That
12498                // marker is the durable barrier the selection is still waiting
12499                // on, so an otherwise commandless replay remains legitimately
12500                // pending instead of failing as an untracked yield.
12501                state.matched_recorded_pending = true;
12502            }
12503            marker
12504        };
12505        let Some(marker) = marker else {
12506            return Poll::Pending;
12507        };
12508        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
12509            || marker.selection_group_size != self.leaves.len()
12510            || self.members.first().map(|member| member.base_sequence)
12511                != Some(marker.selection_group_base_sequence)
12512        {
12513            return Poll::Ready(Err(invalid_recorded_history(
12514                "selection_group_shape_mismatch",
12515                marker.selection_group_base_sequence,
12516                self.group_id
12517                    .as_deref()
12518                    .unwrap_or("initialized selection group"),
12519                &marker.selection_group_id,
12520                "recorded selection group differs from current workflow code",
12521            )));
12522        }
12523        let Some(member_position) = self.members.iter().position(|member| {
12524            member.key == marker.member_key
12525                && member.index == marker.member_index
12526                && member.base_sequence == marker.member_base_sequence
12527                && member.size == marker.member_size
12528                && member.kind == marker.operation_kind
12529        }) else {
12530            return Poll::Ready(Err(invalid_recorded_history(
12531                "selection_member_shape_mismatch",
12532                marker.member_base_sequence,
12533                "winner member matching current workflow code",
12534                &format!("{:?}", marker.member_key),
12535                "recorded selection winner differs from the authored member identity",
12536            )));
12537        };
12538        let member = self.members[member_position].clone();
12539        let (handles, resolution_sequence) = {
12540            let mut state = match self.ctx.state.lock() {
12541                Ok(state) => state,
12542                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12543            };
12544            let identities = self
12545                .members
12546                .iter()
12547                .map(|candidate| {
12548                    selection_operation_identity(
12549                        &state,
12550                        &candidate.kind,
12551                        candidate.base_sequence,
12552                        candidate.size,
12553                    )
12554                })
12555                .collect::<Vec<_>>();
12556            if let Some((position, missing)) = identities
12557                .iter()
12558                .enumerate()
12559                .find(|(_, identity)| identity.is_empty())
12560                .map(|(position, identity)| (position, identity.clone()))
12561            {
12562                let candidate = &self.members[position];
12563                return Poll::Ready(Err(invalid_recorded_history(
12564                    "selection_operation_identity_missing",
12565                    candidate.base_sequence,
12566                    &format!(
12567                        "durable {} resource identity from scheduled/open history",
12568                        candidate.kind
12569                    ),
12570                    &missing,
12571                    "selection member history is missing its canonical durable identity",
12572                )));
12573            }
12574            let expected_winner_identity = &identities[member_position];
12575            let resolution_sequence = match validated_selection_resolution_sequence(
12576                &state,
12577                &marker,
12578                &member,
12579                expected_winner_identity,
12580            ) {
12581                Ok(sequence) => sequence,
12582                Err(error) => return Poll::Ready(Err(error)),
12583            };
12584            let handles = self
12585                .members
12586                .iter()
12587                .zip(identities)
12588                .map(|(member, identity)| DurableOperationHandle {
12589                    ctx: self.ctx.clone(),
12590                    key: member.key.clone(),
12591                    index: member.index,
12592                    kind: member.kind.clone(),
12593                    identity,
12594                    base_sequence: member.base_sequence,
12595                    size: member.size,
12596                    selection_group_id: marker.selection_group_id.clone(),
12597                    shape: member.shape.clone(),
12598                })
12599                .collect::<Vec<_>>();
12600            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
12601                return Poll::Ready(Err(error));
12602            }
12603            state.selection_marker_cursor += 1;
12604            (handles, resolution_sequence)
12605        };
12606
12607        let mut winner_failure = None;
12608        let mut flat_results = Vec::with_capacity(member.size);
12609        if marker.outcome == "failed" {
12610            let resolution_offset = match resolution_sequence
12611                .checked_sub(member.base_sequence)
12612                .and_then(|offset| usize::try_from(offset).ok())
12613            {
12614                Some(offset) if offset < member.size => offset,
12615                _ => {
12616                    return Poll::Ready(Err(invalid_recorded_history(
12617                        "selection_resolution_event_mismatch",
12618                        member.base_sequence,
12619                        "failure event within selected member bounds",
12620                        &resolution_sequence.to_string(),
12621                        "selection failure event is outside the authored member",
12622                    )))
12623                }
12624            };
12625            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
12626            match leaf.outcome.take() {
12627                Some(Err(error)) => winner_failure = Some(error),
12628                _ => {
12629                    return Poll::Ready(Err(invalid_recorded_history(
12630                        "selection_winner_outcome_mismatch",
12631                        member.base_sequence,
12632                        "exact failed terminal history referenced by SelectionResolved",
12633                        "missing or successful resolution event",
12634                        "selection winner marker disagrees with terminal operation history",
12635                    )))
12636                }
12637            }
12638        } else {
12639            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
12640                match leaf.outcome.take() {
12641                    Some(Ok(result)) => flat_results.push(result),
12642                    Some(Err(_)) => {
12643                        return Poll::Ready(Err(invalid_recorded_history(
12644                            "selection_winner_outcome_mismatch",
12645                            member.base_sequence,
12646                            "fully completed nested selection member",
12647                            "failed durable leaf",
12648                            "completed selection winner contains a failed leaf",
12649                        )))
12650                    }
12651                    None => {
12652                        return Poll::Ready(Err(invalid_recorded_history(
12653                            "selection_winner_unresolved",
12654                            member.base_sequence,
12655                            "terminal history for every completed winner leaf",
12656                            "pending member history",
12657                            "completed SelectionResolved member has an unfinished durable barrier",
12658                        )))
12659                    }
12660                }
12661            }
12662        }
12663        let value = if winner_failure.is_none() {
12664            let mut flat_results = flat_results.into_iter();
12665            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
12666            match value.into_json_result() {
12667                Ok(value) => Some(value),
12668                Err(error) => return Poll::Ready(Err(error)),
12669            }
12670        } else {
12671            None
12672        };
12673        let winner = handles[member_position].clone();
12674        self.ctx
12675            .state
12676            .lock()
12677            .map_err(|_| Error::WorkflowStatePoisoned)?
12678            .advance_cancellation_selection(&marker.selection_group_id);
12679        Poll::Ready(Ok(SelectionResult {
12680            key: winner.key.clone(),
12681            index: winner.index,
12682            kind: winner.kind.clone(),
12683            identity: winner.identity.clone(),
12684            value,
12685            failure: winner_failure,
12686            winner,
12687            handles,
12688        }))
12689    }
12690}
12691
12692fn selection_operation_identity(
12693    state: &WorkflowState,
12694    kind: &str,
12695    base_sequence: u64,
12696    size: usize,
12697) -> String {
12698    if kind == "group" {
12699        return format!("group:{base_sequence}:{size}");
12700    }
12701    let fields: &[&str] = match kind {
12702        "activity" => &["activity_execution_id"],
12703        "child" => &["child_workflow_run_id"],
12704        "timer" => &["timer_id"],
12705        "signal" => &["signal_wait_id"],
12706        "condition" => &["condition_wait_id"],
12707        _ => &[],
12708    };
12709    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
12710        for event in state
12711            .history_events
12712            .iter()
12713            .filter(|event| durable_event_sequence(event) == Some(sequence))
12714        {
12715            for field in fields {
12716                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
12717                    if !identity.is_empty() {
12718                        return identity.to_string();
12719                    }
12720                }
12721            }
12722        }
12723    }
12724    String::new()
12725}
12726
12727fn validated_selection_resolution_sequence(
12728    state: &WorkflowState,
12729    marker: &SelectionMarker,
12730    member: &SelectionMemberPlan,
12731    expected_identity: &str,
12732) -> Result<u64> {
12733    if expected_identity.is_empty() {
12734        return Err(invalid_recorded_history(
12735            "selection_operation_identity_missing",
12736            member.base_sequence,
12737            &format!(
12738                "durable {} resource identity from scheduled/open history",
12739                member.kind
12740            ),
12741            "missing operation identity",
12742            "selection member history is missing its canonical durable identity",
12743        ));
12744    }
12745    if marker.operation_identity != expected_identity {
12746        return Err(invalid_recorded_history(
12747            "selection_operation_identity_mismatch",
12748            member.base_sequence,
12749            expected_identity,
12750            &marker.operation_identity,
12751            "selection winner identity does not match durable scheduled/open history",
12752        ));
12753    }
12754
12755    let failure_types = [
12756        "ActivityFailed",
12757        "ActivityCancelled",
12758        "ActivityTimedOut",
12759        "ChildRunFailed",
12760        "ChildRunCancelled",
12761        "ChildRunTerminated",
12762    ];
12763    let success_types = [
12764        "ActivityCompleted",
12765        "ChildRunCompleted",
12766        "TimerFired",
12767        "SignalApplied",
12768        "ConditionWaitSatisfied",
12769        "ConditionWaitTimedOut",
12770    ];
12771    let terminal_types: &[&str] = if marker.outcome == "failed" {
12772        &failure_types
12773    } else {
12774        &success_types
12775    };
12776    let mut candidates = Vec::new();
12777    let member_commands = (member.base_sequence
12778        ..member.base_sequence.saturating_add(member.size as u64))
12779        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
12780        .map(|command| (command.sequence(), command))
12781        .collect::<BTreeMap<_, _>>();
12782    let mut resolved_conditions = BTreeSet::new();
12783    for event in state.history_events.iter() {
12784        let Some(sequence) = durable_event_sequence(event) else {
12785            continue;
12786        };
12787        let Some(command) = member_commands.get(&sequence) else {
12788            continue;
12789        };
12790        if !terminal_types.contains(&event.event_type.as_str()) {
12791            continue;
12792        }
12793        if matches!(command, RecordedCommand::ConditionWait { .. }) {
12794            if !matches!(
12795                event.event_type.as_str(),
12796                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
12797            ) && !(event.event_type == "TimerFired"
12798                && event.payload.get("timer_kind").and_then(Value::as_str)
12799                    == Some("condition_timeout"))
12800            {
12801                continue;
12802            }
12803            if !resolved_conditions.insert(sequence) {
12804                continue;
12805            }
12806        }
12807        let event_id = event
12808            .raw
12809            .get("id")
12810            .or_else(|| event.raw.get("event_id"))
12811            .and_then(Value::as_str)
12812            .filter(|value| !value.is_empty())
12813            .ok_or_else(|| {
12814                invalid_recorded_history(
12815                    "selection_resolution_event_id_missing",
12816                    member.base_sequence,
12817                    "terminal selection history with a durable event id",
12818                    &event.payload.to_string(),
12819                    "selection terminal history cannot be bound to its winner marker",
12820                )
12821            })?;
12822        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
12823    }
12824    let resolution = if marker.outcome == "failed" {
12825        candidates.first()
12826    } else {
12827        candidates.last()
12828    };
12829    let Some((event_id, event_type, sequence)) = resolution else {
12830        return Err(invalid_recorded_history(
12831            "selection_resolution_event_missing",
12832            member.base_sequence,
12833            "terminal history for the selected member",
12834            &format!("{:?}", marker.member_key),
12835            "selection winner marker has no matching durable terminal event",
12836        ));
12837    };
12838    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
12839        return Err(invalid_recorded_history(
12840            "selection_resolution_event_mismatch",
12841            member.base_sequence,
12842            &format!("{event_type}:{event_id}"),
12843            &format!(
12844                "{}:{}",
12845                marker.resolution_event_type, marker.resolution_event_id
12846            ),
12847            "selection winner marker does not reference the event that made its member terminal",
12848        ));
12849    }
12850    Ok(*sequence)
12851}
12852
12853fn selection_member_recorded_command(
12854    state: &WorkflowState,
12855    authored_sequence: u64,
12856) -> Option<&RecordedCommand> {
12857    let original = state
12858        .recorded_commands
12859        .iter()
12860        .find(|command| command.sequence() == authored_sequence)?;
12861    let RecordedCommand::ConditionWait {
12862        occurrence_id,
12863        parallel_group_path: Some(_),
12864        ..
12865    } = original
12866    else {
12867        return Some(original);
12868    };
12869    // Decoding proves each physical reopen has the same authored identity and
12870    // group path after a satisfied predecessor. Only its latest wait can make
12871    // this logical member terminal.
12872    state
12873        .recorded_commands
12874        .iter()
12875        .filter(|command| {
12876            matches!(command, RecordedCommand::ConditionWait {
12877                occurrence_id: candidate, ..
12878            } if candidate == occurrence_id)
12879        })
12880        .max_by_key(|command| command.sequence())
12881}
12882
12883fn recorded_selection_member_outcome(
12884    state: &WorkflowState,
12885    handle: &DurableOperationHandle,
12886) -> Result<Option<ParallelResult>> {
12887    for event in state.history_events.iter() {
12888        let Some(sequence) = durable_event_sequence(event) else {
12889            continue;
12890        };
12891        if sequence < handle.base_sequence
12892            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
12893            || !matches!(
12894                event.event_type.as_str(),
12895                "ActivityFailed"
12896                    | "ActivityCancelled"
12897                    | "ActivityTimedOut"
12898                    | "ChildRunFailed"
12899                    | "ChildRunCancelled"
12900                    | "ChildRunTerminated"
12901            )
12902        {
12903            continue;
12904        }
12905        let Some(command) = state
12906            .recorded_commands
12907            .iter()
12908            .find(|command| command.sequence() == sequence)
12909        else {
12910            continue;
12911        };
12912        match command {
12913            RecordedCommand::Activity {
12914                outcome: Some(Err(failure)),
12915                ..
12916            } => return Err(Error::ActivityFailed(failure.clone())),
12917            RecordedCommand::ChildWorkflow {
12918                outcome: Some(Err(failure)),
12919                ..
12920            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
12921            _ => {}
12922        }
12923    }
12924
12925    let mut results = Vec::with_capacity(handle.size);
12926    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
12927        let Some(command) = selection_member_recorded_command(state, sequence) else {
12928            return Ok(None);
12929        };
12930        let result = match command {
12931            RecordedCommand::Activity { outcome, .. } => match outcome {
12932                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
12933                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
12934                None => return Ok(None),
12935            },
12936            RecordedCommand::Timer { fired, .. } => {
12937                if !fired {
12938                    return Ok(None);
12939                }
12940                ParallelAvroResult::Timer
12941            }
12942            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
12943                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
12944                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
12945                None => return Ok(None),
12946            },
12947            RecordedCommand::SignalWait { value, .. } => match value {
12948                Some(value) => ParallelAvroResult::Signal(value.clone()),
12949                None => return Ok(None),
12950            },
12951            RecordedCommand::ConditionWait { result, .. } => match result {
12952                Some(result) => ParallelAvroResult::Condition(*result),
12953                None => return Ok(None),
12954            },
12955            other => {
12956                return Err(command_mismatch(
12957                    other,
12958                    format!("selected {} member", handle.kind),
12959                ))
12960            }
12961        };
12962        results.push(result);
12963    }
12964    let mut results = results.into_iter();
12965    parallel_results_for_shape(&handle.shape, &mut results)
12966        .into_json_result()
12967        .map(Some)
12968}
12969
12970fn recorded_selection_member_is_terminal(
12971    state: &WorkflowState,
12972    handle: &DurableOperationHandle,
12973) -> bool {
12974    let mut completed = 0usize;
12975    let mut all_completed = true;
12976    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
12977        let Some(command) = selection_member_recorded_command(state, sequence) else {
12978            all_completed = false;
12979            continue;
12980        };
12981        let terminal = match command {
12982            RecordedCommand::Activity {
12983                outcome: Some(Err(_)),
12984                ..
12985            }
12986            | RecordedCommand::ChildWorkflow {
12987                outcome: Some(Err(_)),
12988                ..
12989            } => return true,
12990            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
12991            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
12992            RecordedCommand::Timer { fired, .. } => *fired,
12993            RecordedCommand::SignalWait { value, .. } => value.is_some(),
12994            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
12995            RecordedCommand::SearchAttributes { .. }
12996            | RecordedCommand::CancellationScope { .. }
12997            | RecordedCommand::SideEffect { .. }
12998            | RecordedCommand::VersionMarker { .. }
12999            | RecordedCommand::Memo { .. }
13000            | RecordedCommand::CancellationBoundary { .. }
13001            | RecordedCommand::CancellationGroup { .. } => false,
13002        };
13003        if !terminal {
13004            all_completed = false;
13005            continue;
13006        }
13007        completed += 1;
13008    }
13009    all_completed && completed == handle.size
13010}
13011
13012fn selection_cancellation_for_handle(
13013    state: &WorkflowState,
13014    handle: &DurableOperationHandle,
13015) -> Result<bool> {
13016    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13017        recorded.selection_group_id == handle.selection_group_id
13018            && recorded.member_base_sequence == handle.base_sequence
13019    }) else {
13020        return Ok(false);
13021    };
13022    validate_selection_cancellation_marker(marker, handle)?;
13023    Ok(true)
13024}
13025
13026fn validate_selection_cancellations_for_handles(
13027    state: &WorkflowState,
13028    handles: &[DurableOperationHandle],
13029) -> Result<()> {
13030    let Some(group_id) = handles
13031        .first()
13032        .map(|handle| handle.selection_group_id.as_str())
13033    else {
13034        return Ok(());
13035    };
13036    for marker in state
13037        .cancelled_selection_members
13038        .iter()
13039        .filter(|marker| marker.selection_group_id == group_id)
13040    {
13041        let Some(handle) = handles
13042            .iter()
13043            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13044        else {
13045            return Err(invalid_recorded_history(
13046                "selection_cancellation_member_mismatch",
13047                marker.member_base_sequence,
13048                "SelectionOperationCancelled matching an authored selection handle",
13049                &format!("{marker:?}"),
13050                "selection cancellation member base does not name an authored member",
13051            ));
13052        };
13053        validate_selection_cancellation_marker(marker, handle)?;
13054    }
13055    Ok(())
13056}
13057
13058fn validate_selection_cancellation_marker(
13059    marker: &SelectionCancellation,
13060    handle: &DurableOperationHandle,
13061) -> Result<()> {
13062    if marker.selection_group_id != handle.selection_group_id
13063        || marker.member_key != handle.key
13064        || marker.member_index != handle.index
13065        || marker.member_base_sequence != handle.base_sequence
13066        || marker.member_size != handle.size
13067        || marker.operation_kind != handle.kind
13068        || marker.operation_identity != handle.identity
13069    {
13070        return Err(invalid_recorded_history(
13071            "selection_cancellation_member_mismatch",
13072            handle.base_sequence,
13073            "SelectionOperationCancelled matching the authored selection handle",
13074            &format!("{marker:?}"),
13075            "selection cancellation history targets different authored member metadata",
13076        ));
13077    }
13078    Ok(())
13079}
13080
13081/// Future returned by [`DurableOperationHandle::await_result`].
13082pub struct DurableOperationAwaitCall {
13083    handle: DurableOperationHandle,
13084}
13085
13086impl Future for DurableOperationAwaitCall {
13087    type Output = Result<ParallelResult>;
13088
13089    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13090        let mut state = match self.handle.ctx.state.lock() {
13091            Ok(state) => state,
13092            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13093        };
13094        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13095            return Poll::Ready(Err(error));
13096        }
13097        match state.prepare_selection_handle_cancellation(&self.handle) {
13098            Ok(true) => return Poll::Pending,
13099            Ok(false) => {}
13100            Err(error) => return Poll::Ready(Err(error)),
13101        }
13102        match selection_cancellation_for_handle(&state, &self.handle) {
13103            Err(error) => return Poll::Ready(Err(error)),
13104            Ok(false) => {}
13105            Ok(true) => {
13106                state.advance_cancellation_receipt(
13107                    &self.handle.selection_group_id,
13108                    self.handle.base_sequence,
13109                );
13110                return Poll::Ready(Err(Error::DurableOperationCancelled(
13111                    DurableOperationCancelled {
13112                        selection_group_id: self.handle.selection_group_id.clone(),
13113                        member_key: self.handle.key.clone(),
13114                        member_index: self.handle.index,
13115                        operation_kind: self.handle.kind.clone(),
13116                        operation_identity: self.handle.identity.clone(),
13117                    },
13118                )));
13119            }
13120        }
13121        match recorded_selection_member_outcome(&state, &self.handle) {
13122            Ok(Some(result)) => {
13123                state.advance_cancellation_handle(&self.handle, false);
13124                Poll::Ready(Ok(result))
13125            }
13126            Ok(None) => Poll::Pending,
13127            Err(error) => {
13128                if !workflow_task_integrity_error(&error) {
13129                    state.advance_cancellation_handle(&self.handle, true);
13130                }
13131                Poll::Ready(Err(error))
13132            }
13133        }
13134    }
13135}
13136
13137fn validate_selection_delivery_handle(
13138    state: &WorkflowState,
13139    handle: &DurableOperationHandle,
13140) -> Result<()> {
13141    let path = state
13142        .recorded_commands
13143        .iter()
13144        .find(|command| command.sequence() == handle.base_sequence)
13145        .and_then(|command| match command {
13146            RecordedCommand::Activity {
13147                parallel_group_path,
13148                ..
13149            }
13150            | RecordedCommand::ChildWorkflow {
13151                parallel_group_path,
13152                ..
13153            }
13154            | RecordedCommand::Timer {
13155                parallel_group_path,
13156                ..
13157            }
13158            | RecordedCommand::SignalWait {
13159                parallel_group_path,
13160                ..
13161            }
13162            | RecordedCommand::ConditionWait {
13163                parallel_group_path,
13164                ..
13165            } => parallel_group_path.as_ref(),
13166            _ => None,
13167        })
13168        .and_then(|path| path.first());
13169    let matches = path.is_some_and(|entry| {
13170        entry.parallel_group_mode.as_deref() == Some("select")
13171            && entry.parallel_group_id == handle.selection_group_id
13172            && entry.selection_member_key.as_ref() == Some(&handle.key)
13173            && entry.selection_member_index == Some(handle.index)
13174            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13175            && entry.selection_member_size == Some(handle.size)
13176            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13177    });
13178    if !matches
13179        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13180            != handle.identity
13181    {
13182        return Err(invalid_recorded_history(
13183            "cooperative_cancellation_call_mismatch",
13184            handle.base_sequence,
13185            "selection handle matching its authored durable identity",
13186            &format!("{handle:?}"),
13187            "selection handle identity or member metadata changed before cancellation replay",
13188        ));
13189    }
13190    Ok(())
13191}
13192
13193/// Future returned by [`DurableOperationHandle::cancel`].
13194pub struct CancelDurableOperationCall {
13195    handle: DurableOperationHandle,
13196    emitted: bool,
13197}
13198
13199impl Future for CancelDurableOperationCall {
13200    type Output = Result<()>;
13201
13202    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13203        let ctx = self.handle.ctx.clone();
13204        let mut state = match ctx.state.lock() {
13205            Ok(state) => state,
13206            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13207        };
13208        match selection_cancellation_for_handle(&state, &self.handle) {
13209            Err(error) => return Poll::Ready(Err(error)),
13210            Ok(true) => {
13211                state.advance_cancellation_receipt(
13212                    &self.handle.selection_group_id,
13213                    self.handle.base_sequence,
13214                );
13215                return Poll::Ready(Ok(()));
13216            }
13217            Ok(false) => {}
13218        }
13219        if recorded_selection_member_is_terminal(&state, &self.handle) {
13220            return Poll::Ready(Ok(()));
13221        }
13222        if !self.emitted {
13223            state.commands.push(json!({
13224                "type": "cancel_selection_operation",
13225                "selection_group_id": self.handle.selection_group_id,
13226                "member_key": self.handle.key,
13227                "member_index": self.handle.index,
13228                "member_base_sequence": self.handle.base_sequence,
13229                "member_size": self.handle.size,
13230                "operation_kind": self.handle.kind,
13231                "operation_identity": self.handle.identity,
13232            }));
13233            self.emitted = true;
13234        }
13235        // The cancellation command is only a request. Do not expose workflow
13236        // state after cancel until committed SelectionOperationCancelled
13237        // history proves that the request won the race with member completion.
13238        Poll::Pending
13239    }
13240}
13241
13242trait PollNestedResultExt<T> {
13243    fn flatten_result(self) -> Poll<Result<T>>;
13244}
13245
13246impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
13247    fn flatten_result(self) -> Poll<Result<T>> {
13248        match self {
13249            Poll::Ready(Ok(result)) => Poll::Ready(result),
13250            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13251            Poll::Pending => Poll::Pending,
13252        }
13253    }
13254}
13255
13256struct SagaCompensation {
13257    activity_type: String,
13258    options: ActivityOptions,
13259    arguments: AvroValue,
13260    registration_order: usize,
13261}
13262
13263/// Workflow-local deterministic saga compensation helper.
13264///
13265/// Register each compensation only after its forward step succeeds. Passing
13266/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
13267/// reverse registration order after any failure, including cooperative
13268/// cancellation. Each compensation is an ordinary durable activity, so replay,
13269/// duplicate delivery, and worker restart use existing history semantics.
13270pub struct Saga {
13271    ctx: WorkflowContext,
13272    compensations: Vec<SagaCompensation>,
13273}
13274
13275impl Saga {
13276    fn new(ctx: WorkflowContext) -> Self {
13277        Self {
13278            ctx,
13279            compensations: Vec::new(),
13280        }
13281    }
13282
13283    pub fn add_compensation<T: Serialize>(
13284        &mut self,
13285        activity_type: impl Into<String>,
13286        args: T,
13287    ) -> Result<&mut Self> {
13288        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
13289    }
13290
13291    pub fn add_compensation_with_options<T: Serialize>(
13292        &mut self,
13293        activity_type: impl Into<String>,
13294        options: ActivityOptions,
13295        args: T,
13296    ) -> Result<&mut Self> {
13297        let activity_type = activity_type.into();
13298        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
13299            return Err(Error::Codec(
13300                "saga compensation activity type must be non-empty without surrounding whitespace"
13301                    .to_string(),
13302            ));
13303        }
13304        options.validate().map_err(Error::InvalidActivityOptions)?;
13305        let arguments = AvroValue::from_serialize(&args)?;
13306        let registration_order = self.compensations.len() + 1;
13307        self.compensations.push(SagaCompensation {
13308            activity_type,
13309            options,
13310            arguments,
13311            registration_order,
13312        });
13313        Ok(self)
13314    }
13315
13316    /// Compensate `initiating_failure` and return the failure that must remain.
13317    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
13318        let _shield = match self.ctx.cancellation_shield() {
13319            Ok(shield) => shield,
13320            Err(error) => return error,
13321        };
13322        while let Some(compensation) = self.compensations.pop() {
13323            if let Err(compensation_failure) = self
13324                .ctx
13325                .activity_with_options(
13326                    compensation.activity_type.clone(),
13327                    compensation.options,
13328                    compensation.arguments,
13329                )
13330                .await
13331            {
13332                if workflow_task_integrity_error(&compensation_failure) {
13333                    return compensation_failure;
13334                }
13335                return Error::SagaCompensationFailed(SagaCompensationFailure {
13336                    initiating_failure: Box::new(initiating_failure),
13337                    compensation_failure: Box::new(compensation_failure),
13338                    compensation_activity_type: compensation.activity_type,
13339                    compensation_registration_order: compensation.registration_order,
13340                });
13341            }
13342        }
13343        initiating_failure
13344    }
13345
13346    /// Return a successful forward value or compensate and preserve its failure.
13347    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
13348        match outcome {
13349            Ok(value) => Ok(value),
13350            Err(error) => Err(self.compensate(error).await),
13351        }
13352    }
13353}
13354
13355pub struct ActivityCall {
13356    ctx: WorkflowContext,
13357    activity_type: String,
13358    options: ActivityOptions,
13359    worker_session: Option<WorkerSessionOptions>,
13360    args: Option<Result<AvroValue>>,
13361    scheduled: bool,
13362    local: bool,
13363    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
13364    parallel_group_path: Vec<ParallelGroupMetadata>,
13365}
13366
13367impl ActivityCall {
13368    fn poll_avro_value(
13369        mut self: Pin<&mut Self>,
13370        _cx: &mut TaskContext<'_>,
13371    ) -> Poll<Result<AvroValue>> {
13372        let ctx = self.ctx.clone();
13373        let mut state = match ctx.state.lock() {
13374            Ok(state) => state,
13375            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13376        };
13377
13378        if let Some(result) = &self.local_result {
13379            return match result.lock() {
13380                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
13381                    Poll::Ready(result.map_err(Error::ActivityFailed))
13382                }),
13383                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13384            };
13385        }
13386        if self.scheduled {
13387            return Poll::Pending;
13388        }
13389
13390        let options = match self.options.validate() {
13391            Ok(options) => options,
13392            Err(error) => {
13393                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
13394            }
13395        };
13396        if self.local {
13397            if self.worker_session.is_some() {
13398                return Poll::Ready(Err(Error::WorkerLoop(
13399                    "local activities cannot use worker-session routing".into(),
13400                )));
13401            }
13402            if let Err(error) = local_activity::validate(&options) {
13403                return Poll::Ready(Err(error));
13404            }
13405        }
13406        let session = match self
13407            .worker_session
13408            .as_ref()
13409            .map(WorkerSessionOptions::to_wire)
13410            .transpose()
13411        {
13412            Ok(value) => value,
13413            Err(error) => return Poll::Ready(Err(error)),
13414        };
13415        let session_queue = session
13416            .as_ref()
13417            .and_then(|session| session["queue"].as_str());
13418        let task_queue = options
13419            .task_queue
13420            .clone()
13421            .or_else(|| session_queue.map(str::to_owned))
13422            .unwrap_or_else(|| state.task_queue.clone());
13423        if session_queue.is_some_and(|queue| queue != task_queue) {
13424            return Poll::Ready(Err(Error::WorkerLoop(
13425                "worker-session queue must match the activity task queue".into(),
13426            )));
13427        }
13428        let current_recorded_options = RecordedActivityOptions {
13429            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
13430            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
13431            retry_policy: current_activity_retry_snapshot(&options),
13432            worker_session: session,
13433        };
13434
13435        let cursor = state.command_cursor;
13436        let call_kind = if self.local {
13437            CancellationCallKind::LocalActivity
13438        } else {
13439            CancellationCallKind::Activity
13440        };
13441        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13442            return Poll::Ready(Err(error));
13443        }
13444        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
13445            Ok(recorded) => recorded,
13446            Err(error) => return Poll::Ready(Err(error)),
13447        };
13448        if let Some(recorded) = recorded {
13449            let sequence = recorded.sequence();
13450            match recorded {
13451                RecordedCommand::Activity {
13452                    activity_type,
13453                    cancellation_policy,
13454                    options: recorded_options,
13455                    outcome,
13456                    parallel_group_path,
13457                    ..
13458                } => {
13459                    let current_policy = options
13460                        .cancellation_policy
13461                        .unwrap_or(CancellationPolicy::TryCancel)
13462                        .as_str();
13463                    if cancellation_policy != current_policy {
13464                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13465                            ReplayFailure::new(
13466                                "activity_cancellation_policy_changed",
13467                                Some(sequence),
13468                                Some(cancellation_policy),
13469                                Some(current_policy.to_string()),
13470                                "Activity cancellation policy changed during replay",
13471                            ),
13472                        )));
13473                    }
13474                    if let Err(error) = ensure_parallel_path_matches(
13475                        sequence,
13476                        parallel_group_path.as_deref(),
13477                        &self.parallel_group_path,
13478                    ) {
13479                        return Poll::Ready(Err(error));
13480                    }
13481                    if let Some(recorded_type) = activity_type {
13482                        if recorded_type != self.activity_type {
13483                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13484                                ReplayFailure::new(
13485                                    "recorded_command_detail_mismatch",
13486                                    Some(sequence),
13487                                    Some(format!("activity:{recorded_type}")),
13488                                    Some(format!("activity:{}", self.activity_type)),
13489                                    "recorded activity type differs from the current workflow command",
13490                                ),
13491                            )));
13492                        }
13493                    }
13494                    if let Some(recorded_options) = recorded_options {
13495                        if recorded_options.worker_session
13496                            != current_recorded_options.worker_session
13497                        {
13498                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
13499                                "activity_worker_session_mismatch", Some(sequence),
13500                                Some(activity_options_description(&recorded_options)),
13501                                Some(activity_options_description(&current_recorded_options)),
13502                                "recorded worker-session routing differs from the current activity",
13503                            ))));
13504                        }
13505                        if !recorded_options
13506                            .task_queue
13507                            .matches_current(&current_recorded_options.task_queue)
13508                        {
13509                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13510                                ReplayFailure::new(
13511                                    "activity_task_queue_mismatch",
13512                                    Some(sequence),
13513                                    Some(activity_options_description(&recorded_options)),
13514                                    Some(activity_options_description(&current_recorded_options)),
13515                                    "recorded activity task queue differs from the current workflow command",
13516                                ),
13517                            )));
13518                        }
13519                        if (self.local
13520                            && matches!(
13521                                recorded_options.execution_mode,
13522                                RecordedSnapshotValue::Unknown
13523                            ))
13524                            || !recorded_options
13525                                .execution_mode
13526                                .matches_current(&current_recorded_options.execution_mode)
13527                        {
13528                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13529                                ReplayFailure::new(
13530                                    "activity_execution_mode_mismatch",
13531                                    Some(sequence),
13532                                    Some(activity_options_description(&recorded_options)),
13533                                    Some(activity_options_description(&current_recorded_options)),
13534                                    "recorded activity execution mode differs from the current workflow command",
13535                                ),
13536                            )));
13537                        }
13538                        if !recorded_options
13539                            .retry_policy
13540                            .matches_current(&current_recorded_options.retry_policy)
13541                        {
13542                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13543                                ReplayFailure::new(
13544                                    "activity_retry_policy_mismatch",
13545                                    Some(sequence),
13546                                    Some(activity_options_description(&recorded_options)),
13547                                    Some(activity_options_description(&current_recorded_options)),
13548                                    "recorded activity retry policy differs from the current workflow command",
13549                                ),
13550                            )));
13551                        }
13552                    }
13553                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
13554                        return Poll::Ready(Err(error));
13555                    }
13556                    match state.prepare_scalar_cancellation(
13557                        cursor,
13558                        call_kind,
13559                        &self.parallel_group_path,
13560                    ) {
13561                        Ok(true) => {
13562                            self.scheduled = true;
13563                            return Poll::Pending;
13564                        }
13565                        Ok(false) => {}
13566                        Err(error) => return Poll::Ready(Err(error)),
13567                    }
13568                    state.command_cursor += 1;
13569                    if let Some(outcome) = outcome {
13570                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13571                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
13572                    }
13573                    state.matched_recorded_pending = true;
13574                    self.scheduled = true;
13575                    return Poll::Pending;
13576                }
13577                other => {
13578                    return Poll::Ready(Err(command_mismatch(
13579                        &other,
13580                        format!("activity:{}", self.activity_type),
13581                    )));
13582                }
13583            }
13584        }
13585
13586        if !self.scheduled {
13587            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
13588                Ok(args) => args,
13589                Err(error) => return Poll::Ready(Err(error)),
13590            };
13591            let arguments = normalize_avro_arguments(args);
13592            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
13593                Ok(envelope) => envelope,
13594                Err(error) => return Poll::Ready(Err(error)),
13595            };
13596
13597            let mut command = serde_json::Map::from_iter([
13598                (
13599                    "type".to_string(),
13600                    json!(if self.local {
13601                        "record_local_activity"
13602                    } else {
13603                        "schedule_activity"
13604                    }),
13605                ),
13606                (
13607                    "activity_type".to_string(),
13608                    json!(self.activity_type.clone()),
13609                ),
13610                ("queue".to_string(), json!(task_queue)),
13611                ("arguments".to_string(), envelope),
13612            ]);
13613            for (field, value) in [
13614                ("start_to_close_timeout", options.start_to_close_timeout),
13615                (
13616                    "schedule_to_start_timeout",
13617                    options.schedule_to_start_timeout,
13618                ),
13619                (
13620                    "schedule_to_close_timeout",
13621                    options.schedule_to_close_timeout,
13622                ),
13623                ("heartbeat_timeout", options.heartbeat_timeout),
13624            ] {
13625                if let Some(value) = value {
13626                    command.insert(field.to_string(), json!(value));
13627                }
13628            }
13629            if let Some(retry_policy) = &options.retry_policy {
13630                command.insert("retry_policy".to_string(), retry_policy.clone());
13631            }
13632            if let Some(policy) = options.cancellation_policy {
13633                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
13634            }
13635            if let Some(session) = current_recorded_options.worker_session {
13636                command.insert("worker_session".into(), session);
13637            }
13638            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13639            ctx.apply_scope_membership(&mut command);
13640            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
13641                Ok(true) => {
13642                    self.scheduled = true;
13643                    return Poll::Pending;
13644                }
13645                Ok(false) => {}
13646                Err(error) => return Poll::Ready(Err(error)),
13647            }
13648            if self.local {
13649                command.remove("queue");
13650                command.insert("execution_mode".into(), json!("local"));
13651                let result = Arc::new(Mutex::new(None));
13652                let command_index = state.commands.len();
13653                state.local_activity_requests.push(local_activity::Request {
13654                    command_index,
13655                    options,
13656                    arguments,
13657                    result: result.clone(),
13658                });
13659                self.local_result = Some(result);
13660            }
13661            state.commands.push(Value::Object(command));
13662            self.scheduled = true;
13663        }
13664
13665        Poll::Pending
13666    }
13667}
13668
13669impl Future for ActivityCall {
13670    type Output = Result<Value>;
13671
13672    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13673        match self.poll_avro_value(cx) {
13674            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
13675            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13676            Poll::Pending => Poll::Pending,
13677        }
13678    }
13679}
13680
13681/// Future returned by [`WorkflowContext::sleep`].
13682pub struct TimerCall {
13683    ctx: WorkflowContext,
13684    delay_seconds: Option<u64>,
13685    scheduled: bool,
13686    matched_pending: bool,
13687    parallel_group_path: Vec<ParallelGroupMetadata>,
13688}
13689
13690impl Future for TimerCall {
13691    type Output = Result<()>;
13692
13693    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13694        if self.matched_pending {
13695            return Poll::Pending;
13696        }
13697
13698        let ctx = self.ctx.clone();
13699        let Some(requested_delay) = self.delay_seconds else {
13700            return Poll::Ready(Err(Error::TimerDurationOverflow));
13701        };
13702        let mut state = match ctx.state.lock() {
13703            Ok(state) => state,
13704            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13705        };
13706
13707        let cursor = state.command_cursor;
13708        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13709            return Poll::Ready(Err(error));
13710        }
13711        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
13712        {
13713            Ok(recorded) => recorded,
13714            Err(error) => return Poll::Ready(Err(error)),
13715        };
13716        if let Some(recorded) = recorded {
13717            match recorded {
13718                RecordedCommand::Timer {
13719                    sequence,
13720                    delay_seconds,
13721                    fired,
13722                    parallel_group_path,
13723                    ..
13724                } => {
13725                    if let Err(error) =
13726                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
13727                    {
13728                        return Poll::Ready(Err(error));
13729                    }
13730                    if let Err(error) = ensure_parallel_path_matches(
13731                        sequence,
13732                        parallel_group_path.as_deref(),
13733                        &self.parallel_group_path,
13734                    ) {
13735                        return Poll::Ready(Err(error));
13736                    }
13737                    if delay_seconds != requested_delay {
13738                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13739                            ReplayFailure::new(
13740                                "timer_delay_mismatch",
13741                                Some(sequence),
13742                                Some(format!("timer:{delay_seconds}s")),
13743                                Some(format!("timer:{requested_delay}s")),
13744                                "recorded timer delay differs from the current workflow command",
13745                            ),
13746                        )));
13747                    }
13748                    if let Err(error) =
13749                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
13750                    {
13751                        return Poll::Ready(Err(error));
13752                    }
13753                    match state.prepare_scalar_cancellation(
13754                        cursor,
13755                        CancellationCallKind::Timer,
13756                        &self.parallel_group_path,
13757                    ) {
13758                        Ok(true) => {
13759                            self.scheduled = true;
13760                            self.matched_pending = true;
13761                            return Poll::Pending;
13762                        }
13763                        Ok(false) => {}
13764                        Err(error) => return Poll::Ready(Err(error)),
13765                    }
13766                    state.command_cursor += 1;
13767                    if fired {
13768                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13769                        return Poll::Ready(Ok(()));
13770                    }
13771                    state.matched_recorded_pending = true;
13772                    self.scheduled = true;
13773                    self.matched_pending = true;
13774                    return Poll::Pending;
13775                }
13776                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
13777            }
13778        }
13779
13780        if !self.scheduled {
13781            let mut command = serde_json::Map::from_iter([
13782                ("type".to_string(), json!("start_timer")),
13783                ("delay_seconds".to_string(), json!(requested_delay)),
13784            ]);
13785            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
13786                Ok(Some(proof)) => {
13787                    command.insert("cancellation_cleanup".into(), proof);
13788                }
13789                Ok(None) => {}
13790                Err(error) => return Poll::Ready(Err(error)),
13791            }
13792            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13793            ctx.apply_scope_membership(&mut command);
13794            match state.prepare_scalar_cancellation(
13795                cursor,
13796                CancellationCallKind::Timer,
13797                &self.parallel_group_path,
13798            ) {
13799                Ok(true) => {
13800                    self.scheduled = true;
13801                    self.matched_pending = true;
13802                    return Poll::Pending;
13803                }
13804                Ok(false) => {}
13805                Err(error) => return Poll::Ready(Err(error)),
13806            }
13807            state.commands.push(Value::Object(command));
13808            self.scheduled = true;
13809        }
13810
13811        Poll::Pending
13812    }
13813}
13814
13815/// Future returned by [`WorkflowContext::wait_condition`].
13816pub struct ConditionWaitCall {
13817    ctx: WorkflowContext,
13818    options: ConditionWaitOptions,
13819    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
13820    occurrence_id: Option<String>,
13821    opened_wait: bool,
13822    parallel_group_path: Vec<ParallelGroupMetadata>,
13823}
13824
13825impl Future for ConditionWaitCall {
13826    type Output = Result<ConditionWaitResult>;
13827
13828    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13829        if self.opened_wait {
13830            return Poll::Pending;
13831        }
13832
13833        let options = match self.options.validate() {
13834            Ok(options) => options,
13835            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
13836        };
13837        let ctx = self.ctx.clone();
13838        let occurrence_id = match self.occurrence_id.as_ref() {
13839            Some(occurrence_id) => occurrence_id.clone(),
13840            None => {
13841                let mut state = match ctx.state.lock() {
13842                    Ok(state) => state,
13843                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13844                };
13845                let ordinal = state.condition_wait_occurrence_counter;
13846                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
13847                    Some(next) => next,
13848                    None => {
13849                        return Poll::Ready(Err(Error::WorkerLoop(
13850                            "condition wait occurrence counter overflowed".to_string(),
13851                        )))
13852                    }
13853                };
13854                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
13855                drop(state);
13856                self.occurrence_id = Some(occurrence_id.clone());
13857                occurrence_id
13858            }
13859        };
13860
13861        let recorded_result = {
13862            let mut state = match ctx.state.lock() {
13863                Ok(state) => state,
13864                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13865            };
13866            let initial_cursor = state.command_cursor;
13867            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
13868                return Poll::Ready(Err(error));
13869            }
13870            let recorded = match state
13871                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
13872            {
13873                Ok(recorded) => recorded,
13874                Err(error) => return Poll::Ready(Err(error)),
13875            };
13876            let Some(recorded) = recorded else {
13877                drop(state);
13878                return self.poll_new_condition(options);
13879            };
13880            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
13881                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
13882            }
13883
13884            let mut cursor = state.command_cursor;
13885            let mut result = None;
13886            let mut pending_delivery = false;
13887            loop {
13888                if cursor > initial_cursor
13889                    && matches!(
13890                        state.recorded_commands.get(cursor),
13891                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
13892                    )
13893                {
13894                    break;
13895                }
13896                let recorded = match state
13897                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
13898                {
13899                    Ok(recorded) => recorded,
13900                    Err(error) => return Poll::Ready(Err(error)),
13901                };
13902                let Some(RecordedCommand::ConditionWait {
13903                    sequence,
13904                    occurrence_id: ref recorded_occurrence_id,
13905                    ref condition_key,
13906                    ref predicate_identity,
13907                    timeout_seconds,
13908                    result: recorded_result,
13909                    ref parallel_group_path,
13910                    ..
13911                }) = recorded
13912                else {
13913                    break;
13914                };
13915
13916                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
13917                    break;
13918                }
13919                if let Err(error) = ensure_parallel_path_matches(
13920                    sequence,
13921                    parallel_group_path.as_deref(),
13922                    &self.parallel_group_path,
13923                ) {
13924                    return Poll::Ready(Err(error));
13925                }
13926                if let Err(error) = validate_recorded_condition_wait(
13927                    sequence,
13928                    recorded_occurrence_id,
13929                    condition_key.as_deref(),
13930                    predicate_identity,
13931                    timeout_seconds,
13932                    &occurrence_id,
13933                    &options,
13934                ) {
13935                    return Poll::Ready(Err(error));
13936                }
13937                if result == Some(ConditionWaitResult::TimedOut) {
13938                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
13939                        "condition_wait_reopened_after_timeout",
13940                        Some(sequence),
13941                        Some("timed-out condition is terminal".to_string()),
13942                        Some("another physical wait-open".to_string()),
13943                        "condition history reopened one logical wait after its durable timeout",
13944                    ))));
13945                }
13946                if let Err(error) =
13947                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
13948                {
13949                    return Poll::Ready(Err(error));
13950                }
13951                match state.prepare_scalar_cancellation(
13952                    cursor,
13953                    CancellationCallKind::Condition,
13954                    &self.parallel_group_path,
13955                ) {
13956                    Ok(pending) => pending_delivery |= pending,
13957                    Err(error) => return Poll::Ready(Err(error)),
13958                }
13959                result = recorded_result;
13960                if result.is_some() {
13961                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13962                }
13963                cursor += 1;
13964            }
13965            state.command_cursor = cursor;
13966            if pending_delivery {
13967                self.opened_wait = true;
13968                return Poll::Pending;
13969            }
13970            result
13971        };
13972
13973        if let Some(result) = recorded_result {
13974            return Poll::Ready(Ok(result));
13975        }
13976
13977        self.poll_open_condition(options, true)
13978    }
13979}
13980
13981impl ConditionWaitCall {
13982    fn poll_new_condition(
13983        self: Pin<&mut Self>,
13984        options: ValidatedConditionWaitOptions,
13985    ) -> Poll<Result<ConditionWaitResult>> {
13986        self.poll_open_condition(options, false)
13987    }
13988
13989    fn poll_open_condition(
13990        mut self: Pin<&mut Self>,
13991        options: ValidatedConditionWaitOptions,
13992        recorded_wait: bool,
13993    ) -> Poll<Result<ConditionWaitResult>> {
13994        {
13995            let ctx = self.ctx.clone();
13996            let mut state = match ctx.state.lock() {
13997                Ok(state) => state,
13998                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13999            };
14000            let cursor = state.command_cursor;
14001            match state.prepare_scalar_cancellation(
14002                cursor,
14003                CancellationCallKind::Condition,
14004                &self.parallel_group_path,
14005            ) {
14006                Ok(true) => {
14007                    self.opened_wait = true;
14008                    return Poll::Pending;
14009                }
14010                Ok(false) => {}
14011                Err(error) => return Poll::Ready(Err(error)),
14012            }
14013        }
14014        let selection_member = self
14015            .parallel_group_path
14016            .first()
14017            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14018        match (self.predicate)() {
14019            Ok(true) if !selection_member || recorded_wait => {
14020                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14021            }
14022            Ok(_) => {}
14023            Err(error) => return Poll::Ready(Err(error)),
14024        }
14025        if options.timeout_seconds == Some(0) && !selection_member {
14026            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14027        }
14028
14029        let ctx = self.ctx.clone();
14030        let mut state = match ctx.state.lock() {
14031            Ok(state) => state,
14032            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14033        };
14034        let mut command = serde_json::Map::from_iter([
14035            ("type".to_string(), json!("open_condition_wait")),
14036            (
14037                "condition_wait_occurrence_id".to_string(),
14038                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14039            ),
14040            ("condition_key".to_string(), json!(options.condition_key)),
14041            (
14042                "condition_definition_fingerprint".to_string(),
14043                json!(options.predicate_identity),
14044            ),
14045        ]);
14046        if let Some(timeout_seconds) = options.timeout_seconds {
14047            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14048        }
14049        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14050        ctx.apply_scope_membership(&mut command);
14051        state.commands.push(Value::Object(command));
14052        drop(state);
14053        self.opened_wait = true;
14054        Poll::Pending
14055    }
14056}
14057
14058fn validate_recorded_condition_wait(
14059    sequence: u64,
14060    recorded_occurrence_id: &str,
14061    recorded_key: Option<&str>,
14062    recorded_predicate_identity: &str,
14063    recorded_timeout_seconds: Option<u64>,
14064    current_occurrence_id: &str,
14065    current: &ValidatedConditionWaitOptions,
14066) -> Result<()> {
14067    if recorded_occurrence_id != current_occurrence_id {
14068        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14069            "condition_wait_occurrence_mismatch",
14070            Some(sequence),
14071            Some(recorded_occurrence_id.to_string()),
14072            Some(current_occurrence_id.to_string()),
14073            "recorded condition occurrence differs from the current authored wait position",
14074        )));
14075    }
14076    if recorded_key != Some(current.condition_key.as_str()) {
14077        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14078            "condition_wait_key_mismatch",
14079            Some(sequence),
14080            recorded_key.map(str::to_string),
14081            Some(current.condition_key.clone()),
14082            "recorded condition identity differs from the current workflow wait",
14083        )));
14084    }
14085    if recorded_predicate_identity != current.predicate_identity {
14086        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14087            "condition_wait_predicate_mismatch",
14088            Some(sequence),
14089            Some(recorded_predicate_identity.to_string()),
14090            Some(current.predicate_identity.clone()),
14091            "recorded condition predicate behavior differs from current workflow code",
14092        )));
14093    }
14094    if recorded_timeout_seconds != current.timeout_seconds {
14095        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14096            "condition_wait_timeout_mismatch",
14097            Some(sequence),
14098            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14099            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14100            "recorded condition timeout differs from the current workflow wait",
14101        )));
14102    }
14103    Ok(())
14104}
14105
14106/// Future returned by [`WorkflowContext::start_child_workflow`].
14107pub struct ChildWorkflowCall {
14108    ctx: WorkflowContext,
14109    workflow_type: String,
14110    options: ChildWorkflowOptions,
14111    args: Option<Result<AvroValue>>,
14112    scheduled: bool,
14113    matched_pending: bool,
14114    parallel_group_path: Vec<ParallelGroupMetadata>,
14115}
14116
14117impl ChildWorkflowCall {
14118    fn poll_avro_value(
14119        mut self: Pin<&mut Self>,
14120        _cx: &mut TaskContext<'_>,
14121    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14122        if self.matched_pending {
14123            return Poll::Pending;
14124        }
14125
14126        let ctx = self.ctx.clone();
14127        let mut state = match ctx.state.lock() {
14128            Ok(state) => state,
14129            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14130        };
14131
14132        let cursor = state.command_cursor;
14133        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14134            return Poll::Ready(Err(error));
14135        }
14136        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14137        {
14138            Ok(recorded) => recorded,
14139            Err(error) => return Poll::Ready(Err(error)),
14140        };
14141        if let Some(recorded) = recorded {
14142            let sequence = recorded.sequence();
14143            match recorded {
14144                RecordedCommand::ChildWorkflow {
14145                    workflow_type,
14146                    policies,
14147                    outcome,
14148                    parallel_group_path,
14149                    ..
14150                } => {
14151                    if let Err(error) = ensure_parallel_path_matches(
14152                        sequence,
14153                        parallel_group_path.as_deref(),
14154                        &self.parallel_group_path,
14155                    ) {
14156                        return Poll::Ready(Err(error));
14157                    }
14158                    if let Some(recorded_type) = workflow_type {
14159                        if recorded_type != self.workflow_type {
14160                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14161                                ReplayFailure::new(
14162                                    "recorded_command_detail_mismatch",
14163                                    Some(sequence),
14164                                    Some(format!("child workflow:{recorded_type}")),
14165                                    Some(format!("child workflow:{}", self.workflow_type)),
14166                                    "recorded child workflow type differs from the current workflow command",
14167                                ),
14168                            )));
14169                        }
14170                    }
14171                    if let Err(error) =
14172                        ensure_child_policies_match(sequence, &policies, &self.options)
14173                    {
14174                        return Poll::Ready(Err(error));
14175                    }
14176                    if let Err(error) =
14177                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14178                    {
14179                        return Poll::Ready(Err(error));
14180                    }
14181                    match state.prepare_scalar_cancellation(
14182                        cursor,
14183                        CancellationCallKind::Child,
14184                        &self.parallel_group_path,
14185                    ) {
14186                        Ok(true) => {
14187                            self.scheduled = true;
14188                            self.matched_pending = true;
14189                            return Poll::Pending;
14190                        }
14191                        Ok(false) => {}
14192                        Err(error) => return Poll::Ready(Err(error)),
14193                    }
14194                    state.command_cursor += 1;
14195                    if let Some(outcome) = outcome {
14196                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14197                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
14198                    }
14199                    state.matched_recorded_pending = true;
14200                    self.scheduled = true;
14201                    self.matched_pending = true;
14202                    return Poll::Pending;
14203                }
14204                other => {
14205                    return Poll::Ready(Err(command_mismatch(
14206                        &other,
14207                        format!("child workflow:{}", self.workflow_type),
14208                    )));
14209                }
14210            }
14211        }
14212
14213        if !self.scheduled {
14214            if self.options.task_queue.trim().is_empty() {
14215                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14216                    "task_queue must not be empty".to_string(),
14217                )));
14218            }
14219            for (name, value) in [
14220                (
14221                    "execution_timeout_seconds",
14222                    self.options.execution_timeout_seconds,
14223                ),
14224                ("run_timeout_seconds", self.options.run_timeout_seconds),
14225            ] {
14226                if value == Some(0) {
14227                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
14228                        "{name} must be at least 1"
14229                    ))));
14230                }
14231            }
14232
14233            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14234                Ok(args) => args,
14235                Err(error) => return Poll::Ready(Err(error)),
14236            };
14237            let arguments = match encode_typed_envelope(
14238                &normalize_avro_arguments(args),
14239                &state.payload_codec,
14240            ) {
14241                Ok(arguments) => arguments,
14242                Err(error) => return Poll::Ready(Err(error)),
14243            };
14244            let mut command = json!({
14245                "type": "start_child_workflow",
14246                "workflow_type": self.workflow_type,
14247                "queue": self.options.task_queue,
14248                "parent_close_policy": self.options.parent_close_policy.as_str(),
14249                "arguments": arguments,
14250            });
14251            let object = command
14252                .as_object_mut()
14253                .expect("child workflow command is always an object");
14254            if self.options.cancellation_policy != CancellationPolicy::Abandon {
14255                object.insert(
14256                    "cancellation_policy".to_string(),
14257                    json!(self.options.cancellation_policy.as_str()),
14258                );
14259            }
14260            if let Some(policy) = &self.options.retry_policy {
14261                let mut retry_policy = serde_json::Map::new();
14262                if let Some(max_attempts) = policy.max_attempts {
14263                    if max_attempts == 0 {
14264                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14265                            "retry_policy.max_attempts must be at least 1".to_string(),
14266                        )));
14267                    }
14268                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
14269                }
14270                if !policy.backoff_seconds.is_empty() {
14271                    retry_policy
14272                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
14273                }
14274                if !policy.non_retryable_error_types.is_empty() {
14275                    retry_policy.insert(
14276                        "non_retryable_error_types".to_string(),
14277                        json!(policy.non_retryable_error_types),
14278                    );
14279                }
14280                if retry_policy.is_empty() {
14281                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14282                        "retry_policy must configure at least one field".to_string(),
14283                    )));
14284                }
14285                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
14286            }
14287            if let Some(seconds) = self.options.execution_timeout_seconds {
14288                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
14289            }
14290            if let Some(seconds) = self.options.run_timeout_seconds {
14291                object.insert("run_timeout_seconds".to_string(), json!(seconds));
14292            }
14293            apply_parallel_group_path(object, &self.parallel_group_path);
14294            ctx.apply_scope_membership(object);
14295            match state.prepare_scalar_cancellation(
14296                cursor,
14297                CancellationCallKind::Child,
14298                &self.parallel_group_path,
14299            ) {
14300                Ok(true) => {
14301                    self.scheduled = true;
14302                    self.matched_pending = true;
14303                    return Poll::Pending;
14304                }
14305                Ok(false) => {}
14306                Err(error) => return Poll::Ready(Err(error)),
14307            }
14308            state.commands.push(command);
14309            self.scheduled = true;
14310        }
14311
14312        Poll::Pending
14313    }
14314}
14315
14316impl Future for ChildWorkflowCall {
14317    type Output = Result<ChildWorkflowResult>;
14318
14319    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14320        match self.poll_avro_value(cx) {
14321            Poll::Ready(Ok(result)) => match result.result.into_json() {
14322                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
14323                    parent: result.parent,
14324                    child: result.child,
14325                    child_workflow_type: result.child_workflow_type,
14326                    result: projected,
14327                })),
14328                Err(error) => Poll::Ready(Err(error)),
14329            },
14330            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14331            Poll::Pending => Poll::Pending,
14332        }
14333    }
14334}
14335
14336fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
14337    Error::NonDeterministicReplay(ReplayFailure::new(
14338        "recorded_command_mismatch",
14339        Some(recorded.sequence()),
14340        Some(recorded.shape().to_string()),
14341        Some(actual.into()),
14342        "current workflow command does not match the recorded durable command sequence",
14343    ))
14344}
14345
14346pub struct SignalCall {
14347    ctx: WorkflowContext,
14348    signal_name: String,
14349    runtime_reserved_allowed: bool,
14350    opened_wait: bool,
14351    matched_pending: bool,
14352    parallel_group_path: Vec<ParallelGroupMetadata>,
14353}
14354
14355impl SignalCall {
14356    fn poll_avro_value(
14357        mut self: Pin<&mut Self>,
14358        _cx: &mut TaskContext<'_>,
14359    ) -> Poll<Result<Vec<AvroValue>>> {
14360        if self.matched_pending {
14361            return Poll::Pending;
14362        }
14363        if !self.runtime_reserved_allowed {
14364            if let Err(error) = validate_user_signal_name(&self.signal_name) {
14365                return Poll::Ready(Err(error));
14366            }
14367        }
14368
14369        let ctx = self.ctx.clone();
14370        let mut state = match ctx.state.lock() {
14371            Ok(state) => state,
14372            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14373        };
14374
14375        let cursor = state.command_cursor;
14376        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14377            return Poll::Ready(Err(error));
14378        }
14379        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
14380        {
14381            Ok(recorded) => recorded,
14382            Err(error) => return Poll::Ready(Err(error)),
14383        };
14384        if let Some(recorded) = recorded {
14385            match recorded {
14386                RecordedCommand::SignalWait {
14387                    sequence,
14388                    signal_name,
14389                    value,
14390                    parallel_group_path,
14391                } => {
14392                    if let Err(error) = ensure_parallel_path_matches(
14393                        sequence,
14394                        parallel_group_path.as_deref(),
14395                        &self.parallel_group_path,
14396                    ) {
14397                        return Poll::Ready(Err(error));
14398                    }
14399                    if signal_name != self.signal_name {
14400                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14401                            ReplayFailure::new(
14402                                "recorded_command_detail_mismatch",
14403                                Some(sequence),
14404                                Some(format!("signal wait:{signal_name}")),
14405                                Some(format!("signal wait:{}", self.signal_name)),
14406                                "recorded signal name differs from the current workflow command",
14407                            ),
14408                        )));
14409                    }
14410
14411                    if let Err(error) =
14412                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
14413                    {
14414                        return Poll::Ready(Err(error));
14415                    }
14416                    match state.prepare_scalar_cancellation(
14417                        cursor,
14418                        CancellationCallKind::Signal,
14419                        &self.parallel_group_path,
14420                    ) {
14421                        Ok(true) => {
14422                            self.opened_wait = true;
14423                            self.matched_pending = true;
14424                            return Poll::Pending;
14425                        }
14426                        Ok(false) => {}
14427                        Err(error) => return Poll::Ready(Err(error)),
14428                    }
14429                    state.command_cursor += 1;
14430                    if let Some(value) = value {
14431                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14432                        return Poll::Ready(Ok(value));
14433                    }
14434                    if state
14435                        .resume_signal
14436                        .as_ref()
14437                        .is_some_and(|signal| signal.signal_name == self.signal_name)
14438                    {
14439                        let signal = state
14440                            .resume_signal
14441                            .take()
14442                            .expect("matching resume signal is present");
14443                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
14444                        return Poll::Ready(Ok(signal.arguments));
14445                    }
14446
14447                    state.matched_recorded_pending = true;
14448                    self.opened_wait = true;
14449                    self.matched_pending = true;
14450                    return Poll::Pending;
14451                }
14452                other => {
14453                    return Poll::Ready(Err(command_mismatch(
14454                        &other,
14455                        format!("signal wait:{}", self.signal_name),
14456                    )));
14457                }
14458            }
14459        }
14460
14461        match state.prepare_scalar_cancellation(
14462            cursor,
14463            CancellationCallKind::Signal,
14464            &self.parallel_group_path,
14465        ) {
14466            Ok(true) => {
14467                self.opened_wait = true;
14468                self.matched_pending = true;
14469                return Poll::Pending;
14470            }
14471            Ok(false) => {}
14472            Err(error) => return Poll::Ready(Err(error)),
14473        }
14474
14475        if state
14476            .resume_signal
14477            .as_ref()
14478            .is_some_and(|signal| signal.signal_name == self.signal_name)
14479        {
14480            let signal = state
14481                .resume_signal
14482                .take()
14483                .expect("matching resume signal is present");
14484            state.unavailable_cancellation_boundary(&self.parallel_group_path);
14485            return Poll::Ready(Ok(signal.arguments));
14486        }
14487
14488        if !self.opened_wait {
14489            let mut command = serde_json::Map::from_iter([
14490                ("type".to_string(), json!("open_signal_wait")),
14491                ("signal_name".to_string(), json!(self.signal_name)),
14492            ]);
14493            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14494            ctx.apply_scope_membership(&mut command);
14495            state.commands.push(Value::Object(command));
14496            self.opened_wait = true;
14497        }
14498
14499        Poll::Pending
14500    }
14501}
14502
14503impl Future for SignalCall {
14504    type Output = Result<Vec<Value>>;
14505
14506    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14507        match self.poll_avro_value(cx) {
14508            Poll::Ready(Ok(values)) => Poll::Ready(
14509                values
14510                    .into_iter()
14511                    .map(AvroValue::into_json)
14512                    .collect::<Result<Vec<_>>>(),
14513            ),
14514            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14515            Poll::Pending => Poll::Pending,
14516        }
14517    }
14518}
14519
14520#[derive(Clone, Debug)]
14521pub struct ActivityContext {
14522    client: Client,
14523    pub task_id: String,
14524    pub activity_attempt_id: String,
14525    pub lease_owner: String,
14526    pub activity_type: String,
14527    pub attempt_number: u64,
14528    pub task_queue: String,
14529    pub worker_id: String,
14530    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
14531    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
14532    worker_session: Option<WorkerSession>,
14533}
14534
14535impl ActivityContext {
14536    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
14537        if let Some(heartbeats) = &self.local_heartbeats {
14538            return heartbeats
14539                .lock()
14540                .map_err(|_| Error::WorkflowStatePoisoned)?
14541                .record(details);
14542        }
14543        if let Some(guard) = &self.claim_guard {
14544            return guard.heartbeat(self, details).await;
14545        }
14546        if let Some(session) = &self.worker_session {
14547            if !session.active() {
14548                return Err(Error::ActivityExecutionAbandoned(
14549                    "worker-session lease or TTL is no longer active".into(),
14550                ));
14551            }
14552            let result = self
14553                .client
14554                .heartbeat_activity_task_value(
14555                    &self.task_id,
14556                    &self.activity_attempt_id,
14557                    &self.lease_owner,
14558                    details,
14559                )
14560                .await;
14561            return worker_session::settle_activity_heartbeat(
14562                session,
14563                result,
14564                &self.task_id,
14565                &self.activity_attempt_id,
14566                &self.lease_owner,
14567            );
14568        }
14569        self.client
14570            .heartbeat_activity_task(
14571                &self.task_id,
14572                &self.activity_attempt_id,
14573                &self.lease_owner,
14574                details,
14575            )
14576            .await
14577    }
14578}
14579
14580fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
14581    validate_payload_codec(codec)?;
14582    match value {
14583        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
14584            value, codec,
14585        )?)),
14586        None => Ok(AvroValue::Array(Vec::new())),
14587    }
14588}
14589
14590fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
14591    let Some(signal_name) = task
14592        .signal_name
14593        .as_deref()
14594        .filter(|value| !value.is_empty())
14595    else {
14596        return Ok(None);
14597    };
14598    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
14599    let AvroValue::Array(arguments) = decoded else {
14600        unreachable!("normalize_avro_arguments always returns an array");
14601    };
14602
14603    Ok(Some(ResumeSignal {
14604        signal_name: signal_name.to_string(),
14605        arguments,
14606    }))
14607}
14608
14609fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
14610    validate_payload_codec(&task.payload_codec)?;
14611    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
14612    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
14613    for event in &task.history_events {
14614        validate_history_event_payloads(event, &task.payload_codec)?;
14615    }
14616    Ok(())
14617}
14618
14619fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
14620    validate_payload_codec(&task.payload_codec)?;
14621    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
14622}
14623
14624fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
14625    validate_payload_codec(&task.payload_codec)?;
14626    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
14627    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
14628    for event in &task.history_events {
14629        validate_history_event_payloads(event, &task.payload_codec)?;
14630    }
14631
14632    let Some(export) = task.history_export.as_ref() else {
14633        return Ok(());
14634    };
14635    let export_codec = match export.get("payloads") {
14636        Some(payloads) => declared_payload_codec(payloads, "codec")?,
14637        None => None,
14638    }
14639    .unwrap_or(&task.payload_codec);
14640    validate_payload_codec(export_codec)?;
14641
14642    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
14643        for event in events {
14644            let event_type = event
14645                .get("event_type")
14646                .or_else(|| event.get("type"))
14647                .and_then(Value::as_str)
14648                .unwrap_or_default();
14649            if let Some(payload) = event.get("payload") {
14650                validate_history_payloads(event_type, payload, export_codec)?;
14651            }
14652        }
14653    }
14654    for signal in export
14655        .get("signals")
14656        .and_then(Value::as_array)
14657        .into_iter()
14658        .flatten()
14659    {
14660        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
14661        validate_payload_codec(codec)?;
14662        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
14663    }
14664    for activity in export
14665        .get("activities")
14666        .and_then(Value::as_array)
14667        .into_iter()
14668        .flatten()
14669    {
14670        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
14671        validate_payload_codec(codec)?;
14672        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
14673        validate_optional_inbound_payload(activity.get("result"), codec)?;
14674    }
14675    Ok(())
14676}
14677
14678fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
14679    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
14680}
14681
14682fn validate_history_payloads(
14683    event_type: &str,
14684    payload: &Value,
14685    fallback_codec: &str,
14686) -> Result<()> {
14687    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
14688    validate_payload_codec(codec)?;
14689    for field in history_payload_fields(event_type) {
14690        validate_optional_inbound_payload(payload.get(*field), codec)?;
14691    }
14692    Ok(())
14693}
14694
14695const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
14696
14697fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
14698    match event_type {
14699        "ActivityCompleted" => &["result"],
14700        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
14701        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
14702        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
14703        "ChildRunCompleted" => &["result", "output"],
14704        "WorkflowCompleted" => &["output"],
14705        "ServiceCallStarted"
14706        | "ServiceCallCompleted"
14707        | "ServiceCallFailed"
14708        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
14709        _ => &[],
14710    }
14711}
14712
14713fn signal_history_payload(payload: &Value) -> Option<&Value> {
14714    SIGNAL_HISTORY_PAYLOAD_FIELDS
14715        .iter()
14716        .find_map(|field| payload.get(*field))
14717}
14718
14719fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
14720    match value.get(field) {
14721        None => Ok(None),
14722        Some(Value::String(codec)) => Ok(Some(codec)),
14723        Some(_) => Err(invalid_payload_envelope()),
14724    }
14725}
14726
14727fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
14728    validate_payload_codec(codec)?;
14729    if let Some(value) = value.filter(|value| !value.is_null()) {
14730        decode_wire_avro_value(value, codec)?;
14731    }
14732    Ok(())
14733}
14734
14735fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
14736    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
14737        invalid_recorded_history(
14738            "parallel_group_metadata_invalid",
14739            sequence,
14740            "non-empty parallel_group_id",
14741            &payload.to_string(),
14742            "parallel-group history is missing its stable identity",
14743        )
14744    })?;
14745    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
14746        invalid_recorded_history(
14747            "parallel_group_metadata_invalid",
14748            sequence,
14749            "activity, child, timer, signal, condition, or mixed group kind",
14750            &payload.to_string(),
14751            "parallel-group history is missing its group kind",
14752        )
14753    })?;
14754    if !matches!(
14755        kind.as_str(),
14756        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
14757    ) {
14758        return Err(invalid_recorded_history(
14759            "parallel_group_metadata_invalid",
14760            sequence,
14761            "activity, child, timer, signal, condition, or mixed group kind",
14762            &kind,
14763            "parallel-group history contains an unsupported group kind",
14764        ));
14765    }
14766    let base_sequence = payload
14767        .get("parallel_group_base_sequence")
14768        .and_then(value_as_u64)
14769        .filter(|value| *value > 0)
14770        .ok_or_else(|| {
14771            invalid_recorded_history(
14772                "parallel_group_metadata_invalid",
14773                sequence,
14774                "positive parallel_group_base_sequence",
14775                &payload.to_string(),
14776                "parallel-group history contains an invalid base sequence",
14777            )
14778        })?;
14779    let size = payload
14780        .get("parallel_group_size")
14781        .and_then(value_as_u64)
14782        .and_then(|value| usize::try_from(value).ok())
14783        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
14784        .ok_or_else(|| {
14785            invalid_recorded_history(
14786                "parallel_group_metadata_invalid",
14787                sequence,
14788                "bounded positive parallel_group_size",
14789                &payload.to_string(),
14790                "parallel-group history contains an invalid group size",
14791            )
14792        })?;
14793    let index = payload
14794        .get("parallel_group_index")
14795        .and_then(value_as_u64)
14796        .and_then(|value| usize::try_from(value).ok())
14797        .filter(|value| *value < size)
14798        .ok_or_else(|| {
14799            invalid_recorded_history(
14800                "parallel_group_metadata_invalid",
14801                sequence,
14802                "parallel_group_index within group bounds",
14803                &payload.to_string(),
14804                "parallel-group history contains an invalid member index",
14805            )
14806        })?;
14807    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
14808        return Err(invalid_recorded_history(
14809            "parallel_group_metadata_invalid",
14810            sequence,
14811            "base sequence plus member index equals workflow sequence",
14812            &payload.to_string(),
14813            "parallel-group path does not preserve durable workflow position",
14814        ));
14815    }
14816    let mode = payload
14817        .get("parallel_group_mode")
14818        .and_then(Value::as_str)
14819        .unwrap_or("all");
14820    if !matches!(mode, "all" | "select") {
14821        return Err(invalid_recorded_history(
14822            "parallel_group_metadata_invalid",
14823            sequence,
14824            "parallel group mode all or select",
14825            mode,
14826            "parallel-group history contains an unsupported group mode",
14827        ));
14828    }
14829    let expected_id = if mode == "select" {
14830        format!("select-calls:{base_sequence}:{size}")
14831    } else {
14832        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
14833    };
14834    if group_id != expected_id {
14835        return Err(invalid_recorded_history(
14836            "parallel_group_metadata_invalid",
14837            sequence,
14838            &expected_id,
14839            &group_id,
14840            "parallel-group history contains an incompatible stable group ID",
14841        ));
14842    }
14843    let selection_member_key = if mode == "select" {
14844        Some(selection_key_from_value(
14845            payload.get("selection_member_key"),
14846            sequence,
14847        )?)
14848    } else {
14849        None
14850    };
14851    let selection_member_index = if mode == "select" {
14852        Some(required_parallel_usize(
14853            payload,
14854            "selection_member_index",
14855            sequence,
14856        )?)
14857    } else {
14858        None
14859    };
14860    let selection_member_base_sequence = if mode == "select" {
14861        Some(
14862            payload
14863                .get("selection_member_base_sequence")
14864                .and_then(value_as_u64)
14865                .filter(|value| *value >= base_sequence)
14866                .ok_or_else(|| {
14867                    invalid_recorded_history(
14868                        "parallel_group_metadata_invalid",
14869                        sequence,
14870                        "selection member base within its group",
14871                        &payload.to_string(),
14872                        "selection history contains an invalid member base sequence",
14873                    )
14874                })?,
14875        )
14876    } else {
14877        None
14878    };
14879    let selection_member_size = if mode == "select" {
14880        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
14881        if member_size == 0 {
14882            return Err(invalid_recorded_history(
14883                "parallel_group_metadata_invalid",
14884                sequence,
14885                "positive selection member size",
14886                &payload.to_string(),
14887                "selection history contains an invalid member size",
14888            ));
14889        }
14890        Some(member_size)
14891    } else {
14892        None
14893    };
14894    let selection_member_kind = if mode == "select" {
14895        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
14896            invalid_recorded_history(
14897                "parallel_group_metadata_invalid",
14898                sequence,
14899                "selection member operation kind",
14900                &payload.to_string(),
14901                "selection history is missing its authored member kind",
14902            )
14903        })?;
14904        if !matches!(
14905            kind.as_str(),
14906            "activity" | "child" | "timer" | "signal" | "condition" | "group"
14907        ) {
14908            return Err(invalid_recorded_history(
14909                "parallel_group_metadata_invalid",
14910                sequence,
14911                "activity, child, timer, signal, condition, or group selection member kind",
14912                &kind,
14913                "selection history contains an unsupported member kind",
14914            ));
14915        }
14916        Some(kind)
14917    } else {
14918        None
14919    };
14920    if let (Some(member_base), Some(member_size)) =
14921        (selection_member_base_sequence, selection_member_size)
14922    {
14923        let member_end = member_base
14924            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
14925            .ok_or_else(|| {
14926                invalid_recorded_history(
14927                    "parallel_group_metadata_invalid",
14928                    sequence,
14929                    "bounded selection member range",
14930                    &payload.to_string(),
14931                    "selection member range overflowed",
14932                )
14933            })?;
14934        let group_end = base_sequence
14935            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
14936            .unwrap_or(u64::MAX);
14937        if sequence < member_base || sequence >= member_end || member_end > group_end {
14938            return Err(invalid_recorded_history(
14939                "parallel_group_metadata_invalid",
14940                sequence,
14941                "workflow sequence within one bounded selection member",
14942                &payload.to_string(),
14943                "selection member range does not contain its durable leaf",
14944            ));
14945        }
14946    }
14947    Ok(ParallelGroupMetadata {
14948        parallel_group_id: group_id,
14949        parallel_group_kind: kind,
14950        parallel_group_base_sequence: base_sequence,
14951        parallel_group_size: size,
14952        parallel_group_index: index,
14953        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
14954        selection_member_key,
14955        selection_member_index,
14956        selection_member_base_sequence,
14957        selection_member_size,
14958        selection_member_kind,
14959    })
14960}
14961
14962fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
14963    payload
14964        .get(field)
14965        .and_then(value_as_u64)
14966        .and_then(|value| usize::try_from(value).ok())
14967        .ok_or_else(|| {
14968            invalid_recorded_history(
14969                "parallel_group_metadata_invalid",
14970                sequence,
14971                &format!("non-negative integer {field}"),
14972                &payload.to_string(),
14973                "selection history contains invalid member metadata",
14974            )
14975        })
14976}
14977
14978fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
14979    match value {
14980        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
14981        Some(value) => value_as_u64(value)
14982            .and_then(|value| usize::try_from(value).ok())
14983            .map(SelectionKey::Index)
14984            .ok_or_else(|| {
14985                invalid_recorded_history(
14986                    "selection_member_key_invalid",
14987                    sequence,
14988                    "non-empty string or non-negative integer member key",
14989                    &value.to_string(),
14990                    "selection history contains an invalid member key",
14991                )
14992            }),
14993        None => Err(invalid_recorded_history(
14994            "selection_member_key_missing",
14995            sequence,
14996            "selection_member_key",
14997            "<missing>",
14998            "selection history is missing its stable member key",
14999        )),
15000    }
15001}
15002
15003fn recorded_parallel_group_path(
15004    events: &[&HistoryEvent],
15005    sequence: u64,
15006) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15007    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15008    for event in events {
15009        let payload = &event.payload;
15010        let has_metadata = payload.get("parallel_group_path").is_some()
15011            || payload.get("parallel_group_id").is_some()
15012            || payload.get("parallel_group_kind").is_some()
15013            || payload.get("parallel_group_base_sequence").is_some()
15014            || payload.get("parallel_group_size").is_some()
15015            || payload.get("parallel_group_index").is_some()
15016            || payload.get("parallel_group_mode").is_some()
15017            || payload.get("selection_member_key").is_some();
15018        if !has_metadata {
15019            continue;
15020        }
15021
15022        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15023        let path = match payload.get("parallel_group_path") {
15024            None => vec![top_level.clone()],
15025            Some(Value::Array(entries)) if !entries.is_empty() => entries
15026                .iter()
15027                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15028                .collect::<Result<Vec<_>>>()?,
15029            Some(value) => {
15030                return Err(invalid_recorded_history(
15031                    "parallel_group_metadata_invalid",
15032                    sequence,
15033                    "non-empty parallel_group_path list",
15034                    &value.to_string(),
15035                    "parallel-group history contains an invalid group path",
15036                ));
15037            }
15038        };
15039        if path.last() != Some(&top_level) {
15040            return Err(invalid_recorded_history(
15041                "parallel_group_metadata_invalid",
15042                sequence,
15043                &serde_json::to_string(&path.last()).unwrap_or_default(),
15044                &serde_json::to_string(&top_level).unwrap_or_default(),
15045                "parallel-group top-level fields do not match the innermost path entry",
15046            ));
15047        }
15048        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15049            return Err(invalid_recorded_history(
15050                "parallel_group_history_conflict",
15051                sequence,
15052                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15053                &serde_json::to_string(&path).unwrap_or_default(),
15054                "parallel-group metadata changed between scheduling and resolution history",
15055            ));
15056        }
15057        recorded = Some(path);
15058    }
15059    Ok(recorded)
15060}
15061
15062fn recorded_commands(
15063    events: &[HistoryEvent],
15064    fallback_codec: &str,
15065    parent: WorkflowIdentity,
15066) -> Result<Vec<RecordedCommand>> {
15067    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15068    let mut last_new_sequence = None;
15069
15070    for event in events {
15071        let is_activity = matches!(
15072            event.event_type.as_str(),
15073            "ActivityScheduled"
15074                | "ActivityStarted"
15075                | "ActivityHeartbeatRecorded"
15076                | "ActivityRetryScheduled"
15077                | "ActivityCompleted"
15078                | "ActivityFailed"
15079                | "ActivityCancelled"
15080                | "ActivityTimedOut"
15081        );
15082        let is_workflow_timer = matches!(
15083            event.event_type.as_str(),
15084            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15085        ) && !is_internal_timer_event(event);
15086        let is_child_workflow = matches!(
15087            event.event_type.as_str(),
15088            "ChildWorkflowScheduled"
15089                | "ChildRunStarted"
15090                | "ChildRunCompleted"
15091                | "ChildRunFailed"
15092                | "ChildRunCancelled"
15093                | "ChildRunTerminated"
15094        );
15095        let is_signal_wait = is_recorded_signal_wait_event(event);
15096        let is_condition_wait = is_recorded_condition_wait_event(event);
15097        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15098        let is_side_effect = event.event_type == "SideEffectRecorded";
15099        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15100        let is_memo = event.event_type == "MemoUpserted";
15101        if !is_activity
15102            && !is_workflow_timer
15103            && !is_child_workflow
15104            && !is_signal_wait
15105            && !is_condition_wait
15106            && !is_search_attributes
15107            && !is_side_effect
15108            && !is_version_marker
15109            && !is_memo
15110        {
15111            continue;
15112        }
15113
15114        let sequence = durable_event_sequence(event).ok_or_else(|| {
15115            Error::NonDeterministicReplay(ReplayFailure::new(
15116                "durable_command_sequence_missing",
15117                None,
15118                Some("positive workflow sequence".to_string()),
15119                Some(event.event_type.clone()),
15120                "durable command history event has no workflow sequence",
15121            ))
15122        })?;
15123        if sequence == 0 {
15124            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15125                "durable_command_sequence_invalid",
15126                Some(sequence),
15127                Some("positive workflow sequence".to_string()),
15128                Some(sequence.to_string()),
15129                "durable command history uses an invalid workflow sequence",
15130            )));
15131        }
15132        if !events_by_sequence.contains_key(&sequence) {
15133            if let Some(previous) = last_new_sequence {
15134                if sequence < previous {
15135                    return Err(invalid_recorded_history(
15136                        "durable_command_sequence_mismatch",
15137                        sequence,
15138                        &format!("workflow sequence greater than {previous}"),
15139                        &sequence.to_string(),
15140                        "durable commands are not strictly ordered by their recorded workflow sequence",
15141                    ));
15142                }
15143            }
15144            last_new_sequence = Some(sequence);
15145        }
15146        events_by_sequence.entry(sequence).or_default().push(event);
15147    }
15148
15149    let commands: Vec<RecordedCommand> = events_by_sequence
15150        .into_iter()
15151        .map(|(sequence, sequence_events)| {
15152            let activity_events: Vec<_> = sequence_events
15153                .iter()
15154                .copied()
15155                .filter(|event| event.event_type.starts_with("Activity"))
15156                .collect();
15157            let timer_events: Vec<_> = sequence_events
15158                .iter()
15159                .copied()
15160                .filter(|event| event.event_type.starts_with("Timer"))
15161                .collect();
15162            let child_events: Vec<_> = sequence_events
15163                .iter()
15164                .copied()
15165                .filter(|event| {
15166                    event.event_type == "ChildWorkflowScheduled"
15167                        || event.event_type.starts_with("ChildRun")
15168                })
15169                .collect();
15170            let signal_wait_events: Vec<_> = sequence_events
15171                .iter()
15172                .copied()
15173                .filter(|event| is_recorded_signal_wait_event(event))
15174                .collect();
15175            let condition_wait_events: Vec<_> = sequence_events
15176                .iter()
15177                .copied()
15178                .filter(|event| is_recorded_condition_wait_event(event))
15179                .collect();
15180            let search_attribute_events: Vec<_> = sequence_events
15181                .iter()
15182                .copied()
15183                .filter(|event| event.event_type == "SearchAttributesUpserted")
15184                .collect();
15185            let side_effect_events: Vec<_> = sequence_events
15186                .iter()
15187                .copied()
15188                .filter(|event| event.event_type == "SideEffectRecorded")
15189                .collect();
15190            let version_marker_events: Vec<_> = sequence_events
15191                .iter()
15192                .copied()
15193                .filter(|event| event.event_type == "VersionMarkerRecorded")
15194                .collect();
15195            let memo_events: Vec<_> = sequence_events
15196                .iter()
15197                .copied()
15198                .filter(|event| event.event_type == "MemoUpserted")
15199                .collect();
15200
15201            let command_kind_count = usize::from(!activity_events.is_empty())
15202                + usize::from(!timer_events.is_empty())
15203                + usize::from(!child_events.is_empty())
15204                + usize::from(!signal_wait_events.is_empty())
15205                + usize::from(!condition_wait_events.is_empty())
15206                + usize::from(!search_attribute_events.is_empty())
15207                + usize::from(!side_effect_events.is_empty())
15208                + usize::from(!version_marker_events.is_empty())
15209                + usize::from(!memo_events.is_empty());
15210            if command_kind_count > 1 {
15211                let actual = [
15212                    (!activity_events.is_empty()).then_some("activity"),
15213                    (!timer_events.is_empty()).then_some("timer"),
15214                    (!child_events.is_empty()).then_some("child workflow"),
15215                    (!signal_wait_events.is_empty()).then_some("signal wait"),
15216                    (!condition_wait_events.is_empty()).then_some("condition wait"),
15217                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
15218                    (!side_effect_events.is_empty()).then_some("side effect"),
15219                    (!version_marker_events.is_empty()).then_some("version marker"),
15220                    (!memo_events.is_empty()).then_some("memo upsert"),
15221                ]
15222                .into_iter()
15223                .flatten()
15224                .collect::<Vec<_>>()
15225                .join(" and ");
15226                return Err(invalid_recorded_history(
15227                    "durable_command_sequence_collision",
15228                    sequence,
15229                    "one durable command kind",
15230                    &actual,
15231                    "one workflow sequence records more than one durable command kind",
15232                ));
15233            }
15234
15235            if !activity_events.is_empty() {
15236                let parallel_group_path =
15237                    recorded_parallel_group_path(&activity_events, sequence)?;
15238                let scheduled_count = activity_events
15239                    .iter()
15240                    .filter(|event| event.event_type == "ActivityScheduled")
15241                    .count();
15242                if scheduled_count > 1 {
15243                    return Err(invalid_recorded_history(
15244                        "duplicate_activity_schedule",
15245                        sequence,
15246                        "at most one ActivityScheduled event",
15247                        "multiple ActivityScheduled events",
15248                        "activity history schedules more than one command at one workflow sequence",
15249                    ));
15250                }
15251                let activity_type = activity_events.iter().find_map(|event| {
15252                    event
15253                        .payload
15254                        .get("activity_type")
15255                        .or_else(|| event.payload.get("activity_name"))
15256                        .and_then(Value::as_str)
15257                        .map(str::to_string)
15258                });
15259                if activity_events.iter().filter_map(|event| {
15260                    event
15261                        .payload
15262                        .get("activity_type")
15263                        .or_else(|| event.payload.get("activity_name"))
15264                        .and_then(Value::as_str)
15265                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
15266                    return Err(invalid_recorded_history(
15267                        "activity_identity_mismatch",
15268                        sequence,
15269                        activity_type.as_deref().unwrap_or("one activity identity"),
15270                        "conflicting activity identities",
15271                        "activity lifecycle events at one workflow sequence disagree on identity",
15272                    ));
15273                }
15274                let terminal: Vec<_> = activity_events
15275                    .iter()
15276                    .copied()
15277                    .filter(|event| {
15278                        matches!(
15279                            event.event_type.as_str(),
15280                            "ActivityCompleted"
15281                                | "ActivityFailed"
15282                                | "ActivityCancelled"
15283                                | "ActivityTimedOut"
15284                        )
15285                    })
15286                    .collect();
15287                let duplicate_delivery = terminal.first().is_some_and(|first| {
15288                    terminal.iter().all(|event| {
15289                        event.event_type == first.event_type && event.payload == first.payload
15290                    })
15291                });
15292                if terminal.len() > 1 && !duplicate_delivery {
15293                    return Err(invalid_recorded_history(
15294                        "duplicate_activity_terminal_event",
15295                        sequence,
15296                        "at most one terminal activity event",
15297                        "multiple terminal activity events",
15298                        "activity history settles one command more than once",
15299                    ));
15300                }
15301                let outcome = terminal
15302                    .first()
15303                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
15304                    .transpose()?;
15305                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
15306                let activity_snapshot = activity_events
15307                    .iter()
15308                    .find(|event| event.event_type == "ActivityScheduled")
15309                    .and_then(|event| event.payload.get("activity"))
15310                    .and_then(Value::as_object);
15311                let options = Some(match activity_snapshot {
15312                    Some(activity) => RecordedActivityOptions {
15313                        task_queue: recorded_optional_string(activity, "queue"),
15314                        execution_mode,
15315                        retry_policy: recorded_activity_retry_snapshot(
15316                            activity.get("retry_policy"),
15317                        ),
15318                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15319                    },
15320                    None => RecordedActivityOptions {
15321                        task_queue: RecordedSnapshotValue::Unknown,
15322                        execution_mode,
15323                        retry_policy: recorded_activity_retry_snapshot(None),
15324                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15325                    },
15326                });
15327                return Ok(RecordedCommand::Activity {
15328                    sequence,
15329                    activity_type,
15330                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
15331                    options,
15332                    outcome,
15333                    parallel_group_path,
15334                });
15335            }
15336
15337            if !child_events.is_empty() {
15338                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
15339                let scheduled: Vec<_> = child_events
15340                    .iter()
15341                    .copied()
15342                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
15343                    .collect();
15344                if scheduled.len() != 1 {
15345                    return Err(invalid_recorded_history(
15346                        "child_workflow_schedule_missing_or_duplicate",
15347                        sequence,
15348                        "one ChildWorkflowScheduled event",
15349                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
15350                        "child workflow replay requires exactly one recorded schedule event",
15351                    ));
15352                }
15353                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
15354                let workflow_type = child_events.iter().find_map(|event| {
15355                    event
15356                        .payload
15357                        .get("child_workflow_type")
15358                        .or_else(|| event.payload.get("workflow_type"))
15359                        .and_then(Value::as_str)
15360                        .filter(|value| !value.is_empty())
15361                        .map(str::to_string)
15362                });
15363                if child_events
15364                    .iter()
15365                    .filter_map(|event| {
15366                        event
15367                            .payload
15368                            .get("child_workflow_type")
15369                            .or_else(|| event.payload.get("workflow_type"))
15370                            .and_then(Value::as_str)
15371                    })
15372                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
15373                {
15374                    return Err(invalid_recorded_history(
15375                        "child_workflow_identity_mismatch",
15376                        sequence,
15377                        workflow_type
15378                            .as_deref()
15379                            .unwrap_or("one child workflow type"),
15380                        "conflicting child workflow types",
15381                        "child workflow lifecycle events at one sequence disagree on type",
15382                    ));
15383                }
15384                let mut outcomes = child_workflow_outcomes(
15385                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
15386                    fallback_codec,
15387                    parent.clone(),
15388                )?;
15389                let terminal_events = child_events
15390                    .iter()
15391                    .copied()
15392                    .filter(|event| event.event_type.starts_with("ChildRun"))
15393                    .collect::<Vec<_>>();
15394                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
15395                    terminal_events.iter().all(|event| {
15396                        event.event_type == first.event_type && event.payload == first.payload
15397                    })
15398                });
15399                if outcomes.len() > 1 && !duplicate_delivery {
15400                    return Err(invalid_recorded_history(
15401                        "duplicate_child_workflow_terminal_event",
15402                        sequence,
15403                        "at most one terminal child event",
15404                        "multiple terminal child events",
15405                        "child workflow history settles one command more than once",
15406                    ));
15407                }
15408                return Ok(RecordedCommand::ChildWorkflow {
15409                    sequence,
15410                    workflow_type,
15411                    policies,
15412                    outcome: outcomes.pop(),
15413                    parallel_group_path,
15414                });
15415            }
15416
15417            if !signal_wait_events.is_empty() {
15418                let opened: Vec<_> = signal_wait_events
15419                    .iter()
15420                    .copied()
15421                    .filter(|event| event.event_type == "SignalWaitOpened")
15422                    .collect();
15423                if opened.len() != 1 {
15424                    return Err(invalid_recorded_history(
15425                        "signal_wait_open_missing_or_duplicate",
15426                        sequence,
15427                        "one SignalWaitOpened event",
15428                        &format!("{} SignalWaitOpened events", opened.len()),
15429                        "signal replay requires exactly one canonical wait-open event",
15430                    ));
15431                }
15432
15433                let applied: Vec<_> = signal_wait_events
15434                    .iter()
15435                    .copied()
15436                    .filter(|event| event.event_type == "SignalApplied")
15437                    .collect();
15438                if applied.len() > 1 {
15439                    return Err(invalid_recorded_history(
15440                        "duplicate_signal_wait_apply",
15441                        sequence,
15442                        "at most one SignalApplied event",
15443                        "multiple SignalApplied events",
15444                        "signal history applies one durable wait more than once",
15445                    ));
15446                }
15447
15448                let signal_names = signal_wait_events
15449                    .iter()
15450                    .map(|event| required_signal_wait_name(event, sequence))
15451                    .collect::<Result<Vec<_>>>()?;
15452                let signal_name = signal_names
15453                    .first()
15454                    .expect("signal wait events are not empty")
15455                    .clone();
15456                if signal_names.iter().any(|candidate| candidate != &signal_name) {
15457                    return Err(invalid_recorded_history(
15458                        "signal_wait_identity_mismatch",
15459                        sequence,
15460                        &signal_name,
15461                        "conflicting signal names",
15462                        "signal wait lifecycle events at one workflow sequence disagree on identity",
15463                    ));
15464                }
15465                let value = applied
15466                    .first()
15467                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
15468                    .transpose()?;
15469                return Ok(RecordedCommand::SignalWait {
15470                    sequence,
15471                    signal_name,
15472                    value,
15473                    parallel_group_path: recorded_parallel_group_path(
15474                        &signal_wait_events,
15475                        sequence,
15476                    )?,
15477                });
15478            }
15479
15480            if !condition_wait_events.is_empty() {
15481                return recorded_condition_wait(
15482                    sequence,
15483                    &condition_wait_events,
15484                    events,
15485                );
15486            }
15487
15488            if !search_attribute_events.is_empty() {
15489                if search_attribute_events.len() != 1 {
15490                    return Err(invalid_recorded_history(
15491                        "duplicate_search_attribute_update",
15492                        sequence,
15493                        "one SearchAttributesUpserted event",
15494                        &format!(
15495                            "{} SearchAttributesUpserted events",
15496                            search_attribute_events.len()
15497                        ),
15498                        "search-attribute history records one workflow command more than once",
15499                    ));
15500                }
15501                let payload = &search_attribute_events[0].payload;
15502                let attributes = payload
15503                    .get("attributes")
15504                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
15505                    .cloned()
15506                    .ok_or_else(|| {
15507                        invalid_recorded_history(
15508                            "search_attribute_update_missing",
15509                            sequence,
15510                            "non-empty attributes object",
15511                            "missing or invalid attributes",
15512                            "search-attribute history is missing its recorded mutation",
15513                        )
15514                    })?;
15515                let attribute_types =
15516                    recorded_search_attribute_types(payload, &attributes, sequence)?;
15517                return Ok(RecordedCommand::SearchAttributes {
15518                    sequence,
15519                    attributes,
15520                    attribute_types,
15521                });
15522            }
15523
15524            if !side_effect_events.is_empty() {
15525                if side_effect_events.len() != 1 {
15526                    return Err(invalid_recorded_history(
15527                        "duplicate_side_effect_record",
15528                        sequence,
15529                        "one SideEffectRecorded event",
15530                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
15531                        "side-effect history records one workflow command more than once",
15532                    ));
15533                }
15534                let event = side_effect_events[0];
15535                let result = event.payload.get("result").ok_or_else(|| {
15536                    invalid_recorded_history(
15537                        "side_effect_result_missing",
15538                        sequence,
15539                        "recorded result payload",
15540                        "missing result",
15541                        "side-effect history is missing its recorded value",
15542                    )
15543                })?;
15544                let has_published_envelope = result.as_str().is_some()
15545                    || result.as_object().is_some_and(|envelope| {
15546                        envelope.get("codec").and_then(Value::as_str).is_some()
15547                            && envelope.get("blob").and_then(Value::as_str).is_some()
15548                    });
15549                if !has_published_envelope {
15550                    return Err(invalid_recorded_history(
15551                        "side_effect_payload_malformed",
15552                        sequence,
15553                        "payload blob or {codec, blob} envelope",
15554                        &result.to_string(),
15555                        "side-effect history result does not use a published payload envelope",
15556                    ));
15557                }
15558                let codec = event
15559                    .payload
15560                    .get("payload_codec")
15561                    .and_then(Value::as_str)
15562                    .unwrap_or(fallback_codec);
15563                let value = decode_wire_avro_value(result, codec).map_err(|error| {
15564                    if error.to_string().contains("unsupported_payload_codec") {
15565                        return error;
15566                    }
15567
15568                    invalid_recorded_history(
15569                        "side_effect_payload_incompatible",
15570                        sequence,
15571                        &format!("valid {codec} payload envelope"),
15572                        &error.to_string(),
15573                        "side-effect history payload cannot be decoded with its recorded codec",
15574                    )
15575                })?;
15576                return Ok(RecordedCommand::SideEffect { sequence, value });
15577            }
15578
15579            if !version_marker_events.is_empty() {
15580                if version_marker_events.len() != 1 {
15581                    return Err(invalid_recorded_history(
15582                        "duplicate_version_marker_record",
15583                        sequence,
15584                        "one VersionMarkerRecorded event",
15585                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
15586                        "version-marker history records one workflow command more than once",
15587                    ));
15588                }
15589                let payload = &version_marker_events[0].payload;
15590                let change_id = payload
15591                    .get("change_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                            "version_marker_field_missing",
15598                            sequence,
15599                            "non-empty change_id",
15600                            "missing or invalid change_id",
15601                            "version-marker history is missing its stable change ID",
15602                        )
15603                    })?;
15604                let version = required_version_i32(payload, "version", sequence)?;
15605                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
15606                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
15607                if min_supported > max_supported || version < min_supported || version > max_supported {
15608                    return Err(invalid_recorded_history(
15609                        "version_marker_history_range_invalid",
15610                        sequence,
15611                        "min_supported <= version <= max_supported",
15612                        &format!("{min_supported} <= {version} <= {max_supported}"),
15613                        "recorded version marker contains an internally incompatible range",
15614                    ));
15615                }
15616                return Ok(RecordedCommand::VersionMarker {
15617                    sequence,
15618                    change_id,
15619                    version,
15620                });
15621            }
15622
15623            if !memo_events.is_empty() {
15624                if memo_events.len() != 1 {
15625                    return Err(invalid_recorded_history(
15626                        "duplicate_memo_upsert_record",
15627                        sequence,
15628                        "one MemoUpserted event",
15629                        &format!("{} MemoUpserted events", memo_events.len()),
15630                        "memo history records one workflow update more than once",
15631                    ));
15632                }
15633                let payload = &memo_events[0].payload;
15634                let entries = payload.get("entries").cloned().ok_or_else(|| {
15635                    invalid_recorded_history(
15636                        "memo_entries_missing",
15637                        sequence,
15638                        "memo entries object",
15639                        "missing entries",
15640                        "MemoUpserted history is missing replay identity entries",
15641                    )
15642                })?;
15643                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
15644                    invalid_recorded_history(
15645                        "memo_entries_invalid",
15646                        sequence,
15647                        "valid canonical memo entries",
15648                        &error.to_string(),
15649                        "MemoUpserted history contains invalid replay identity entries",
15650                    )
15651                })?;
15652                let merged = payload.get("merged").cloned().ok_or_else(|| {
15653                    invalid_recorded_history(
15654                        "memo_merged_projection_missing",
15655                        sequence,
15656                        "merged memo projection",
15657                        "missing merged",
15658                        "MemoUpserted history is missing its merged projection",
15659                    )
15660                })?;
15661                decode_memo_history_map(&merged, false).map_err(|error| {
15662                    invalid_recorded_history(
15663                        "memo_merged_projection_invalid",
15664                        sequence,
15665                        "valid merged memo projection",
15666                        &error.to_string(),
15667                        "MemoUpserted history contains an invalid merged projection",
15668                    )
15669                })?;
15670
15671                return Ok(RecordedCommand::Memo { sequence, entries });
15672            }
15673            let scheduled: Vec<_> = timer_events
15674                .iter()
15675                .copied()
15676                .filter(|event| event.event_type == "TimerScheduled")
15677                .collect();
15678            let fired: Vec<_> = timer_events
15679                .iter()
15680                .copied()
15681                .filter(|event| event.event_type == "TimerFired")
15682                .collect();
15683            if scheduled.len() != 1 {
15684                return Err(invalid_recorded_history(
15685                    "timer_schedule_missing_or_duplicate",
15686                    sequence,
15687                    "one TimerScheduled event",
15688                    &format!("{} TimerScheduled events", scheduled.len()),
15689                    "timer replay requires exactly one recorded schedule event",
15690                ));
15691            }
15692            if fired.len() > 1 {
15693                return Err(invalid_recorded_history(
15694                    "duplicate_timer_fire",
15695                    sequence,
15696                    "at most one TimerFired event",
15697                    "multiple TimerFired events",
15698                    "timer history contains more than one fire event for a workflow sequence",
15699                ));
15700            }
15701
15702            let scheduled = scheduled[0];
15703            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
15704            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
15705            if let Some(fired) = fired.first() {
15706                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
15707                if fired_timer_id != timer_id {
15708                    return Err(invalid_recorded_history(
15709                        "timer_identity_mismatch",
15710                        sequence,
15711                        &timer_id,
15712                        &fired_timer_id,
15713                        "TimerFired does not correspond to the recorded TimerScheduled event",
15714                    ));
15715                }
15716                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
15717                if fired_delay != delay_seconds {
15718                    return Err(invalid_recorded_history(
15719                        "timer_history_delay_mismatch",
15720                        sequence,
15721                        &delay_seconds.to_string(),
15722                        &fired_delay.to_string(),
15723                        "TimerScheduled and TimerFired record different delays",
15724                    ));
15725                }
15726            }
15727
15728            Ok(RecordedCommand::Timer {
15729                sequence,
15730                delay_seconds,
15731                fired: !fired.is_empty(),
15732                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
15733            })
15734        })
15735        .collect::<Result<_>>()?;
15736
15737    let mut marker_sequences = HashMap::new();
15738    for command in &commands {
15739        if let RecordedCommand::VersionMarker {
15740            sequence,
15741            change_id,
15742            ..
15743        } = command
15744        {
15745            if let Some(first_sequence) = marker_sequences.insert(change_id.clone(), *sequence) {
15746                return Err(invalid_recorded_history(
15747                    "duplicate_version_marker",
15748                    *sequence,
15749                    &format!("one marker for change ID {change_id:?}"),
15750                    &format!("markers at sequences {first_sequence} and {sequence}"),
15751                    "workflow history contains duplicate markers for one stable change ID",
15752                ));
15753            }
15754        }
15755    }
15756
15757    Ok(commands)
15758}
15759
15760fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
15761    payload
15762        .get(field)
15763        .and_then(Value::as_i64)
15764        .and_then(|value| i32::try_from(value).ok())
15765        .ok_or_else(|| {
15766            invalid_recorded_history(
15767                "version_marker_field_missing",
15768                sequence,
15769                &format!("integer {field}"),
15770                "missing or out-of-range integer",
15771                "version-marker history is missing a required integer field",
15772            )
15773        })
15774}
15775
15776fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
15777    event
15778        .payload
15779        .get("sequence")
15780        .or_else(|| event.payload.get("workflow_sequence"))
15781        .or_else(|| event.raw.get("sequence"))
15782        .or_else(|| event.raw.get("workflow_sequence"))
15783        .and_then(value_as_u64)
15784}
15785
15786fn is_internal_timer_event(event: &HistoryEvent) -> bool {
15787    matches!(
15788        event
15789            .payload
15790            .get("timer_kind")
15791            .or_else(|| event.raw.get("timer_kind"))
15792            .and_then(Value::as_str),
15793        Some("condition_timeout" | "signal_timeout")
15794    )
15795}
15796
15797fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
15798    matches!(
15799        event.event_type.as_str(),
15800        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15801    )
15802}
15803
15804fn recorded_condition_wait(
15805    sequence: u64,
15806    condition_events: &[&HistoryEvent],
15807    all_events: &[HistoryEvent],
15808) -> Result<RecordedCommand> {
15809    let opened = condition_events
15810        .iter()
15811        .copied()
15812        .filter(|event| event.event_type == "ConditionWaitOpened")
15813        .collect::<Vec<_>>();
15814    if opened.len() != 1 {
15815        return Err(invalid_recorded_history(
15816            "condition_wait_open_missing_or_duplicate",
15817            sequence,
15818            "one ConditionWaitOpened event",
15819            &format!("{} ConditionWaitOpened events", opened.len()),
15820            "condition replay requires exactly one canonical wait-open event",
15821        ));
15822    }
15823    let terminal = condition_events
15824        .iter()
15825        .copied()
15826        .filter(|event| {
15827            matches!(
15828                event.event_type.as_str(),
15829                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15830            )
15831        })
15832        .collect::<Vec<_>>();
15833    if terminal.len() > 1 {
15834        return Err(invalid_recorded_history(
15835            "duplicate_condition_wait_terminal_event",
15836            sequence,
15837            "at most one condition terminal event",
15838            "multiple condition terminal events",
15839            "condition history settles one durable wait more than once",
15840        ));
15841    }
15842
15843    let opened = opened[0];
15844    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
15845    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
15846    for event in condition_events
15847        .iter()
15848        .copied()
15849        .filter(|event| !std::ptr::eq(*event, opened))
15850    {
15851        let event_wait_id = required_condition_wait_id(event, sequence)?;
15852        if event_wait_id != condition_wait_id {
15853            return Err(invalid_recorded_history(
15854                "condition_wait_id_mismatch",
15855                sequence,
15856                &condition_wait_id,
15857                &event_wait_id,
15858                "condition lifecycle events at one sequence disagree on wait identity",
15859            ));
15860        }
15861        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
15862        if event_occurrence_id != occurrence_id {
15863            return Err(invalid_recorded_history(
15864                "condition_wait_occurrence_history_mismatch",
15865                sequence,
15866                &occurrence_id,
15867                &event_occurrence_id,
15868                "condition lifecycle events at one sequence disagree on authored occurrence identity",
15869            ));
15870        }
15871    }
15872
15873    let condition_key = optional_non_empty_history_string(opened, "condition_key");
15874    let predicate_identity = opened
15875        .payload
15876        .get("condition_definition_fingerprint")
15877        .and_then(Value::as_str)
15878        .filter(|value| !value.is_empty())
15879        .map(str::to_string)
15880        .ok_or_else(|| {
15881            invalid_recorded_history(
15882                "condition_wait_predicate_fingerprint_missing",
15883                sequence,
15884                "non-empty condition_definition_fingerprint",
15885                &opened.event_type,
15886                "canonical condition history is missing its predicate identity",
15887            )
15888        })?;
15889    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
15890    for event in condition_events
15891        .iter()
15892        .copied()
15893        .filter(|event| !std::ptr::eq(*event, opened))
15894    {
15895        for (field, opened_value) in [
15896            ("condition_key", condition_key.as_deref()),
15897            (
15898                "condition_definition_fingerprint",
15899                Some(predicate_identity.as_str()),
15900            ),
15901        ] {
15902            if let Some(value) = optional_non_empty_history_string(event, field) {
15903                if opened_value.is_some_and(|opened_value| opened_value != value) {
15904                    return Err(invalid_recorded_history(
15905                        "condition_wait_definition_history_mismatch",
15906                        sequence,
15907                        opened_value.unwrap_or_default(),
15908                        &value,
15909                        "condition lifecycle events disagree on the recorded definition",
15910                    ));
15911                }
15912            }
15913        }
15914        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
15915            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
15916                return Err(invalid_recorded_history(
15917                    "condition_wait_definition_history_mismatch",
15918                    sequence,
15919                    &format!("{}s", timeout_seconds.unwrap_or_default()),
15920                    &format!("{event_timeout}s"),
15921                    "condition lifecycle events disagree on the recorded timeout",
15922                ));
15923            }
15924        }
15925    }
15926
15927    let timeout_timer_events = all_events
15928        .iter()
15929        .filter(|event| {
15930            matches!(
15931                event.event_type.as_str(),
15932                "TimerScheduled" | "TimerCancelled" | "TimerFired"
15933            ) && event.payload.get("timer_kind").and_then(Value::as_str)
15934                == Some("condition_timeout")
15935                && event
15936                    .payload
15937                    .get("condition_wait_id")
15938                    .and_then(Value::as_str)
15939                    == Some(condition_wait_id.as_str())
15940        })
15941        .collect::<Vec<_>>();
15942    let scheduled = timeout_timer_events
15943        .iter()
15944        .copied()
15945        .filter(|event| event.event_type == "TimerScheduled")
15946        .collect::<Vec<_>>();
15947    let fired = timeout_timer_events
15948        .iter()
15949        .copied()
15950        .filter(|event| event.event_type == "TimerFired")
15951        .collect::<Vec<_>>();
15952    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
15953        return Err(invalid_recorded_history(
15954            "condition_wait_timeout_history_invalid",
15955            sequence,
15956            "one timeout schedule and at most one fire",
15957            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
15958            "condition timeout history has a missing or duplicate lifecycle event",
15959        ));
15960    }
15961    if let Some(scheduled) = scheduled.first() {
15962        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
15963        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
15964        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
15965            return Err(invalid_recorded_history(
15966                "condition_wait_timeout_delay_mismatch",
15967                sequence,
15968                &format!("{}s", timeout_seconds.unwrap_or_default()),
15969                &format!("{delay_seconds}s"),
15970                "condition timeout timer differs from the wait definition",
15971            ));
15972        }
15973        if let Some(fired) = fired.first() {
15974            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
15975            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
15976            if fired_timer_id != timer_id || fired_delay != delay_seconds {
15977                return Err(invalid_recorded_history(
15978                    "condition_wait_timeout_identity_mismatch",
15979                    sequence,
15980                    &format!("{timer_id}:{delay_seconds}s"),
15981                    &format!("{fired_timer_id}:{fired_delay}s"),
15982                    "condition timeout fire does not match its durable schedule",
15983                ));
15984            }
15985        }
15986    }
15987
15988    let result = terminal.first().map(|event| {
15989        if event.event_type == "ConditionWaitTimedOut" {
15990            ConditionWaitResult::TimedOut
15991        } else {
15992            ConditionWaitResult::Satisfied
15993        }
15994    });
15995    let result = if !fired.is_empty() {
15996        if result == Some(ConditionWaitResult::Satisfied) {
15997            return Err(invalid_recorded_history(
15998                "condition_wait_terminal_conflict",
15999                sequence,
16000                "one satisfied or timed-out outcome",
16001                "satisfied event and fired timeout",
16002                "condition history records conflicting terminal outcomes",
16003            ));
16004        }
16005        Some(ConditionWaitResult::TimedOut)
16006    } else {
16007        result
16008    };
16009
16010    Ok(RecordedCommand::ConditionWait {
16011        sequence,
16012        occurrence_id,
16013        condition_key,
16014        predicate_identity,
16015        timeout_seconds,
16016        result,
16017        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16018    })
16019}
16020
16021fn recorded_condition_group_path(
16022    condition_events: &[&HistoryEvent],
16023    all_events: &[HistoryEvent],
16024    sequence: u64,
16025) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16026    let opened = condition_events
16027        .iter()
16028        .copied()
16029        .find(|event| event.event_type == "ConditionWaitOpened")
16030        .expect("canonical condition opener is validated first");
16031    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16032    let previous_events = all_events
16033        .iter()
16034        .take_while(|event| !std::ptr::eq(*event, opened))
16035        .collect::<Vec<_>>();
16036    let originals = previous_events
16037        .iter()
16038        .copied()
16039        .filter(|event| event.event_type == "ConditionWaitOpened")
16040        .filter(|event| {
16041            event
16042                .payload
16043                .get("condition_wait_occurrence_id")
16044                .and_then(Value::as_str)
16045                == Some(occurrence.as_str())
16046        })
16047        .collect::<Vec<_>>();
16048    let Some(original) = originals.first().copied() else {
16049        return recorded_parallel_group_path(condition_events, sequence);
16050    };
16051    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16052    if authored_sequence == sequence {
16053        return recorded_parallel_group_path(condition_events, sequence);
16054    }
16055    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16056    if original_path.is_none() {
16057        return recorded_parallel_group_path(condition_events, sequence);
16058    }
16059    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16060    let identity_matches = [
16061        "condition_key",
16062        "condition_definition_fingerprint",
16063        "timeout_seconds",
16064    ]
16065    .iter()
16066    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16067    let previous = originals
16068        .iter()
16069        .copied()
16070        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16071        .max_by_key(|event| durable_event_sequence(event));
16072    let previously_satisfied = previous.is_some_and(|previous| {
16073        previous_events.iter().any(|event| {
16074            event.event_type == "ConditionWaitSatisfied"
16075                && event.payload.get("condition_wait_id")
16076                    == previous.payload.get("condition_wait_id")
16077                && event.payload.get("condition_wait_occurrence_id")
16078                    == previous.payload.get("condition_wait_occurrence_id")
16079                && durable_event_sequence(event) == durable_event_sequence(previous)
16080        })
16081    });
16082    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16083        return Err(invalid_recorded_history(
16084            "condition_wait_group_reopen_mismatch",
16085            sequence,
16086            "same authored condition and group path after a satisfied physical wait",
16087            &opened.payload.to_string(),
16088            "grouped condition reopen has no matching recorded predecessor",
16089        ));
16090    }
16091    Ok(reopened_path)
16092}
16093
16094fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16095    event
16096        .payload
16097        .get("condition_wait_occurrence_id")
16098        .and_then(Value::as_str)
16099        .filter(|value| !value.is_empty())
16100        .map(str::to_string)
16101        .ok_or_else(|| {
16102            invalid_recorded_history(
16103                "condition_wait_occurrence_id_missing",
16104                sequence,
16105                "non-empty condition_wait_occurrence_id",
16106                &event.event_type,
16107                "condition history is missing authored occurrence identity",
16108            )
16109        })
16110}
16111
16112fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16113    event
16114        .payload
16115        .get("condition_wait_id")
16116        .and_then(Value::as_str)
16117        .filter(|value| !value.is_empty())
16118        .map(str::to_string)
16119        .ok_or_else(|| {
16120            invalid_recorded_history(
16121                "condition_wait_id_missing",
16122                sequence,
16123                "non-empty condition_wait_id",
16124                &event.event_type,
16125                "canonical condition history is missing its durable wait identity",
16126            )
16127        })
16128}
16129
16130fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16131    event
16132        .payload
16133        .get(field)
16134        .and_then(Value::as_str)
16135        .filter(|value| !value.is_empty())
16136        .map(str::to_string)
16137}
16138
16139fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16140    match event.payload.get(field) {
16141        None | Some(Value::Null) => Ok(None),
16142        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16143            invalid_recorded_history(
16144                "condition_wait_definition_invalid",
16145                sequence,
16146                &format!("non-negative integer {field}"),
16147                &value.to_string(),
16148                "condition history contains an invalid numeric definition field",
16149            )
16150        }),
16151    }
16152}
16153
16154fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16155    event
16156        .payload
16157        .get("signal_name")
16158        .or_else(|| event.raw.get("signal_name"))
16159        .and_then(Value::as_str)
16160        .filter(|value| !value.is_empty())
16161        .map(str::to_string)
16162        .ok_or_else(|| {
16163            invalid_recorded_history(
16164                "signal_wait_name_missing",
16165                sequence,
16166                "non-empty signal_name",
16167                &event.event_type,
16168                "canonical signal-wait history is missing its signal identity",
16169            )
16170        })
16171}
16172
16173fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16174    matches!(
16175        event.event_type.as_str(),
16176        "SignalWaitOpened" | "SignalApplied"
16177    )
16178}
16179
16180fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
16181    event
16182        .payload
16183        .get(field)
16184        .and_then(Value::as_str)
16185        .filter(|value| !value.is_empty())
16186        .map(str::to_string)
16187        .ok_or_else(|| {
16188            invalid_recorded_history(
16189                "timer_history_field_missing",
16190                sequence,
16191                field,
16192                &event.event_type,
16193                "timer history is missing a required identity field",
16194            )
16195        })
16196}
16197
16198fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
16199    event
16200        .payload
16201        .get(field)
16202        .and_then(value_as_u64)
16203        .ok_or_else(|| {
16204            invalid_recorded_history(
16205                "timer_history_field_missing",
16206                sequence,
16207                field,
16208                &event.event_type,
16209                "timer history is missing a required numeric field",
16210            )
16211        })
16212}
16213
16214fn recorded_search_attribute_types(
16215    payload: &Value,
16216    attributes: &Value,
16217    sequence: u64,
16218) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
16219    let Some(raw_types) = payload.get("attribute_types") else {
16220        // This is the explicit compatibility rule for histories recorded
16221        // before typed identity was persisted. Values still constrain replay;
16222        // the unknown type snapshot does not assert a typed match.
16223        return Ok(RecordedSnapshotValue::Unknown);
16224    };
16225    let Some(raw_types) = raw_types.as_object() else {
16226        return Err(invalid_recorded_history(
16227            "search_attribute_types_malformed",
16228            sequence,
16229            "canonical attribute type map",
16230            &raw_types.to_string(),
16231            "search-attribute history contains malformed type identity",
16232        ));
16233    };
16234    let attribute_keys = attributes
16235        .as_object()
16236        .expect("recorded search attributes were validated as an object");
16237    let mut types = BTreeMap::new();
16238    for (key, value) in raw_types {
16239        let Some(attribute_type) = value.as_str() else {
16240            return Err(invalid_recorded_history(
16241                "search_attribute_types_malformed",
16242                sequence,
16243                "canonical string type name",
16244                &value.to_string(),
16245                "search-attribute history contains a non-string type identity",
16246            ));
16247        };
16248        if !attribute_keys.contains_key(key)
16249            || !matches!(
16250                attribute_type,
16251                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
16252            )
16253        {
16254            return Err(invalid_recorded_history(
16255                "search_attribute_types_malformed",
16256                sequence,
16257                "canonical types for keys present in attributes",
16258                &format!("{key}:{attribute_type}"),
16259                "search-attribute history contains unsupported or orphaned type identity",
16260            ));
16261        }
16262        types.insert(key.clone(), attribute_type.to_string());
16263    }
16264    Ok(RecordedSnapshotValue::Known(types))
16265}
16266
16267fn invalid_recorded_history(
16268    reason: &str,
16269    sequence: u64,
16270    expected: &str,
16271    actual: &str,
16272    message: &str,
16273) -> Error {
16274    Error::NonDeterministicReplay(ReplayFailure::new(
16275        reason,
16276        Some(sequence),
16277        Some(expected.to_string()),
16278        Some(actual.to_string()),
16279        message,
16280    ))
16281}
16282
16283type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
16284
16285fn activity_outcome(
16286    event: &HistoryEvent,
16287    fallback_codec: &str,
16288    recorded_activity_type: Option<String>,
16289) -> Result<ActivityOutcome> {
16290    if event.event_type == "ActivityCompleted" {
16291        let codec = event
16292            .payload
16293            .get("payload_codec")
16294            .and_then(Value::as_str)
16295            .unwrap_or(fallback_codec);
16296        return Ok(Ok(decode_wire_avro_value(
16297            event.payload.get("result").unwrap_or(&Value::Null),
16298            codec,
16299        )?));
16300    }
16301
16302    let payload = &event.payload;
16303    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
16304        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
16305        "ActivityCancelled" => (
16306            ActivityFailureKind::Cancelled,
16307            "cancelled",
16308            "activity was cancelled",
16309        ),
16310        "ActivityTimedOut" => (
16311            ActivityFailureKind::TimedOut,
16312            "timeout",
16313            "activity timed out",
16314        ),
16315        _ => unreachable!("activity_outcome is called only for terminal activity events"),
16316    };
16317    let exception = payload
16318        .get("exception")
16319        .filter(|value| !value.is_null())
16320        .cloned();
16321    let failure_category = payload_string(payload, "failure_category");
16322    let timeout_kind = payload_string(payload, "timeout_kind");
16323    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
16324        ActivityFailureKind::Failed => failure_category
16325            .clone()
16326            .unwrap_or_else(|| fallback_reason.to_string()),
16327        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
16328        ActivityFailureKind::TimedOut => timeout_kind
16329            .clone()
16330            .unwrap_or_else(|| fallback_reason.to_string()),
16331    });
16332    let message = payload_string(payload, "message")
16333        .or_else(|| {
16334            exception
16335                .as_ref()
16336                .and_then(|value| payload_string(value, "message"))
16337        })
16338        .unwrap_or_else(|| fallback_message.to_string());
16339
16340    Ok(Err(ActivityFailure {
16341        kind,
16342        reason,
16343        message,
16344        activity_execution_id: payload_string(payload, "activity_execution_id"),
16345        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
16346        activity_type: payload_string(payload, "activity_type")
16347            .or_else(|| payload_string(payload, "activity_name"))
16348            .or(recorded_activity_type),
16349        activity_class: payload_string(payload, "activity_class"),
16350        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
16351        failure_id: payload_string(payload, "failure_id"),
16352        failure_category,
16353        timeout_kind,
16354        non_retryable: payload
16355            .get("non_retryable")
16356            .and_then(Value::as_bool)
16357            .unwrap_or(false),
16358        exception_type: payload_string(payload, "exception_type").or_else(|| {
16359            exception
16360                .as_ref()
16361                .and_then(|value| payload_string(value, "type"))
16362        }),
16363        exception_class: payload_string(payload, "exception_class").or_else(|| {
16364            exception
16365                .as_ref()
16366                .and_then(|value| payload_string(value, "class"))
16367        }),
16368        code: payload
16369            .get("code")
16370            .filter(|value| !value.is_null())
16371            .cloned(),
16372        exception,
16373    }))
16374}
16375
16376type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
16377
16378fn child_workflow_outcomes(
16379    events: &[HistoryEvent],
16380    fallback_codec: &str,
16381    parent: WorkflowIdentity,
16382) -> Result<Vec<ChildWorkflowOutcome>> {
16383    let mut outcomes = Vec::new();
16384
16385    for event in events {
16386        let kind = match event.event_type.as_str() {
16387            "ChildRunCompleted" => None,
16388            "ChildRunFailed" => Some((
16389                ChildWorkflowFailureKind::Failed,
16390                "child_workflow",
16391                "child workflow failed",
16392            )),
16393            "ChildRunCancelled" => Some((
16394                ChildWorkflowFailureKind::Cancelled,
16395                "cancelled",
16396                "child workflow was cancelled",
16397            )),
16398            "ChildRunTerminated" => Some((
16399                ChildWorkflowFailureKind::Terminated,
16400                "terminated",
16401                "child workflow was terminated",
16402            )),
16403            _ => continue,
16404        };
16405        let payload = &event.payload;
16406        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
16407        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
16408        let child_workflow_type = payload_string(payload, "child_workflow_type");
16409
16410        if let Some((kind, reason, fallback_message)) = kind {
16411            let exception = payload
16412                .get("exception")
16413                .filter(|value| !value.is_null())
16414                .cloned();
16415            let message = payload_string(payload, "message")
16416                .or_else(|| {
16417                    exception
16418                        .as_ref()
16419                        .and_then(|value| payload_string(value, "message"))
16420                })
16421                .unwrap_or_else(|| fallback_message.to_string());
16422            let exception_type = payload_string(payload, "exception_type").or_else(|| {
16423                exception
16424                    .as_ref()
16425                    .and_then(|value| payload_string(value, "type"))
16426            });
16427            let exception_class = payload_string(payload, "exception_class").or_else(|| {
16428                exception
16429                    .as_ref()
16430                    .and_then(|value| payload_string(value, "class"))
16431            });
16432            outcomes.push(Err(ChildWorkflowFailure {
16433                kind,
16434                reason: reason.to_string(),
16435                message,
16436                parent_workflow_id: parent.workflow_id.clone(),
16437                parent_workflow_run_id: parent.run_id.clone(),
16438                child_workflow_id,
16439                child_workflow_run_id,
16440                child_workflow_type,
16441                failure_id: payload_string(payload, "failure_id"),
16442                failure_category: payload_string(payload, "failure_category"),
16443                exception_type,
16444                exception_class,
16445                non_retryable: payload
16446                    .get("non_retryable")
16447                    .and_then(Value::as_bool)
16448                    .unwrap_or(false),
16449                code: payload
16450                    .get("code")
16451                    .filter(|value| !value.is_null())
16452                    .cloned(),
16453                exception,
16454            }));
16455            continue;
16456        }
16457
16458        let codec = payload
16459            .get("payload_codec")
16460            .and_then(Value::as_str)
16461            .unwrap_or(fallback_codec);
16462        let result = payload
16463            .get("result")
16464            .or_else(|| payload.get("output"))
16465            .unwrap_or(&Value::Null);
16466        outcomes.push(Ok(ChildWorkflowAvroResult {
16467            parent: parent.clone(),
16468            child: WorkflowIdentity {
16469                workflow_id: child_workflow_id,
16470                run_id: child_workflow_run_id,
16471            },
16472            child_workflow_type,
16473            result: decode_wire_avro_value(result, codec)?,
16474        }));
16475    }
16476
16477    Ok(outcomes)
16478}
16479
16480fn payload_string(payload: &Value, key: &str) -> Option<String> {
16481    payload
16482        .get(key)
16483        .and_then(Value::as_str)
16484        .filter(|value| !value.is_empty())
16485        .map(str::to_string)
16486}
16487
16488fn recorded_activity_failure_boundary(
16489    ctx: &WorkflowContext,
16490    error: &Error,
16491) -> Option<(u64, String)> {
16492    let Error::ActivityFailed(failure) = error else {
16493        return None;
16494    };
16495    if failure.kind != ActivityFailureKind::Failed {
16496        return None;
16497    }
16498    let activity_execution_id = failure
16499        .activity_execution_id
16500        .as_deref()
16501        .filter(|value| !value.is_empty())?;
16502    let state = ctx.state.lock().ok()?;
16503    let mut matches = state.recorded_commands.iter().filter_map(|command| {
16504        let RecordedCommand::Activity {
16505            sequence,
16506            outcome: Some(Err(recorded_failure)),
16507            ..
16508        } = command
16509        else {
16510            return None;
16511        };
16512        (*sequence > 0 && recorded_failure == failure)
16513            .then_some((*sequence, activity_execution_id.to_string()))
16514    });
16515    let boundary = matches.next()?;
16516    matches.next().is_none().then_some(boundary)
16517}
16518
16519fn workflow_failure_command(
16520    error: &Error,
16521    failed_activity_boundary: Option<(u64, String)>,
16522) -> Value {
16523    let (exception_type, exception_class, properties) = match error {
16524        Error::ActivityFailed(failure) => (
16525            match failure.kind {
16526                ActivityFailureKind::Failed => "ActivityFailed",
16527                ActivityFailureKind::Cancelled => "ActivityCancelled",
16528                ActivityFailureKind::TimedOut => "ActivityTimedOut",
16529            },
16530            "durable_workflow::ActivityFailure",
16531            json!({
16532                "reason": failure.reason,
16533                "activity_execution_id": failure.activity_execution_id,
16534                "activity_attempt_id": failure.activity_attempt_id,
16535                "activity_type": failure.activity_type,
16536                "activity_class": failure.activity_class,
16537                "attempt_number": failure.attempt_number,
16538                "failure_id": failure.failure_id,
16539                "failure_category": failure.failure_category,
16540                "timeout_kind": failure.timeout_kind,
16541                "activity_non_retryable": failure.non_retryable,
16542                "activity_exception_type": failure.exception_type,
16543                "activity_exception_class": failure.exception_class,
16544                "activity_code": failure.code,
16545                "activity_exception": failure.exception,
16546            }),
16547        ),
16548        Error::ChildWorkflowFailed(failure) => (
16549            match failure.kind {
16550                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16551                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16552                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16553            },
16554            "durable_workflow::ChildWorkflowFailure",
16555            json!({
16556                "reason": failure.reason,
16557                "parent_workflow_id": failure.parent_workflow_id,
16558                "parent_workflow_run_id": failure.parent_workflow_run_id,
16559                "child_workflow_id": failure.child_workflow_id,
16560                "child_workflow_run_id": failure.child_workflow_run_id,
16561                "child_workflow_type": failure.child_workflow_type,
16562                "failure_id": failure.failure_id,
16563                "failure_category": failure.failure_category,
16564                "child_exception_type": failure.exception_type,
16565                "child_exception_class": failure.exception_class,
16566                "child_non_retryable": failure.non_retryable,
16567                "child_code": failure.code,
16568                "child_exception": failure.exception,
16569            }),
16570        ),
16571        Error::ParallelFailed(failure) => (
16572            "ParallelFailed",
16573            "durable_workflow::ParallelFailure",
16574            json!({
16575                "parallel_group_id": failure.group_id,
16576                "parallel_member_path": failure.member_path,
16577                "parallel_group_path": failure.group_path,
16578                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
16579                "cause_type": workflow_error_type(&failure.cause),
16580                "cause_message": failure.cause.to_string(),
16581            }),
16582        ),
16583        Error::SagaCompensationFailed(failure) => (
16584            "SagaCompensationFailed",
16585            "durable_workflow::SagaCompensationFailure",
16586            json!({
16587                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
16588                "initiating_failure_message": failure.initiating_failure.to_string(),
16589                "compensation_activity_type": failure.compensation_activity_type,
16590                "compensation_registration_order": failure.compensation_registration_order,
16591                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
16592                "compensation_failure_message": failure.compensation_failure.to_string(),
16593            }),
16594        ),
16595        Error::WorkflowCancellationRequested(_) => (
16596            "WorkflowCancellationRequested",
16597            "durable_workflow::WorkflowCancellationRequested",
16598            json!({"reason": "cancelled"}),
16599        ),
16600        Error::CooperativeCancellationRequested(cancellation) => (
16601            "WorkflowCancellationRequested",
16602            "durable_workflow::CooperativeCancellationRequested",
16603            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
16604                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
16605        ),
16606        Error::CancellationScopeRequested(cancellation) => (
16607            "WorkflowCancellationRequested",
16608            "durable_workflow::CancellationScopeRequested",
16609            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
16610                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
16611                "cancellation":cancellation.context.to_value()}),
16612        ),
16613        Error::NonDeterministicReplay(_) => (
16614            "NonDeterministicReplay",
16615            "durable_workflow::Error",
16616            Value::Null,
16617        ),
16618        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
16619    };
16620    let non_retryable = match error {
16621        Error::ActivityFailed(failure) => failure.non_retryable,
16622        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16623        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16624        Error::SagaCompensationFailed(failure) => {
16625            workflow_error_non_retryable(&failure.compensation_failure)
16626        }
16627        Error::WorkflowCancellationRequested(_)
16628        | Error::CooperativeCancellationRequested(_)
16629        | Error::CancellationScopeRequested(_) => true,
16630        Error::NonDeterministicReplay(_) => true,
16631        _ => false,
16632    };
16633
16634    let mut command = json!({
16635        "type": "fail_workflow",
16636        "message": error.to_string(),
16637        "exception_type": exception_type,
16638        "exception_class": exception_class,
16639        "non_retryable": non_retryable,
16640        "exception": {
16641            "type": exception_type,
16642            "class": exception_class,
16643            "message": error.to_string(),
16644            "properties": properties,
16645        }
16646    });
16647
16648    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
16649        command["failed_step_sequence"] = json!(sequence);
16650        command["failed_activity_execution_id"] = json!(activity_execution_id);
16651    }
16652
16653    command
16654}
16655
16656fn workflow_error_type(error: &Error) -> &'static str {
16657    match error {
16658        Error::ActivityFailed(failure) => match failure.kind {
16659            ActivityFailureKind::Failed => "ActivityFailed",
16660            ActivityFailureKind::Cancelled => "ActivityCancelled",
16661            ActivityFailureKind::TimedOut => "ActivityTimedOut",
16662        },
16663        Error::ChildWorkflowFailed(failure) => match failure.kind {
16664            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16665            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16666            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16667        },
16668        Error::ParallelFailed(_) => "ParallelFailed",
16669        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
16670        Error::WorkflowCancellationRequested(_)
16671        | Error::CooperativeCancellationRequested(_)
16672        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
16673        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
16674        _ => "RustWorkflowError",
16675    }
16676}
16677
16678fn workflow_error_non_retryable(error: &Error) -> bool {
16679    match error {
16680        Error::ActivityFailed(failure) => failure.non_retryable,
16681        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16682        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16683        Error::SagaCompensationFailed(failure) => {
16684            workflow_error_non_retryable(&failure.compensation_failure)
16685        }
16686        Error::WorkflowCancellationRequested(_)
16687        | Error::CooperativeCancellationRequested(_)
16688        | Error::CancellationScopeRequested(_)
16689        | Error::NonDeterministicReplay(_) => true,
16690        _ => false,
16691    }
16692}
16693
16694fn workflow_task_integrity_error(error: &Error) -> bool {
16695    matches!(
16696        error,
16697        Error::NonDeterministicReplay(_)
16698            | Error::Protocol(_)
16699            | Error::CancellationScopeExecutionUnavailable
16700            | Error::MissingWorkflowCommandIdentity
16701            | Error::WorkflowStatePoisoned
16702    )
16703}
16704
16705fn decode_signal_event_arguments(
16706    event: &HistoryEvent,
16707    fallback_codec: &str,
16708) -> Result<Vec<AvroValue>> {
16709    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16710    validate_payload_codec(codec)?;
16711    let raw = signal_history_payload(&event.payload);
16712    let decoded = match raw.filter(|value| !value.is_null()) {
16713        Some(value) => decode_wire_avro_value(value, codec)?,
16714        None => AvroValue::Array(Vec::new()),
16715    };
16716    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16717        unreachable!("normalize_avro_arguments always returns an array");
16718    };
16719    Ok(arguments)
16720}
16721
16722fn decode_update_event_arguments(
16723    event: &HistoryEvent,
16724    fallback_codec: &str,
16725) -> Result<Vec<AvroValue>> {
16726    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16727    validate_payload_codec(codec)?;
16728    let decoded = match event
16729        .payload
16730        .get("arguments")
16731        .filter(|value| !value.is_null())
16732    {
16733        Some(value) => decode_wire_avro_value(value, codec)?,
16734        None => AvroValue::Array(Vec::new()),
16735    };
16736    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16737        unreachable!("normalize_avro_arguments always returns an array");
16738    };
16739    Ok(arguments)
16740}
16741
16742fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16743    let Some(export_events) = task
16744        .history_export
16745        .as_ref()
16746        .and_then(|export| export.get("history_events"))
16747        .and_then(Value::as_array)
16748    else {
16749        return Ok(());
16750    };
16751
16752    if export_events.len() > task.history_events.len() {
16753        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
16754    }
16755
16756    Ok(())
16757}
16758
16759fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16760    let Some(export) = task.history_export.as_ref() else {
16761        return Ok(());
16762    };
16763    let signals = export
16764        .get("signals")
16765        .and_then(Value::as_array)
16766        .cloned()
16767        .unwrap_or_default();
16768    let activities = export
16769        .get("activities")
16770        .and_then(Value::as_array)
16771        .cloned()
16772        .unwrap_or_default();
16773    let export_codec = export
16774        .get("payloads")
16775        .and_then(|payloads| payloads.get("codec"))
16776        .and_then(Value::as_str)
16777        .unwrap_or(&task.payload_codec)
16778        .to_string();
16779    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
16780
16781    for event in &mut task.history_events {
16782        if event.event_type == "ActivityCompleted" {
16783            let sequence = event
16784                .payload
16785                .get("sequence")
16786                .or_else(|| event.payload.get("workflow_sequence"))
16787                .and_then(value_as_u64);
16788            let Some(activity) = sequence.and_then(|sequence| {
16789                activities.iter().find(|activity| {
16790                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
16791                })
16792            }) else {
16793                continue;
16794            };
16795            let Some(payload) = event.payload.as_object_mut() else {
16796                continue;
16797            };
16798            if missing_payload(payload.get("result")) {
16799                if let Some(result) = activity
16800                    .get("result")
16801                    .filter(|value| !missing_payload(Some(value)))
16802                {
16803                    payload.insert("result".to_string(), result.clone());
16804                }
16805            }
16806            for field in ["payload_codec", "activity_type"] {
16807                if payload
16808                    .get(field)
16809                    .and_then(Value::as_str)
16810                    .unwrap_or_default()
16811                    .is_empty()
16812                {
16813                    if let Some(value) = activity.get(field) {
16814                        payload.insert(field.to_string(), value.clone());
16815                    }
16816                }
16817            }
16818            continue;
16819        }
16820
16821        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
16822            continue;
16823        }
16824        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
16825        let command_id = event
16826            .payload
16827            .get("workflow_command_id")
16828            .or_else(|| event.raw.get("workflow_command_id"))
16829            .and_then(Value::as_str);
16830        let signal_name = event
16831            .payload
16832            .get("signal_name")
16833            .and_then(Value::as_str)
16834            .unwrap_or_default()
16835            .to_string();
16836        let matched = signals
16837            .iter()
16838            .find(|signal| {
16839                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
16840            })
16841            .or_else(|| {
16842                signals.iter().find(|signal| {
16843                    command_id.is_some()
16844                        && signal.get("command_id").and_then(Value::as_str) == command_id
16845                })
16846            })
16847            .or_else(|| {
16848                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
16849                let signal = signals
16850                    .iter()
16851                    .filter(|signal| {
16852                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
16853                    })
16854                    .nth(*offset);
16855                if signal.is_some() {
16856                    *offset += 1;
16857                }
16858                signal
16859            });
16860        let Some(signal) = matched else {
16861            continue;
16862        };
16863        let signal_codec = signal
16864            .get("payload_codec")
16865            .and_then(Value::as_str)
16866            .unwrap_or(&export_codec);
16867        let Some(payload) = event.payload.as_object_mut() else {
16868            continue;
16869        };
16870        if missing_payload(payload.get("arguments")) {
16871            if let Some(arguments) = signal
16872                .get("arguments")
16873                .filter(|value| !missing_payload(Some(value)))
16874            {
16875                let envelope = match arguments {
16876                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
16877                    other => other.clone(),
16878                };
16879                payload.insert("arguments".to_string(), envelope);
16880            }
16881        }
16882        if payload
16883            .get("payload_codec")
16884            .and_then(Value::as_str)
16885            .unwrap_or_default()
16886            .is_empty()
16887        {
16888            payload.insert("payload_codec".to_string(), json!(signal_codec));
16889        }
16890    }
16891
16892    Ok(())
16893}
16894
16895fn missing_payload(value: Option<&Value>) -> bool {
16896    match value {
16897        None | Some(Value::Null) => true,
16898        Some(Value::String(value)) => value.is_empty(),
16899        Some(_) => false,
16900    }
16901}
16902
16903fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
16904    let export_signals = task
16905        .history_export
16906        .as_ref()
16907        .and_then(|export| export.get("signals"))
16908        .and_then(Value::as_array)
16909        .cloned()
16910        .unwrap_or_default();
16911    let export_codec = task
16912        .history_export
16913        .as_ref()
16914        .and_then(|export| export.get("payloads"))
16915        .and_then(|payloads| payloads.get("codec"))
16916        .and_then(Value::as_str)
16917        .unwrap_or(&task.payload_codec);
16918    let mut name_offsets: HashMap<String, usize> = HashMap::new();
16919    let mut signals = Vec::new();
16920
16921    for event in &task.history_events {
16922        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
16923            continue;
16924        }
16925
16926        let name = event
16927            .payload
16928            .get("signal_name")
16929            .and_then(Value::as_str)
16930            .unwrap_or_default();
16931        if name.is_empty() {
16932            continue;
16933        }
16934        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
16935        let command_id = event
16936            .payload
16937            .get("workflow_command_id")
16938            .or_else(|| event.raw.get("workflow_command_id"))
16939            .and_then(Value::as_str);
16940        let matched_export = export_signals
16941            .iter()
16942            .find(|candidate| {
16943                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
16944            })
16945            .or_else(|| {
16946                export_signals.iter().find(|candidate| {
16947                    command_id.is_some()
16948                        && candidate.get("command_id").and_then(Value::as_str) == command_id
16949                })
16950            })
16951            .or_else(|| {
16952                let offset = name_offsets.entry(name.to_string()).or_default();
16953                let candidate = export_signals
16954                    .iter()
16955                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
16956                    .nth(*offset);
16957                if candidate.is_some() {
16958                    *offset += 1;
16959                }
16960                candidate
16961            });
16962        let codec = event
16963            .payload
16964            .get("payload_codec")
16965            .and_then(Value::as_str)
16966            .or_else(|| {
16967                matched_export
16968                    .and_then(|signal| signal.get("payload_codec"))
16969                    .and_then(Value::as_str)
16970            })
16971            .unwrap_or(export_codec);
16972        let raw_arguments = signal_history_payload(&event.payload)
16973            .filter(|value| !value.is_null())
16974            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
16975        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
16976        let workflow_sequence = event
16977            .payload
16978            .get("workflow_sequence")
16979            .and_then(value_as_u64)
16980            .or_else(|| {
16981                matched_export
16982                    .and_then(|signal| signal.get("workflow_sequence"))
16983                    .and_then(value_as_u64)
16984            });
16985
16986        signals.push(QuerySignal {
16987            id: signal_id.map(str::to_string).or_else(|| {
16988                matched_export
16989                    .and_then(|signal| signal.get("id"))
16990                    .and_then(Value::as_str)
16991                    .map(str::to_string)
16992            }),
16993            name: name.to_string(),
16994            arguments,
16995            avro_arguments,
16996            workflow_sequence,
16997        });
16998    }
16999
17000    if signals.is_empty() {
17001        for signal in export_signals {
17002            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17003                continue;
17004            }
17005            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17006                continue;
17007            };
17008            let codec = signal
17009                .get("payload_codec")
17010                .and_then(Value::as_str)
17011                .unwrap_or(export_codec);
17012            let (arguments, avro_arguments) =
17013                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17014            signals.push(QuerySignal {
17015                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17016                name: name.to_string(),
17017                arguments,
17018                avro_arguments,
17019                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17020            });
17021        }
17022        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17023    }
17024
17025    Ok(signals)
17026}
17027
17028fn decode_query_signal_arguments(
17029    raw: Option<&Value>,
17030    codec: &str,
17031) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17032    validate_payload_codec(codec)?;
17033    let decoded = match raw.filter(|value| !value.is_null()) {
17034        Some(value) => decode_wire_avro_value(value, codec)?,
17035        None => AvroValue::Array(Vec::new()),
17036    };
17037    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17038        unreachable!("normalize_avro_arguments always returns an array");
17039    };
17040    let arguments = avro_arguments
17041        .iter()
17042        .cloned()
17043        .map(AvroValue::into_json)
17044        .collect::<Result<Vec<_>>>()?;
17045    Ok((arguments, avro_arguments))
17046}
17047
17048fn value_as_u64(value: &Value) -> Option<u64> {
17049    value
17050        .as_u64()
17051        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17052}
17053
17054#[cfg(test)]
17055mod tests {
17056    use super::*;
17057    mod activity_cancellation_policies;
17058    mod cancellation_scope_admission;
17059    mod cancellation_scope_authoring;
17060    mod cancellation_scope_history;
17061    mod cancellation_scope_opening;
17062    mod cancellation_scope_replay;
17063    mod child_workflow_policies;
17064    mod cooperative_cancellation;
17065    mod local_activity;
17066    mod runtime_payloads;
17067    mod runtime_uploads;
17068    mod worker_session;
17069    use std::{
17070        fs,
17071        io::{Read, Write},
17072        net::{SocketAddr, TcpListener, TcpStream},
17073        process::Command as ProcessCommand,
17074        sync::atomic::AtomicUsize,
17075        thread,
17076    };
17077
17078    #[derive(Clone, Copy, Debug)]
17079    enum InvalidTaskPayloadCodec {
17080        Missing,
17081        Null,
17082        NonString,
17083    }
17084
17085    impl InvalidTaskPayloadCodec {
17086        fn label(self) -> &'static str {
17087            match self {
17088                Self::Missing => "missing",
17089                Self::Null => "null",
17090                Self::NonString => "non-string",
17091            }
17092        }
17093
17094        fn apply(self, task: &mut Value) {
17095            let task = task.as_object_mut().expect("task fixture object");
17096            match self {
17097                Self::Missing => {
17098                    task.remove("payload_codec");
17099                }
17100                Self::Null => {
17101                    task.insert("payload_codec".to_string(), Value::Null);
17102                }
17103                Self::NonString => {
17104                    task.insert("payload_codec".to_string(), json!(42));
17105                }
17106            }
17107        }
17108    }
17109
17110    fn fixture_envelope(value: Value) -> Value {
17111        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
17112    }
17113
17114    fn fixture_blob(value: Value) -> String {
17115        encode_payload(&value, DEFAULT_CODEC)
17116            .expect("encode Avro test fixture")
17117            .blob
17118    }
17119
17120    #[test]
17121    fn client_builder_rejects_the_sdk_owned_api_suffix() {
17122        for base_url in [
17123            "http://127.0.0.1:8080/api",
17124            "http://localhost:8080/api/",
17125            "https://runtime.example.test/namespaces/orders/api",
17126        ] {
17127            let error = Client::builder(base_url)
17128                .build()
17129                .expect_err("SDK-owned /api suffix must be rejected during build");
17130
17131            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
17132            assert!(
17133                error.to_string().contains("SDK appends /api automatically"),
17134                "the validation error must explain how to fix the endpoint"
17135            );
17136        }
17137    }
17138
17139    #[test]
17140    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
17141        for (base_url, expected) in [
17142            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
17143            (
17144                "http://localhost:8080/durable-workflow/",
17145                "http://localhost:8080/durable-workflow",
17146            ),
17147            (
17148                "https://runtime.example.test/namespaces/orders",
17149                "https://runtime.example.test/namespaces/orders",
17150            ),
17151            (
17152                "https://runtime.example.test/gateway/api/namespaces/orders",
17153                "https://runtime.example.test/gateway/api/namespaces/orders",
17154            ),
17155            (
17156                "https://api.example.test/runtime/orders/",
17157                "https://api.example.test/runtime/orders",
17158            ),
17159        ] {
17160            let client = Client::builder(base_url)
17161                .build()
17162                .expect("Server and Cloud runtime base URL must remain valid");
17163
17164            assert_eq!(client.base_url, expected);
17165        }
17166    }
17167
17168    #[test]
17169    fn workflow_completion_uses_the_additive_command_protocol_floor() {
17170        assert_eq!(
17171            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
17172            WORKER_PROTOCOL_VERSION
17173        );
17174        assert_eq!(
17175            workflow_completion_protocol_version(&[json!({
17176                "type": "upsert_search_attributes",
17177                "attributes": {"OrderStatus": "waiting"},
17178            })]),
17179            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
17180        );
17181        assert_eq!(
17182            workflow_completion_protocol_version(&[json!({
17183                "type": "upsert_search_attributes",
17184                "attributes": {"OrderStatus": "waiting"},
17185                "attribute_types": {"OrderStatus": "keyword"},
17186            })]),
17187            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
17188        );
17189        assert_eq!(
17190            workflow_completion_protocol_version(&[
17191                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
17192                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17193            ]),
17194            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
17195        );
17196        assert_eq!(
17197            workflow_completion_protocol_version(&[
17198                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
17199                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17200            ]),
17201            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
17202        );
17203        assert_eq!(
17204            workflow_completion_protocol_version(&[json!({
17205                "type": "open_condition_wait",
17206                "condition_wait_occurrence_id": "rust:condition-wait:0",
17207                "condition_key": "ready",
17208            })]),
17209            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17210        );
17211        assert_eq!(
17212            workflow_completion_protocol_version_with_message_streams(
17213                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
17214                true,
17215            ),
17216            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
17217        );
17218        assert_eq!(
17219            workflow_completion_protocol_version_with_message_streams(
17220                &[json!({
17221                    "type": "open_condition_wait",
17222                    "condition_wait_occurrence_id": "rust:condition-wait:0",
17223                    "condition_key": "ready",
17224                })],
17225                true,
17226            ),
17227            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17228        );
17229    }
17230
17231    #[test]
17232    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
17233        let manifest = portable_worker_affinity_capability_manifest();
17234
17235        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
17236            assert_eq!(manifest[capability]["supported"], json!(false));
17237            assert_eq!(
17238                manifest[capability]["minimum_protocol_version"],
17239                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
17240            );
17241            assert!(manifest[capability]["reason"]
17242                .as_str()
17243                .is_some_and(|reason| !reason.is_empty()));
17244        }
17245    }
17246
17247    fn typed_fidelity_probe() -> AvroValue {
17248        AvroValue::Map(BTreeMap::from([
17249            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
17250            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
17251            (
17252                "numeric".to_string(),
17253                AvroValue::Map(BTreeMap::from([
17254                    ("0".to_string(), AvroValue::String("zero".to_string())),
17255                    ("1".to_string(), AvroValue::String("one".to_string())),
17256                ])),
17257            ),
17258            (
17259                "nested".to_string(),
17260                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
17261                    "enabled".to_string(),
17262                    AvroValue::Boolean(true),
17263                )]))]),
17264            ),
17265            (
17266                "projection_collisions".to_string(),
17267                AvroValue::Array(projection_collision_probe()),
17268            ),
17269        ]))
17270    }
17271
17272    fn projection_collision_probe() -> Vec<AvroValue> {
17273        vec![
17274            AvroValue::Map(BTreeMap::from([
17275                ("$type".to_string(), AvroValue::String("bytes".to_string())),
17276                (
17277                    "base64".to_string(),
17278                    AvroValue::String("ordinary user text".to_string()),
17279                ),
17280            ])),
17281            AvroValue::Map(BTreeMap::from([
17282                ("$type".to_string(), AvroValue::String("map".to_string())),
17283                (
17284                    "entries".to_string(),
17285                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
17286                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
17287                        (
17288                            "value".to_string(),
17289                            AvroValue::String("user map".to_string()),
17290                        ),
17291                    ]))]),
17292                ),
17293            ])),
17294        ]
17295    }
17296
17297    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17298    struct TypedContract {
17299        nested: TypedNested,
17300        mode: TypedMode,
17301        optional: Option<String>,
17302        absent: Option<String>,
17303        items: Vec<i64>,
17304        labels: BTreeMap<String, String>,
17305        bytes: serde_bytes::ByteBuf,
17306        signed: i64,
17307        finite: f64,
17308    }
17309
17310    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17311    struct TypedNested {
17312        enabled: bool,
17313    }
17314
17315    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17316    enum TypedMode {
17317        Detailed { label: String },
17318    }
17319
17320    fn typed_contract() -> TypedContract {
17321        TypedContract {
17322            nested: TypedNested { enabled: true },
17323            mode: TypedMode::Detailed {
17324                label: "compiler-checked".to_string(),
17325            },
17326            optional: Some("present".to_string()),
17327            absent: None,
17328            items: vec![i64::MIN, 0, i64::MAX],
17329            labels: BTreeMap::from([
17330                ("language".to_string(), "rust".to_string()),
17331                ("wire".to_string(), "avro".to_string()),
17332            ]),
17333            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
17334            signed: -9_223_372_036_854_775_000,
17335            finite: 12.5,
17336        }
17337    }
17338
17339    #[derive(Clone, Debug, Default, PartialEq)]
17340    struct ReplayCounterState {
17341        loaded: Option<String>,
17342        count: i64,
17343        finished: bool,
17344    }
17345
17346    fn replay_counter_worker() -> Worker {
17347        let client = Client::new("http://127.0.0.1:8080").expect("client");
17348        let mut worker = Worker::new(client, "rust-workers");
17349        worker.register_replayed_workflow(
17350            "replay-counter",
17351            ReplayCounterState::default,
17352            |ctx, _input, state| async move {
17353                let loaded = ctx.activity("load-counter", json!([])).await?;
17354                state.update(|current| {
17355                    current.loaded = loaded.as_str().map(str::to_string);
17356                })?;
17357                for _ in 0..2 {
17358                    let signal = ctx.wait_signal("increment").await?;
17359                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
17360                    state.update(|current| current.count += amount)?;
17361                }
17362                state.update(|current| current.finished = true)?;
17363                state.read(|current| Ok(json!(current.count)))?
17364            },
17365        );
17366        worker.register_replayed_query::<ReplayCounterState, _, _>(
17367            "replay-counter",
17368            "current",
17369            |_ctx, state, _args| async move {
17370                Ok(json!({
17371                    "loaded": state.loaded,
17372                    "count": state.count,
17373                    "finished": state.finished,
17374                }))
17375            },
17376        );
17377        worker.register_replayed_query::<ReplayCounterState, _, _>(
17378            "replay-counter",
17379            "detached-mutation",
17380            |_ctx, state, _args| async move {
17381                let mut detached = (*state).clone();
17382                detached.count = 999;
17383                Ok(json!(detached.count))
17384            },
17385        );
17386        worker.register_replayed_query::<ReplayCounterState, _, _>(
17387            "replay-counter",
17388            "failed-mutation",
17389            |_ctx, state, _args| async move {
17390                let mut detached = (*state).clone();
17391                detached.count = 999;
17392                Err(Error::WorkerLoop("query refused".to_string()))
17393            },
17394        );
17395        worker
17396    }
17397
17398    fn replay_counter_query(
17399        query_name: &str,
17400        history_events: Value,
17401        run_status: &str,
17402    ) -> QueryTask {
17403        let arguments = fixture_envelope(json!([]));
17404        serde_json::from_value(json!({
17405            "query_task_id": format!("query-{query_name}"),
17406            "workflow_type": "replay-counter",
17407            "query_name": query_name,
17408            "payload_codec": DEFAULT_CODEC,
17409            "workflow_arguments": arguments.clone(),
17410            "query_arguments": arguments,
17411            "history_events": history_events,
17412            "run_status": run_status,
17413        }))
17414        .expect("query task")
17415    }
17416
17417    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
17418        workflow_context_with_codec(history, DEFAULT_CODEC)
17419    }
17420
17421    fn workflow_context_with_codec(
17422        history: Vec<HistoryEvent>,
17423        payload_codec: &str,
17424    ) -> WorkflowContext {
17425        WorkflowContext {
17426            cancellation_scope_id: "root".into(),
17427            state: Arc::new(Mutex::new(
17428                WorkflowState::new_with_identity(
17429                    history,
17430                    None,
17431                    None,
17432                    "rust-workers".to_string(),
17433                    payload_codec.to_string(),
17434                    None,
17435                )
17436                .expect("valid workflow history"),
17437            )),
17438        }
17439    }
17440
17441    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
17442        HistoryEvent {
17443            event_type: event_type.to_string(),
17444            payload,
17445            raw: HashMap::new(),
17446        }
17447    }
17448
17449    fn parallel_path_entry(
17450        kind: &str,
17451        base: u64,
17452        size: usize,
17453        index: usize,
17454    ) -> ParallelGroupMetadata {
17455        parallel_group_entry(base, size, index, kind)
17456    }
17457
17458    fn parallel_history_event(
17459        event_type: &str,
17460        sequence: u64,
17461        identity_field: &str,
17462        identity: &str,
17463        path: Vec<ParallelGroupMetadata>,
17464        result: Option<Value>,
17465    ) -> HistoryEvent {
17466        let mut payload = serde_json::Map::from_iter([
17467            ("sequence".to_string(), json!(sequence)),
17468            (identity_field.to_string(), json!(identity)),
17469        ]);
17470        let inner = path.last().expect("parallel history path");
17471        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
17472        payload.insert("parallel_group_path".to_string(), json!(path));
17473        if let Some(result) = result {
17474            let field = if event_type == "ChildRunCompleted" {
17475                "result"
17476            } else {
17477                "result"
17478            };
17479            payload.insert(field.to_string(), fixture_envelope(result));
17480            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
17481        }
17482        history_event(event_type, Value::Object(payload))
17483    }
17484
17485    fn nested_parallel_operations() -> Vec<ParallelOperation> {
17486        vec![
17487            ParallelOperation::activity("first", json!([])),
17488            ParallelOperation::group(vec![
17489                ParallelOperation::child_workflow(
17490                    "second",
17491                    ChildWorkflowOptions::new("child-workers"),
17492                    json!([]),
17493                ),
17494                ParallelOperation::activity("third", json!([])),
17495            ]),
17496        ]
17497    }
17498
17499    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
17500        let outer = [
17501            parallel_path_entry("mixed", 1, 3, 0),
17502            parallel_path_entry("mixed", 1, 3, 1),
17503            parallel_path_entry("mixed", 1, 3, 2),
17504        ];
17505        [
17506            vec![outer[0].clone()],
17507            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
17508            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
17509        ]
17510    }
17511
17512    #[test]
17513    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
17514        let ctx = workflow_context(Vec::new());
17515        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17516        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17517
17518        assert!(matches!(
17519            call.as_mut().poll(&mut task_context),
17520            Poll::Pending
17521        ));
17522        let commands = ctx.take_commands().expect("parallel commands");
17523        assert_eq!(
17524            commands
17525                .iter()
17526                .map(|command| command["type"].as_str().unwrap_or_default())
17527                .collect::<Vec<_>>(),
17528            [
17529                "schedule_activity",
17530                "start_child_workflow",
17531                "schedule_activity"
17532            ]
17533        );
17534        let paths = nested_parallel_paths();
17535        for (command, path) in commands.iter().zip(paths) {
17536            assert_eq!(command["parallel_group_path"], json!(path));
17537            assert_eq!(
17538                command["parallel_group_id"],
17539                json!(path.last().expect("inner group").parallel_group_id)
17540            );
17541        }
17542    }
17543
17544    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
17545        let paths = nested_parallel_paths();
17546        let third = parallel_history_event(
17547            "ActivityCompleted",
17548            3,
17549            "activity_type",
17550            "third",
17551            paths[2].clone(),
17552            Some(json!("three")),
17553        );
17554        vec![
17555            parallel_history_event(
17556                "ActivityCompleted",
17557                1,
17558                "activity_type",
17559                "first",
17560                paths[0].clone(),
17561                Some(json!("one")),
17562            ),
17563            parallel_history_event(
17564                "ChildWorkflowScheduled",
17565                2,
17566                "child_workflow_type",
17567                "second",
17568                paths[1].clone(),
17569                None,
17570            ),
17571            parallel_history_event(
17572                "ChildRunCompleted",
17573                2,
17574                "child_workflow_type",
17575                "second",
17576                paths[1].clone(),
17577                Some(json!("two")),
17578            ),
17579            third.clone(),
17580            third,
17581        ]
17582    }
17583
17584    #[test]
17585    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
17586        for _restart_or_completed_replay in 0..2 {
17587            let ctx = workflow_context(completed_nested_parallel_history());
17588            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17589            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17590            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
17591                panic!("completed nested parallel history must replay");
17592            };
17593            assert_eq!(
17594                results,
17595                vec![
17596                    ParallelResult::Activity(json!("one")),
17597                    ParallelResult::Group(vec![
17598                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
17599                            parent: WorkflowIdentity {
17600                                workflow_id: None,
17601                                run_id: None,
17602                            },
17603                            child: WorkflowIdentity {
17604                                workflow_id: None,
17605                                run_id: None,
17606                            },
17607                            child_workflow_type: Some("second".to_string()),
17608                            result: json!("two"),
17609                        }),
17610                        ParallelResult::Activity(json!("three")),
17611                    ]),
17612                ]
17613            );
17614            assert!(ctx.take_commands().expect("commands").is_empty());
17615            ctx.ensure_history_consumed().expect("history consumed");
17616        }
17617    }
17618
17619    #[test]
17620    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
17621        let paths = nested_parallel_paths();
17622        let history = vec![
17623            parallel_history_event(
17624                "ActivityCompleted",
17625                1,
17626                "activity_type",
17627                "first",
17628                paths[0].clone(),
17629                Some(json!("one")),
17630            ),
17631            parallel_history_event(
17632                "ChildWorkflowScheduled",
17633                2,
17634                "child_workflow_type",
17635                "second",
17636                paths[1].clone(),
17637                None,
17638            ),
17639            parallel_history_event(
17640                "ChildRunFailed",
17641                2,
17642                "child_workflow_type",
17643                "second",
17644                paths[1].clone(),
17645                None,
17646            ),
17647            parallel_history_event(
17648                "ActivityCompleted",
17649                3,
17650                "activity_type",
17651                "third",
17652                paths[2].clone(),
17653                Some(json!("late")),
17654            ),
17655        ];
17656        let ctx = workflow_context(history);
17657        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17658        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17659        let outcome = call.as_mut().poll(&mut task_context);
17660        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
17661            panic!("one failed child must return a typed partial failure: {outcome:?}");
17662        };
17663        assert_eq!(failure.member_path, [1, 0]);
17664        assert_eq!(failure.group_id, "parallel-calls:1:3");
17665        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
17666        assert_eq!(
17667            failure
17668                .completed
17669                .iter()
17670                .map(|completion| completion.member_path.clone())
17671                .collect::<Vec<_>>(),
17672            [vec![0], vec![1, 1]]
17673        );
17674    }
17675
17676    #[test]
17677    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
17678        let paths = nested_parallel_paths();
17679        let history = vec![
17680            parallel_history_event(
17681                "ActivityScheduled",
17682                1,
17683                "activity_type",
17684                "first",
17685                paths[0].clone(),
17686                None,
17687            ),
17688            parallel_history_event(
17689                "ChildWorkflowScheduled",
17690                2,
17691                "child_workflow_type",
17692                "second",
17693                paths[1].clone(),
17694                None,
17695            ),
17696            parallel_history_event(
17697                "ActivityScheduled",
17698                3,
17699                "activity_type",
17700                "third",
17701                paths[2].clone(),
17702                None,
17703            ),
17704        ];
17705        for _restart in 0..2 {
17706            let ctx = workflow_context(history.clone());
17707            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17708            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17709            let outcome = call.as_mut().poll(&mut task_context);
17710            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
17711            assert!(ctx.take_commands().expect("commands").is_empty());
17712        }
17713    }
17714
17715    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
17716        vec![selection_group_entry(
17717            1,
17718            2,
17719            index,
17720            "activity",
17721            &SelectionMemberMetadata {
17722                key: SelectionKey::Name(key.to_string()),
17723                index,
17724                base_sequence: index as u64 + 1,
17725                size: 1,
17726                kind: "activity".to_string(),
17727            },
17728        )]
17729    }
17730
17731    fn selection_activity_event(
17732        event_type: &str,
17733        index: usize,
17734        key: &str,
17735        result: Option<Value>,
17736    ) -> HistoryEvent {
17737        let sequence = index as u64 + 1;
17738        let mut event = parallel_history_event(
17739            event_type,
17740            sequence,
17741            "activity_type",
17742            &format!("{key}-activity"),
17743            selection_path(index, key),
17744            result,
17745        );
17746        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
17747        event.raw.insert(
17748            "id".to_string(),
17749            json!(if event_type == "ActivityCompleted" {
17750                format!("event-{key}")
17751            } else {
17752                format!("{event_type}-{key}")
17753            }),
17754        );
17755        event
17756    }
17757
17758    fn selection_winner_marker() -> HistoryEvent {
17759        history_event(
17760            "SelectionResolved",
17761            json!({
17762                "selection_group_id": "select-calls:1:2",
17763                "selection_group_base_sequence": 1,
17764                "selection_group_size": 2,
17765                "member_key": "fast",
17766                "member_index": 1,
17767                "member_base_sequence": 2,
17768                "member_size": 1,
17769                "operation_kind": "activity",
17770                "operation_identity": "activity-fast",
17771                "outcome": "completed",
17772                "resolution_event_id": "event-fast",
17773                "resolution_event_type": "ActivityCompleted",
17774            }),
17775        )
17776    }
17777
17778    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
17779        ctx.select_keyed(vec![
17780            (
17781                "slow",
17782                ParallelOperation::activity_with_options(
17783                    "slow-activity",
17784                    ActivityOptions::new().task_queue("default"),
17785                    json!([]),
17786                ),
17787            ),
17788            (
17789                "fast",
17790                ParallelOperation::activity_with_options(
17791                    "fast-activity",
17792                    ActivityOptions::new().task_queue("default"),
17793                    json!([]),
17794                ),
17795            ),
17796        ])
17797    }
17798
17799    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
17800        let ctx = workflow_context(history);
17801        let mut call = Box::pin(keyed_activity_selection(&ctx));
17802        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17803        let selected = match call.as_mut().poll(&mut task_context) {
17804            Poll::Ready(Ok(selected)) => selected,
17805            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
17806            Poll::Pending => panic!("persisted selection winner must replay without pending"),
17807        };
17808        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
17809        assert_eq!(
17810            selected.value,
17811            Some(ParallelResult::Activity(json!("winner-value")))
17812        );
17813        let slow = selected
17814            .handle(&SelectionKey::Name("slow".to_string()))
17815            .expect("slow handle")
17816            .clone();
17817        let mut await_slow = Box::pin(slow.await_result());
17818        assert!(matches!(
17819            await_slow.as_mut().poll(&mut task_context),
17820            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
17821        ));
17822        assert!(ctx.take_commands().expect("commands").is_empty());
17823    }
17824
17825    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
17826
17827    fn canonical_selection_history() -> Vec<HistoryEvent> {
17828        const FIXTURE: &[u8] =
17829            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
17830        assert_eq!(
17831            format!("{:x}", Sha256::digest(FIXTURE)),
17832            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
17833        );
17834        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
17835
17836        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
17837    }
17838
17839    #[test]
17840    fn selection_fresh_process_entrypoint() {
17841        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
17842            return;
17843        };
17844        let persisted = fs::read(path).expect("persisted selection history");
17845        assert_eq!(
17846            format!("{:x}", Sha256::digest(&persisted)),
17847            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
17848        );
17849        let fixture: Value =
17850            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
17851        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
17852            .expect("valid persisted selection history");
17853
17854        assert_persisted_selection_replay(history);
17855    }
17856
17857    #[test]
17858    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
17859        let ctx = workflow_context(Vec::new());
17860        let mut call = Box::pin(keyed_activity_selection(&ctx));
17861        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17862
17863        assert!(matches!(
17864            call.as_mut().poll(&mut task_context),
17865            Poll::Pending
17866        ));
17867        let commands = ctx.take_commands().expect("selection commands");
17868        assert_eq!(commands.len(), 2);
17869        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
17870        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
17871        assert!(commands.iter().all(|command| {
17872            command["parallel_group_id"] == json!("select-calls:1:2")
17873                && command["parallel_group_mode"] == json!("select")
17874        }));
17875    }
17876
17877    #[test]
17878    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
17879        let ctx = workflow_context(Vec::new());
17880        let mut invalid = Box::pin(ctx.select_keyed(vec![(
17881            "",
17882            ParallelOperation::activity("invalid", json!([])),
17883        )]));
17884        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17885        assert!(matches!(
17886            invalid.as_mut().poll(&mut task_context),
17887            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
17888                reason: "selection_key_invalid",
17889                ..
17890            })))
17891        ));
17892
17893        for invalid_key in [json!(""), json!(-1)] {
17894            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
17895            event.payload["selection_member_key"] = invalid_key.clone();
17896            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
17897            assert!(matches!(
17898                WorkflowState::new_with_identity(
17899                    vec![event],
17900                    None,
17901                    None,
17902                    "rust-workers".to_string(),
17903                    DEFAULT_CODEC.to_string(),
17904                    None,
17905                ),
17906                Err(Error::NonDeterministicReplay(_))
17907            ));
17908        }
17909    }
17910
17911    #[test]
17912    fn selection_preserves_valid_named_and_numeric_keys() {
17913        let ctx = workflow_context(Vec::new());
17914        let mut selection = Box::pin(ctx.select_keyed(vec![
17915            (
17916                SelectionKey::Index(0),
17917                ParallelOperation::activity("numeric", json!([])),
17918            ),
17919            (
17920                SelectionKey::Name("named".to_string()),
17921                ParallelOperation::timer(Duration::from_secs(1)),
17922            ),
17923        ]));
17924        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17925
17926        assert!(matches!(
17927            selection.as_mut().poll(&mut task_context),
17928            Poll::Pending
17929        ));
17930        let commands = ctx.take_commands().expect("selection commands");
17931        assert_eq!(commands[0]["selection_member_key"], json!(0));
17932        assert_eq!(commands[1]["selection_member_key"], json!("named"));
17933    }
17934
17935    #[test]
17936    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
17937        let history = canonical_selection_history();
17938        assert_persisted_selection_replay(history.clone());
17939
17940        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
17941            .join("tests/fixtures/durable_selection_runtime_history.json");
17942        let output =
17943            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
17944                .args([
17945                    "--exact",
17946                    "tests::selection_fresh_process_entrypoint",
17947                    "--nocapture",
17948                ])
17949                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
17950                .output()
17951                .expect("run fresh selection replay process");
17952
17953        assert!(
17954            output.status.success(),
17955            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
17956            String::from_utf8_lossy(&output.stdout),
17957            String::from_utf8_lossy(&output.stderr),
17958        );
17959    }
17960
17961    #[test]
17962    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
17963        let mut history = canonical_selection_history();
17964        history.retain(|event| event.event_type != "SelectionResolved");
17965        let ctx = workflow_context(history);
17966        let mut selection = Box::pin(keyed_activity_selection(&ctx));
17967        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17968
17969        assert!(matches!(
17970            selection.as_mut().poll(&mut task_context),
17971            Poll::Pending
17972        ));
17973        assert!(ctx.take_commands().expect("commands").is_empty());
17974        assert!(
17975            ctx.matched_recorded_pending()
17976                .expect("selection pending state"),
17977            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
17978        );
17979    }
17980
17981    #[test]
17982    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
17983        for (terminal_event, predicate_satisfied, timeout_seconds) in [
17984            ("ConditionWaitSatisfied", true, None),
17985            ("ConditionWaitTimedOut", false, Some(0)),
17986        ] {
17987            let member = SelectionMemberMetadata {
17988                key: SelectionKey::Name("condition".to_string()),
17989                index: 0,
17990                base_sequence: 1,
17991                size: 1,
17992                kind: "condition".to_string(),
17993            };
17994            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
17995            let mut payload = json!({
17996                "sequence": 1,
17997                "condition_wait_id": "condition-1",
17998                "condition_wait_occurrence_id": "rust:condition-wait:0",
17999                "condition_key": "ready",
18000                "condition_definition_fingerprint": "sha256:ready-v1",
18001                "parallel_group_path": path,
18002            });
18003            payload
18004                .as_object_mut()
18005                .expect("condition history payload")
18006                .extend(
18007                    serde_json::to_value(&path[0])
18008                        .expect("condition selection metadata")
18009                        .as_object()
18010                        .expect("condition selection metadata object")
18011                        .clone(),
18012                );
18013            if let Some(timeout_seconds) = timeout_seconds {
18014                payload["timeout_seconds"] = json!(timeout_seconds);
18015            }
18016            let history = vec![
18017                history_event("ConditionWaitOpened", payload.clone()),
18018                history_event(terminal_event, payload),
18019            ];
18020            let ctx = workflow_context(history);
18021            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18022            if timeout_seconds.is_some() {
18023                options = options.timeout(Duration::ZERO);
18024            }
18025            let mut selection = Box::pin(ctx.select_keyed(vec![(
18026                "condition",
18027                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18028            )]));
18029            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18030
18031            assert!(matches!(
18032                selection.as_mut().poll(&mut task_context),
18033                Poll::Pending
18034            ));
18035            assert!(ctx.take_commands().expect("commands").is_empty());
18036            assert!(
18037                ctx.matched_recorded_pending()
18038                    .expect("condition selection pending state"),
18039                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18040            );
18041        }
18042    }
18043
18044    #[test]
18045    fn selection_immediate_condition_members_open_a_durable_wait() {
18046        for predicate_satisfied in [true, false] {
18047            let ctx = workflow_context(Vec::new());
18048            let mut selection = Box::pin(ctx.select_keyed(vec![(
18049                "condition",
18050                ParallelOperation::condition(
18051                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18052                    move || Ok(predicate_satisfied),
18053                ),
18054            )]));
18055            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18056
18057            assert!(matches!(
18058                selection.as_mut().poll(&mut task_context),
18059                Poll::Pending
18060            ));
18061            let commands = ctx.take_commands().expect("condition selection command");
18062            assert_eq!(commands.len(), 1);
18063            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18064            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18065            assert_eq!(
18066                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18067                json!("select")
18068            );
18069        }
18070    }
18071
18072    #[test]
18073    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18074        let history = vec![
18075            selection_activity_event("ActivityScheduled", 0, "slow", None),
18076            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18077            selection_winner_marker(),
18078        ];
18079        let ctx = workflow_context(history.clone());
18080        let mut call = Box::pin(keyed_activity_selection(&ctx));
18081        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18082        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18083            panic!("winner must replay");
18084        };
18085        let slow = selected
18086            .handle(&SelectionKey::Name("slow".to_string()))
18087            .expect("slow handle")
18088            .clone();
18089        let mut cancel = Box::pin(slow.cancel());
18090        assert!(matches!(
18091            cancel.as_mut().poll(&mut task_context),
18092            Poll::Pending
18093        ));
18094        assert!(matches!(
18095            cancel.as_mut().poll(&mut task_context),
18096            Poll::Pending
18097        ));
18098        let commands = ctx.take_commands().expect("cancel command");
18099        assert_eq!(commands.len(), 1);
18100        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18101        assert_eq!(commands[0]["member_key"], json!("slow"));
18102
18103        let mut cancelled_history = history;
18104        cancelled_history.push(history_event(
18105            "SelectionOperationCancelled",
18106            json!({
18107                "selection_group_id": "select-calls:1:2",
18108                "member_key": "slow",
18109                "member_index": 0,
18110                "member_base_sequence": 1,
18111                "member_size": 1,
18112                "operation_kind": "activity",
18113                "operation_identity": "activity-slow",
18114                "cancelled_at": "2026-08-27T00:00:00Z",
18115            }),
18116        ));
18117        let replayed = workflow_context(cancelled_history);
18118        let mut call = Box::pin(keyed_activity_selection(&replayed));
18119        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18120            panic!("winner must replay after cancellation");
18121        };
18122        let slow = selected
18123            .handle(&SelectionKey::Name("slow".to_string()))
18124            .expect("slow handle")
18125            .clone();
18126        let mut cancel = Box::pin(slow.cancel());
18127        assert!(matches!(
18128            cancel.as_mut().poll(&mut task_context),
18129            Poll::Ready(Ok(()))
18130        ));
18131        assert!(replayed.take_commands().expect("commands").is_empty());
18132    }
18133
18134    #[test]
18135    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
18136        let base_history = vec![
18137            selection_activity_event("ActivityScheduled", 0, "slow", None),
18138            selection_activity_event("ActivityScheduled", 1, "fast", None),
18139            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18140            selection_winner_marker(),
18141        ];
18142        for (field, corrupt) in [
18143            ("member_key", json!("fast")),
18144            ("member_index", json!(1)),
18145            ("member_base_sequence", json!(3)),
18146            ("member_size", json!(2)),
18147            ("operation_kind", json!("timer")),
18148            ("operation_identity", json!("forged")),
18149        ] {
18150            let mut cancellation = json!({
18151                "selection_group_id": "select-calls:1:2",
18152                "member_key": "slow",
18153                "member_index": 0,
18154                "member_base_sequence": 1,
18155                "member_size": 1,
18156                "operation_kind": "activity",
18157                "operation_identity": "activity-slow",
18158            });
18159            cancellation[field] = corrupt;
18160            let mut history = base_history.clone();
18161            history.push(history_event("SelectionOperationCancelled", cancellation));
18162            let ctx = workflow_context(history);
18163            let mut selection = Box::pin(keyed_activity_selection(&ctx));
18164            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18165
18166            assert!(matches!(
18167                selection.as_mut().poll(&mut task_context),
18168                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18169            ));
18170        }
18171    }
18172
18173    #[test]
18174    fn selection_child_identity_prefers_the_durable_run_id() {
18175        let ctx = workflow_context(vec![history_event(
18176            "ChildWorkflowScheduled",
18177            json!({
18178                "sequence": 1,
18179                "child_workflow_type": "child",
18180                "child_workflow_instance_id": "child-instance",
18181                "child_workflow_run_id": "child-run",
18182            }),
18183        )]);
18184        let state = ctx.state.lock().expect("workflow state");
18185
18186        assert_eq!(
18187            selection_operation_identity(&state, "child", 1, 1),
18188            "child-run"
18189        );
18190    }
18191
18192    #[test]
18193    fn selection_activity_identity_requires_canonical_execution_id() {
18194        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
18195        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
18196        let mut fast_completed =
18197            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
18198        for event in [&mut fast_open, &mut fast_completed] {
18199            event
18200                .payload
18201                .as_object_mut()
18202                .expect("activity payload")
18203                .remove("activity_execution_id");
18204            event.payload["activity_id"] = json!("forged-activity-id");
18205        }
18206        let mut marker = selection_winner_marker();
18207        marker.payload["operation_identity"] = json!("forged-activity-id");
18208        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
18209        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18210        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18211
18212        assert!(matches!(
18213            selection.as_mut().poll(&mut task_context),
18214            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18215        ));
18216    }
18217
18218    #[test]
18219    fn selection_completion_before_cancellation_remains_awaitable() {
18220        let history = vec![
18221            selection_activity_event("ActivityScheduled", 0, "slow", None),
18222            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18223            selection_winner_marker(),
18224            selection_activity_event(
18225                "ActivityCompleted",
18226                0,
18227                "slow",
18228                Some(json!("completed-first")),
18229            ),
18230        ];
18231        let ctx = workflow_context(history);
18232        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18233        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18234        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18235            panic!("winner must replay");
18236        };
18237        let slow = selected
18238            .handle(&SelectionKey::Name("slow".to_string()))
18239            .expect("slow handle")
18240            .clone();
18241        let mut cancel = Box::pin(slow.cancel());
18242        assert!(matches!(
18243            cancel.as_mut().poll(&mut task_context),
18244            Poll::Ready(Ok(()))
18245        ));
18246        let mut await_slow = Box::pin(slow.await_result());
18247        assert!(matches!(
18248            await_slow.as_mut().poll(&mut task_context),
18249            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
18250        ));
18251        let commands = ctx.take_commands().expect("commands");
18252        assert!(commands.is_empty());
18253    }
18254
18255    #[test]
18256    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
18257        let nested_member = SelectionMemberMetadata {
18258            key: SelectionKey::Name("nested".to_string()),
18259            index: 0,
18260            base_sequence: 1,
18261            size: 2,
18262            kind: "group".to_string(),
18263        };
18264        let deadline_member = SelectionMemberMetadata {
18265            key: SelectionKey::Name("deadline".to_string()),
18266            index: 1,
18267            base_sequence: 3,
18268            size: 1,
18269            kind: "timer".to_string(),
18270        };
18271        let nested_paths = [
18272            vec![
18273                selection_group_entry(1, 3, 0, "mixed", &nested_member),
18274                parallel_group_entry(1, 2, 0, "activity"),
18275            ],
18276            vec![
18277                selection_group_entry(1, 3, 1, "mixed", &nested_member),
18278                parallel_group_entry(1, 2, 1, "activity"),
18279            ],
18280        ];
18281        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
18282        let mut timer_fired = parallel_history_event(
18283            "TimerFired",
18284            3,
18285            "timer_id",
18286            "timer-3",
18287            deadline_path.clone(),
18288            None,
18289        );
18290        timer_fired.payload["delay_seconds"] = json!(0);
18291        timer_fired
18292            .raw
18293            .insert("id".to_string(), json!("timer-fired"));
18294        let mut timer_scheduled = parallel_history_event(
18295            "TimerScheduled",
18296            3,
18297            "timer_id",
18298            "timer-3",
18299            deadline_path,
18300            None,
18301        );
18302        timer_scheduled.payload["delay_seconds"] = json!(0);
18303        let history = vec![
18304            parallel_history_event(
18305                "ActivityScheduled",
18306                1,
18307                "activity_type",
18308                "nested-first",
18309                nested_paths[0].clone(),
18310                None,
18311            ),
18312            parallel_history_event(
18313                "ActivityScheduled",
18314                2,
18315                "activity_type",
18316                "nested-second",
18317                nested_paths[1].clone(),
18318                None,
18319            ),
18320            timer_scheduled,
18321            timer_fired,
18322            history_event(
18323                "SelectionResolved",
18324                json!({
18325                    "selection_group_id": "select-calls:1:3",
18326                    "selection_group_base_sequence": 1,
18327                    "selection_group_size": 3,
18328                    "member_key": "deadline",
18329                    "member_index": 1,
18330                    "member_base_sequence": 3,
18331                    "member_size": 1,
18332                    "operation_kind": "timer",
18333                    "operation_identity": "timer-3",
18334                    "outcome": "completed",
18335                    "resolution_event_id": "timer-fired",
18336                    "resolution_event_type": "TimerFired",
18337                }),
18338            ),
18339            parallel_history_event(
18340                "ActivityFailed",
18341                2,
18342                "activity_type",
18343                "nested-second",
18344                nested_paths[1].clone(),
18345                None,
18346            ),
18347        ];
18348        let ctx = workflow_context(history);
18349        let mut selection = Box::pin(ctx.select_keyed(vec![
18350            (
18351                "nested",
18352                ParallelOperation::group(vec![
18353                    ParallelOperation::activity("nested-first", json!([])),
18354                    ParallelOperation::activity("nested-second", json!([])),
18355                ]),
18356            ),
18357            ("deadline", ParallelOperation::timer(Duration::ZERO)),
18358        ]));
18359        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18360        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18361            panic!("deadline winner must replay");
18362        };
18363        let nested = selected
18364            .handle(&SelectionKey::Name("nested".to_string()))
18365            .expect("nested handle")
18366            .clone();
18367        let mut cancel = Box::pin(nested.cancel());
18368        assert!(matches!(
18369            cancel.as_mut().poll(&mut task_context),
18370            Poll::Ready(Ok(()))
18371        ));
18372        let mut await_nested = Box::pin(nested.await_result());
18373
18374        assert!(matches!(
18375            await_nested.as_mut().poll(&mut task_context),
18376            Poll::Ready(Err(Error::ActivityFailed(_)))
18377        ));
18378        assert!(ctx.take_commands().expect("commands").is_empty());
18379    }
18380
18381    #[test]
18382    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
18383        let ctx = workflow_context(Vec::new());
18384        let mut call = Box::pin(ctx.select(vec![
18385            ParallelOperation::child_workflow(
18386                "child",
18387                ChildWorkflowOptions::new("children"),
18388                json!([]),
18389            ),
18390            ParallelOperation::timer(Duration::from_secs(30)),
18391            ParallelOperation::signal("approval"),
18392            ParallelOperation::condition(
18393                ConditionWaitOptions::new("ready", "sha256:ready"),
18394                || Ok(false),
18395            ),
18396            ParallelOperation::group(vec![
18397                ParallelOperation::activity("nested-one", json!([])),
18398                ParallelOperation::activity("nested-two", json!([])),
18399            ]),
18400        ]));
18401        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18402        assert!(matches!(
18403            call.as_mut().poll(&mut task_context),
18404            Poll::Pending
18405        ));
18406        let commands = ctx.take_commands().expect("selection commands");
18407        assert_eq!(
18408            commands
18409                .iter()
18410                .map(|command| command["type"].as_str().unwrap_or_default())
18411                .collect::<Vec<_>>(),
18412            [
18413                "start_child_workflow",
18414                "start_timer",
18415                "open_signal_wait",
18416                "open_condition_wait",
18417                "schedule_activity",
18418                "schedule_activity",
18419            ]
18420        );
18421        assert!(commands.iter().all(|command| {
18422            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
18423        }));
18424        assert_eq!(
18425            commands[4]["parallel_group_path"].as_array().map(Vec::len),
18426            Some(2)
18427        );
18428        assert_eq!(
18429            commands[4]["parallel_group_path"][0]["selection_member_kind"],
18430            json!("group")
18431        );
18432        assert_eq!(
18433            commands[5]["parallel_group_path"][0]["selection_member_kind"],
18434            json!("group")
18435        );
18436
18437        let one_leaf_ctx = workflow_context(Vec::new());
18438        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
18439            ParallelOperation::activity("nested-only", json!([])),
18440        ])]));
18441        assert!(matches!(
18442            one_leaf.as_mut().poll(&mut task_context),
18443            Poll::Pending
18444        ));
18445        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
18446        assert_eq!(one_leaf_commands.len(), 1);
18447        assert_eq!(
18448            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
18449            json!("group")
18450        );
18451        assert_eq!(
18452            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
18453            json!(1)
18454        );
18455    }
18456
18457    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
18458        let mut saga = ctx.saga();
18459        let outcome = async {
18460            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18461            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18462            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
18463            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
18464            ctx.activity("trip.charge", json!([])).await?;
18465            Ok(json!({"status": "booked"}))
18466        }
18467        .await;
18468        saga.finish(outcome).await
18469    }
18470
18471    fn saga_activity(
18472        event_type: &str,
18473        sequence: u64,
18474        activity_type: &str,
18475        result: Option<Value>,
18476    ) -> HistoryEvent {
18477        let mut payload = json!({
18478            "sequence": sequence,
18479            "activity_type": activity_type,
18480            "message": format!("{activity_type} failed"),
18481            "exception_type": "PlannedFailure",
18482            "non_retryable": true,
18483        });
18484        if let Some(result) = result {
18485            payload["result"] = fixture_envelope(result);
18486        }
18487        history_event(event_type, payload)
18488    }
18489
18490    #[test]
18491    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
18492        let completed_hotel_compensation = saga_activity(
18493            "ActivityCompleted",
18494            4,
18495            "trip.cancel-hotel",
18496            Some(Value::Null),
18497        );
18498        let history = vec![
18499            saga_activity(
18500                "ActivityCompleted",
18501                1,
18502                "trip.reserve-flight",
18503                Some(json!("flight-1")),
18504            ),
18505            saga_activity(
18506                "ActivityCompleted",
18507                2,
18508                "trip.reserve-hotel",
18509                Some(json!("hotel-1")),
18510            ),
18511            saga_activity("ActivityFailed", 3, "trip.charge", None),
18512            completed_hotel_compensation.clone(),
18513            completed_hotel_compensation,
18514        ];
18515
18516        for _restart in 0..2 {
18517            let ctx = workflow_context(history.clone());
18518            let mut future = Box::pin(trip_saga(ctx.clone()));
18519            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18520            assert!(matches!(
18521                future.as_mut().poll(&mut task_context),
18522                Poll::Pending
18523            ));
18524            let commands = ctx.take_commands().expect("compensation command");
18525            assert_eq!(commands.len(), 1);
18526            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18527        }
18528    }
18529
18530    #[test]
18531    fn saga_compensation_failure_preserves_both_typed_failures() {
18532        let history = vec![
18533            saga_activity(
18534                "ActivityCompleted",
18535                1,
18536                "trip.reserve-flight",
18537                Some(json!("flight-1")),
18538            ),
18539            saga_activity(
18540                "ActivityCompleted",
18541                2,
18542                "trip.reserve-hotel",
18543                Some(json!("hotel-1")),
18544            ),
18545            saga_activity("ActivityFailed", 3, "trip.charge", None),
18546            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
18547        ];
18548        let ctx = workflow_context(history);
18549        let mut future = Box::pin(trip_saga(ctx));
18550        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18551        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
18552            future.as_mut().poll(&mut task_context)
18553        else {
18554            panic!("compensation failure must remain structured");
18555        };
18556        assert!(matches!(
18557            *failure.initiating_failure,
18558            Error::ActivityFailed(_)
18559        ));
18560        assert!(matches!(
18561            *failure.compensation_failure,
18562            Error::ActivityFailed(_)
18563        ));
18564        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
18565        assert_eq!(failure.compensation_registration_order, 2);
18566    }
18567
18568    #[test]
18569    fn saga_compensates_cooperative_cancellation() {
18570        let ctx = workflow_context(vec![saga_activity(
18571            "ActivityCompleted",
18572            1,
18573            "trip.reserve-flight",
18574            Some(json!("flight-1")),
18575        )]);
18576        ctx.state.lock().expect("state").cancel_requested = true;
18577        let run = {
18578            let ctx = ctx.clone();
18579            async move {
18580                let mut saga = ctx.saga();
18581                let outcome = async {
18582                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18583                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18584                    ctx.throw_if_cancellation_requested()?;
18585                    Ok(json!("unexpected"))
18586                }
18587                .await;
18588                saga.finish(outcome).await
18589            }
18590        };
18591        let mut future = Box::pin(run);
18592        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18593        assert!(matches!(
18594            future.as_mut().poll(&mut task_context),
18595            Poll::Pending
18596        ));
18597        let commands = ctx.take_commands().expect("cancellation compensation");
18598        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18599    }
18600
18601    fn workflow_task(
18602        workflow_type: &str,
18603        history_events: Vec<HistoryEvent>,
18604        payload_codec: &str,
18605    ) -> WorkflowTask {
18606        WorkflowTask {
18607            task_id: format!("wft-{workflow_type}"),
18608            workflow_command_id: None,
18609            workflow_id: Some(format!("wf-{workflow_type}")),
18610            run_id: Some(format!("run-{workflow_type}")),
18611            workflow_type: workflow_type.to_string(),
18612            cancel_requested: false,
18613            payload_codec: payload_codec.to_string(),
18614            arguments: Some(
18615                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
18616            ),
18617            total_history_events: Some(history_events.len() as u64),
18618            history_size_bytes: None,
18619            continue_as_new_recommended: None,
18620            history_budget_pressure: None,
18621            history_events,
18622            next_history_page_token: None,
18623            workflow_task_attempt: 1,
18624            workflow_signal_id: None,
18625            signal_name: None,
18626            signal_arguments: None,
18627            workflow_update_id: None,
18628            update_name: None,
18629            lease_owner: Some("rust-worker".to_string()),
18630        }
18631    }
18632
18633    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18634    struct SideEffectProbe {
18635        request_id: String,
18636        attempt: u32,
18637    }
18638
18639    #[test]
18640    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
18641        let calls = AtomicUsize::new(0);
18642        let ctx = workflow_context(Vec::new());
18643        let value = ctx
18644            .side_effect(|| {
18645                calls.fetch_add(1, Ordering::SeqCst);
18646                SideEffectProbe {
18647                    request_id: "request-42".to_string(),
18648                    attempt: 3,
18649                }
18650            })
18651            .expect("first side effect");
18652        assert_eq!(value.attempt, 3);
18653        assert_eq!(calls.load(Ordering::SeqCst), 1);
18654        let commands = ctx.take_commands().expect("commands");
18655        assert_eq!(commands.len(), 1);
18656        assert_eq!(commands[0]["type"], "record_side_effect");
18657        assert_eq!(
18658            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18659            serde_json::to_value(&value).expect("value")
18660        );
18661
18662        let replay = workflow_context(vec![history_event(
18663            "SideEffectRecorded",
18664            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18665        )]);
18666        let replayed: SideEffectProbe = replay
18667            .side_effect(|| {
18668                calls.fetch_add(1, Ordering::SeqCst);
18669                panic!("committed side-effect callbacks must not run during replay")
18670            })
18671            .expect("replayed side effect");
18672        assert_eq!(replayed, value);
18673        assert_eq!(calls.load(Ordering::SeqCst), 1);
18674        assert!(replay.take_commands().expect("commands").is_empty());
18675        replay.ensure_history_consumed().expect("history consumed");
18676    }
18677
18678    #[test]
18679    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
18680        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18681        let value = ctx
18682            .side_effect(|| SideEffectProbe {
18683                request_id: "avro-request".to_string(),
18684                attempt: 1,
18685            })
18686            .expect("Avro side effect");
18687        let uuid = ctx.uuid_v4().expect("deterministic UUID");
18688        let commands = ctx.take_commands().expect("commands");
18689        assert_eq!(commands.len(), 2);
18690        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
18691        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
18692        assert_eq!(
18693            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18694            serde_json::to_value(&value).expect("value")
18695        );
18696
18697        let replay = workflow_context_with_codec(
18698            vec![
18699                history_event(
18700                    "SideEffectRecorded",
18701                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18702                ),
18703                history_event(
18704                    "SideEffectRecorded",
18705                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
18706                ),
18707            ],
18708            DEFAULT_CODEC,
18709        );
18710        let replayed: SideEffectProbe = replay
18711            .side_effect(|| panic!("Avro callback must not run"))
18712            .expect("replayed Avro value");
18713        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
18714        assert_eq!(replayed, value);
18715        assert_eq!(replayed_uuid, uuid);
18716        assert!(replay.take_commands().expect("commands").is_empty());
18717    }
18718
18719    #[test]
18720    fn typed_side_effect_replay_preserves_bytes_and_maps() {
18721        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18722        let value = ctx
18723            .side_effect_avro_value(typed_fidelity_probe)
18724            .expect("typed side effect");
18725        let commands = ctx.take_commands().expect("side-effect command");
18726        assert_eq!(
18727            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
18728                .expect("recorded side effect"),
18729            value
18730        );
18731
18732        let replay = workflow_context_with_codec(
18733            vec![history_event(
18734                "SideEffectRecorded",
18735                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18736            )],
18737            DEFAULT_CODEC,
18738        );
18739        assert_eq!(
18740            replay
18741                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
18742                .expect("replayed typed side effect"),
18743            value
18744        );
18745    }
18746
18747    #[test]
18748    fn ordered_side_effects_share_the_durable_command_stream() {
18749        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
18750        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
18751        let ctx = workflow_context(vec![
18752            history_event(
18753                "SideEffectRecorded",
18754                json!({"sequence": 1, "result": first}),
18755            ),
18756            history_event(
18757                "SideEffectRecorded",
18758                json!({"sequence": 2, "result": second}),
18759            ),
18760        ]);
18761        let first: String = ctx
18762            .side_effect(|| panic!("first callback must not run"))
18763            .expect("first replay");
18764        let second: i32 = ctx
18765            .side_effect(|| panic!("second callback must not run"))
18766            .expect("second replay");
18767        assert_eq!(first, "first");
18768        assert_eq!(second, 29);
18769        ctx.ensure_history_consumed().expect("ordered history");
18770
18771        let reordered = workflow_context(vec![history_event(
18772            "VersionMarkerRecorded",
18773            json!({
18774                "sequence": 1,
18775                "change_id": "before-side-effect",
18776                "version": 1,
18777                "min_supported": 1,
18778                "max_supported": 1,
18779            }),
18780        )]);
18781        let error = reordered
18782            .side_effect(|| "new".to_string())
18783            .expect_err("command reordering must fail");
18784        assert!(matches!(
18785            error,
18786            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18787                if reason == "recorded_command_mismatch"
18788        ));
18789    }
18790
18791    #[test]
18792    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
18793        let ctx = workflow_context(Vec::new());
18794        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
18795        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
18796        assert!(ctx.patched("new-search").expect("patch"));
18797        ctx.deprecate_patch("new-search").expect("deprecate patch");
18798        let commands = ctx.take_commands().expect("commands");
18799        assert_eq!(commands.len(), 2);
18800        assert_eq!(commands[0]["type"], "record_version_marker");
18801        assert_eq!(commands[0]["version"], 2);
18802        assert_eq!(commands[1]["change_id"], "new-search");
18803
18804        let replay = workflow_context(vec![history_event(
18805            "VersionMarkerRecorded",
18806            json!({
18807                "sequence": 1,
18808                "change_id": "checkout-v2",
18809                "version": 2,
18810                "min_supported": 1,
18811                "max_supported": 2,
18812            }),
18813        )]);
18814        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
18815        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
18816        assert!(replay.take_commands().expect("commands").is_empty());
18817        replay.ensure_history_consumed().expect("history consumed");
18818    }
18819
18820    #[test]
18821    fn version_markers_reject_incompatible_or_malformed_history() {
18822        let incompatible = workflow_context(vec![history_event(
18823            "VersionMarkerRecorded",
18824            json!({
18825                "sequence": 1,
18826                "change_id": "checkout-v2",
18827                "version": 1,
18828                "min_supported": 1,
18829                "max_supported": 2,
18830            }),
18831        )]);
18832        let error = incompatible
18833            .get_version("checkout-v2", 2, 3)
18834            .expect_err("old version is unsupported");
18835        assert!(matches!(
18836            error,
18837            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18838                if reason == "version_marker_incompatible_range"
18839        ));
18840
18841        for (history, reason) in [
18842            (
18843                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
18844                "side_effect_result_missing",
18845            ),
18846            (
18847                vec![history_event(
18848                    "SideEffectRecorded",
18849                    json!({
18850                        "sequence": 1,
18851                        "result": {"codec": "avro", "blob": "not-base64"},
18852                    }),
18853                )],
18854                "side_effect_payload_incompatible",
18855            ),
18856            (
18857                vec![history_event(
18858                    "SideEffectRecorded",
18859                    json!({"sequence": 1, "result": {"unwrapped": true}}),
18860                )],
18861                "side_effect_payload_malformed",
18862            ),
18863            (
18864                vec![history_event(
18865                    "VersionMarkerRecorded",
18866                    json!({
18867                        "sequence": 1,
18868                        "change_id": "change",
18869                        "version": 1,
18870                        "min_supported": 2,
18871                        "max_supported": 1,
18872                    }),
18873                )],
18874                "version_marker_history_range_invalid",
18875            ),
18876        ] {
18877            let error = WorkflowState::new(
18878                history,
18879                "rust-workers".to_string(),
18880                DEFAULT_CODEC.to_string(),
18881                None,
18882            )
18883            .expect_err("malformed history must fail");
18884            assert!(matches!(
18885                error,
18886                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
18887                    if actual == reason
18888            ));
18889        }
18890    }
18891
18892    #[test]
18893    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
18894        let history = vec![history_event(
18895            "SearchAttributesUpserted",
18896            json!({
18897                "sequence": 1,
18898                "attributes": {"customer_tier": "gold"},
18899                "attribute_types": {"customer_tier": "keyword"},
18900                "merged": {"customer_tier": "gold"}
18901            }),
18902        )];
18903
18904        let matching = workflow_context(history.clone());
18905        matching
18906            .upsert_search_attributes(
18907                SearchAttributeUpdate::new()
18908                    .keyword("customer_tier", "gold")
18909                    .expect("keyword update"),
18910            )
18911            .expect("matching typed update must replay");
18912        matching
18913            .ensure_history_consumed()
18914            .expect("history consumed");
18915
18916        let changed_type = workflow_context(history.clone());
18917        let error = changed_type
18918            .upsert_search_attributes(
18919                SearchAttributeUpdate::new()
18920                    .string("customer_tier", "gold")
18921                    .expect("string update"),
18922            )
18923            .expect_err("same JSON value with a different declaration must be nondeterministic");
18924        let Error::NonDeterministicReplay(failure) = error else {
18925            panic!("typed identity drift must be a replay failure");
18926        };
18927        assert_eq!(failure.reason, "search_attribute_type_mismatch");
18928        assert_eq!(failure.sequence, Some(1));
18929
18930        let changed_value = workflow_context(history);
18931        let error = changed_value
18932            .upsert_search_attributes(
18933                SearchAttributeUpdate::new()
18934                    .keyword("customer_tier", "platinum")
18935                    .expect("keyword update"),
18936            )
18937            .expect_err("changed values must be nondeterministic");
18938        let Error::NonDeterministicReplay(failure) = error else {
18939            panic!("value drift must be a replay failure");
18940        };
18941        assert_eq!(failure.reason, "search_attribute_value_mismatch");
18942    }
18943
18944    #[test]
18945    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
18946        let history = vec![history_event(
18947            "SearchAttributesUpserted",
18948            json!({
18949                "sequence": 1,
18950                "attributes": {"customer_tier": "gold"},
18951                "merged": {"customer_tier": "gold"}
18952            }),
18953        )];
18954
18955        for update in [
18956            SearchAttributeUpdate::new()
18957                .keyword("customer_tier", "gold")
18958                .expect("keyword update"),
18959            SearchAttributeUpdate::new()
18960                .string("customer_tier", "gold")
18961                .expect("string update"),
18962        ] {
18963            let restarted = workflow_context(history.clone());
18964            restarted
18965                .upsert_search_attributes(update)
18966                .expect("legacy history constrains values but has unknown type identity");
18967            restarted
18968                .ensure_history_consumed()
18969                .expect("history consumed");
18970        }
18971    }
18972
18973    #[test]
18974    fn search_attribute_command_emits_canonical_types() {
18975        let ctx = workflow_context(Vec::new());
18976        ctx.upsert_search_attributes(
18977            SearchAttributeUpdate::new()
18978                .keyword("customer_tier", "gold")
18979                .expect("keyword update")
18980                .int("attempts", 3)
18981                .expect("int update")
18982                .delete("obsolete")
18983                .expect("delete update"),
18984        )
18985        .expect("valid search attributes");
18986
18987        assert_eq!(
18988            ctx.take_commands().expect("commands"),
18989            vec![json!({
18990                "type": "upsert_search_attributes",
18991                "attributes": {
18992                    "attempts": 3,
18993                    "customer_tier": "gold",
18994                    "obsolete": null
18995                },
18996                "attribute_types": {
18997                    "attempts": "int",
18998                    "customer_tier": "keyword"
18999                }
19000            })]
19001        );
19002    }
19003
19004    #[test]
19005    fn duplicate_side_effects_and_version_markers_are_rejected() {
19006        let duplicate_side_effect = WorkflowState::new(
19007            vec![
19008                history_event(
19009                    "SideEffectRecorded",
19010                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
19011                ),
19012                history_event(
19013                    "SideEffectRecorded",
19014                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
19015                ),
19016            ],
19017            "rust-workers".to_string(),
19018            DEFAULT_CODEC.to_string(),
19019            None,
19020        )
19021        .expect_err("duplicate side effect");
19022        assert!(matches!(
19023            duplicate_side_effect,
19024            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19025                if reason == "duplicate_side_effect_record"
19026        ));
19027
19028        let marker = |sequence| {
19029            history_event(
19030                "VersionMarkerRecorded",
19031                json!({
19032                    "sequence": sequence,
19033                    "change_id": "same-change",
19034                    "version": 1,
19035                    "min_supported": 1,
19036                    "max_supported": 1,
19037                }),
19038            )
19039        };
19040        let duplicate_marker = WorkflowState::new(
19041            vec![marker(1), marker(3)],
19042            "rust-workers".to_string(),
19043            DEFAULT_CODEC.to_string(),
19044            None,
19045        )
19046        .expect_err("duplicate marker");
19047        assert!(matches!(
19048            duplicate_marker,
19049            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19050                if reason == "duplicate_version_marker"
19051        ));
19052    }
19053
19054    #[test]
19055    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
19056        let mut state = WorkflowState::new(
19057            Vec::new(),
19058            "rust-workers".to_string(),
19059            DEFAULT_CODEC.to_string(),
19060            None,
19061        )
19062        .expect("workflow state");
19063        state.workflow_command_identity = "command-7".to_string();
19064        let context = WorkflowContext {
19065            state: Arc::new(Mutex::new(state)),
19066            cancellation_scope_id: "root".into(),
19067        };
19068        let item =
19069            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
19070
19071        context
19072            .append_workflow_stream("output", &[item], Some(10))
19073            .expect("append command");
19074        context
19075            .error_workflow_stream("output", "producer failed", None)
19076            .expect("error command");
19077        let commands = context.take_commands().expect("commands");
19078
19079        assert_eq!(commands[0]["type"], "record_side_effect");
19080        assert_eq!(
19081            commands[0]["workflow_stream"]["command_identity"],
19082            "command-7"
19083        );
19084        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
19085        assert_eq!(
19086            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19087            "dw-stream:command-7:0:0"
19088        );
19089        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
19090
19091        let recorded = history_event(
19092            "SideEffectRecorded",
19093            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
19094        );
19095        let mut replay_state = WorkflowState::new(
19096            vec![recorded],
19097            "rust-workers".to_string(),
19098            DEFAULT_CODEC.to_string(),
19099            None,
19100        )
19101        .expect("replay state");
19102        replay_state.workflow_command_identity = "command-7".to_string();
19103        let replay_context = WorkflowContext {
19104            state: Arc::new(Mutex::new(replay_state)),
19105            cancellation_scope_id: "root".into(),
19106        };
19107        replay_context
19108            .append_workflow_stream(
19109                "output",
19110                &[WorkflowStreamAppendItem::from_reference(
19111                    "s3://bucket/item.avro",
19112                )],
19113                Some(10),
19114            )
19115            .expect("replayed append");
19116        assert!(replay_context
19117            .take_commands()
19118            .expect("replayed commands")
19119            .is_empty());
19120    }
19121
19122    #[test]
19123    fn workflow_stream_authoring_requires_server_durable_command_identity() {
19124        let context = workflow_context(Vec::new());
19125        let error = context
19126            .append_workflow_stream(
19127                "output",
19128                &[WorkflowStreamAppendItem::from_reference(
19129                    "s3://bucket/item.avro",
19130                )],
19131                None,
19132            )
19133            .expect_err("stream append without durable command identity must fail closed");
19134
19135        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
19136        assert!(context.take_commands().expect("commands").is_empty());
19137    }
19138
19139    #[test]
19140    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
19141        let client = Client::builder("http://localhost:8080").build().unwrap();
19142        let mut worker = Worker::new(client, "rust-workers");
19143        worker.register_workflow("streams.worker", |ctx, _| async move {
19144            ctx.append_workflow_stream(
19145                "output",
19146                &[WorkflowStreamAppendItem::new(json!("hello"))?],
19147                None,
19148            )?;
19149            ctx.close_workflow_stream("output", None)?;
19150            Ok(json!("done"))
19151        });
19152        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
19153            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
19154            task.workflow_command_id = command_id.clone();
19155            let expected_identity = command_id
19156                .as_deref()
19157                .filter(|id| !id.is_empty())
19158                .unwrap_or(&task.task_id)
19159                .to_string();
19160            let commands = worker
19161                .execute_workflow_task(task)
19162                .expect("ordinary worker stream output");
19163            assert_eq!(commands.len(), 3);
19164            assert_eq!(
19165                commands[0]["workflow_stream"]["command_identity"],
19166                expected_identity
19167            );
19168            assert_eq!(
19169                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19170                format!("dw-stream:{expected_identity}:0:0")
19171            );
19172            assert_eq!(
19173                commands[1]["workflow_stream"]["command_identity"],
19174                expected_identity
19175            );
19176            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
19177            let history = commands[..2]
19178                .iter()
19179                .enumerate()
19180                .map(|(index, command)| {
19181                    history_event(
19182                        "SideEffectRecorded",
19183                        json!({"sequence":index + 1,"result":command["result"]}),
19184                    )
19185                })
19186                .collect();
19187            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
19188            replay.task_id = "replacement-task".to_string();
19189            let replayed = worker
19190                .execute_workflow_task(replay)
19191                .expect("replacement worker consumes recorded stream effects");
19192            assert_eq!(replayed.len(), 1);
19193            assert_eq!(replayed[0]["type"], "complete_workflow");
19194        }
19195        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
19196        missing.task_id.clear();
19197        assert!(matches!(
19198            worker.execute_workflow_task(missing),
19199            Err(Error::MissingWorkflowCommandIdentity)
19200        ));
19201    }
19202
19203    #[test]
19204    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
19205        fn worker(calls: Arc<AtomicUsize>) -> Worker {
19206            let client = Client::new("http://127.0.0.1:8080").expect("client");
19207            let mut worker = Worker::new(client, "rust-workers");
19208            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
19209                let calls = Arc::clone(&calls);
19210                async move {
19211                    let captured = ctx.side_effect(|| {
19212                        calls.fetch_add(1, Ordering::SeqCst);
19213                        "captured-once".to_string()
19214                    })?;
19215                    let version = ctx.get_version("cold-restart", 1, 2)?;
19216                    Ok(json!({"captured": captured, "version": version}))
19217                }
19218            });
19219            worker
19220        }
19221
19222        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
19223            WorkflowTask {
19224                task_id: "wft-side-effect-version".to_string(),
19225                workflow_command_id: None,
19226                workflow_id: Some("wf-side-effect-version".to_string()),
19227                run_id: Some("run-side-effect-version".to_string()),
19228                workflow_type: "rust.side-effect-version".to_string(),
19229                cancel_requested: false,
19230                payload_codec: DEFAULT_CODEC.to_string(),
19231                arguments: Some(
19232                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
19233                ),
19234                history_events,
19235                total_history_events: None,
19236                history_size_bytes: None,
19237                continue_as_new_recommended: None,
19238                history_budget_pressure: None,
19239                next_history_page_token: None,
19240                workflow_task_attempt: 1,
19241                workflow_signal_id: None,
19242                signal_name: None,
19243                signal_arguments: None,
19244                workflow_update_id: None,
19245                update_name: None,
19246                lease_owner: Some("rust-worker".to_string()),
19247            }
19248        }
19249
19250        let calls = Arc::new(AtomicUsize::new(0));
19251        let initial = worker(Arc::clone(&calls))
19252            .execute_workflow_task(task(Vec::new()))
19253            .expect("initial execution");
19254        assert_eq!(
19255            initial
19256                .iter()
19257                .map(|command| &command["type"])
19258                .collect::<Vec<_>>(),
19259            vec![
19260                "record_side_effect",
19261                "record_version_marker",
19262                "complete_workflow"
19263            ]
19264        );
19265        assert_eq!(calls.load(Ordering::SeqCst), 1);
19266
19267        let restarted = worker(Arc::clone(&calls));
19268        let replayed = restarted
19269            .execute_workflow_task(task(vec![
19270                history_event(
19271                    "SideEffectRecorded",
19272                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
19273                ),
19274                history_event(
19275                    "VersionMarkerRecorded",
19276                    json!({
19277                        "sequence": 2,
19278                        "change_id": "cold-restart",
19279                        "version": 2,
19280                        "min_supported": 1,
19281                        "max_supported": 2,
19282                    }),
19283                ),
19284            ]))
19285            .expect("cold replay");
19286        assert_eq!(replayed.len(), 1);
19287        assert_eq!(replayed[0]["type"], "complete_workflow");
19288        assert_eq!(calls.load(Ordering::SeqCst), 1);
19289    }
19290
19291    #[test]
19292    fn side_effect_replay_rejects_changed_rust_value_type() {
19293        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
19294        let ctx = workflow_context(vec![history_event(
19295            "SideEffectRecorded",
19296            json!({"sequence": 1, "result": result}),
19297        )]);
19298        let error = ctx
19299            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
19300            .expect_err("changed type must fail replay");
19301        assert!(matches!(
19302            error,
19303            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19304                if reason == "side_effect_type_mismatch"
19305        ));
19306    }
19307
19308    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
19309        vec![
19310            history_event(
19311                "ActivityScheduled",
19312                json!({
19313                    "sequence": 1,
19314                    "activity_type": "flaky",
19315                    "activity_execution_id": "act-1",
19316                    "activity": {
19317                        "id": "act-1",
19318                        "sequence": 1,
19319                        "type": "flaky",
19320                        "queue": "critical-activities",
19321                        "execution_mode": null,
19322                        "retry_policy": {
19323                            "snapshot_version": 1,
19324                            "max_attempts": 3,
19325                            "backoff_seconds": [2, 4],
19326                            "start_to_close_timeout": 30,
19327                            "schedule_to_start_timeout": 5,
19328                            "schedule_to_close_timeout": 90,
19329                            "heartbeat_timeout": 10,
19330                            "non_retryable_error_types": ["PermanentError"]
19331                        }
19332                    }
19333                }),
19334            ),
19335            history_event(
19336                "ActivityStarted",
19337                json!({
19338                    "sequence": 1,
19339                    "activity_type": "flaky",
19340                    "activity_execution_id": "act-1",
19341                    "activity_attempt_id": "attempt-1",
19342                    "attempt_number": 1
19343                }),
19344            ),
19345            history_event(
19346                "ActivityRetryScheduled",
19347                json!({
19348                    "sequence": 1,
19349                    "activity_type": "flaky",
19350                    "activity_execution_id": "act-1",
19351                    "activity_attempt_id": "attempt-1",
19352                    "attempt_number": 1,
19353                    "retry_after_attempt": 1,
19354                    "retry_backoff_seconds": 2,
19355                    "failure_category": "activity",
19356                    "exception_type": "TransientError"
19357                }),
19358            ),
19359            history_event(
19360                "ActivityStarted",
19361                json!({
19362                    "sequence": 1,
19363                    "activity_type": "flaky",
19364                    "activity_execution_id": "act-1",
19365                    "activity_attempt_id": "attempt-2",
19366                    "attempt_number": 2
19367                }),
19368            ),
19369            history_event(
19370                "ActivityCompleted",
19371                json!({
19372                    "sequence": 1,
19373                    "activity_type": "flaky",
19374                    "activity_execution_id": "act-1",
19375                    "activity_attempt_id": "attempt-2",
19376                    "attempt_number": 2,
19377                    "payload_codec": DEFAULT_CODEC,
19378                    "result": fixture_envelope(json!({"status":"recovered"}))
19379                }),
19380            ),
19381        ]
19382    }
19383
19384    fn retry_activity_options() -> ActivityOptions {
19385        ActivityOptions::new()
19386            .task_queue("critical-activities")
19387            .retry_policy(
19388                ActivityRetryPolicy::new(3)
19389                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
19390                    .non_retryable_error_type("PermanentError"),
19391            )
19392            .start_to_close_timeout(Duration::from_secs(30))
19393            .schedule_to_start_timeout(Duration::from_secs(5))
19394            .schedule_to_close_timeout(Duration::from_secs(90))
19395            .heartbeat_timeout(Duration::from_secs(10))
19396    }
19397
19398    #[test]
19399    fn fixed_avro_value_round_trips_json_values() {
19400        let value = json!({"greeting": "hello", "count": 3, "ok": true});
19401        let envelope = PayloadEnvelope::avro(&value).expect("encode");
19402        assert_eq!(envelope.codec, DEFAULT_CODEC);
19403        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
19404    }
19405
19406    #[tokio::test]
19407    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
19408        let client = Client::new("http://127.0.0.1:8080").expect("client");
19409        let mut worker = Worker::new(client, "rust-workers");
19410        worker.register_typed_workflow(
19411            "typed.contract.workflow",
19412            |_ctx, input: TypedContract| async move { Ok(input) },
19413        );
19414        worker.register_typed_activity(
19415            "typed.contract.activity",
19416            |_ctx, input: TypedContract| async move { Ok(input) },
19417        );
19418
19419        let expected = typed_contract();
19420        let arguments = AvroValue::Array(vec![
19421            AvroValue::from_serialize(&expected).expect("typed request")
19422        ]);
19423        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
19424        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
19425        workflow.arguments = Some(envelope.clone());
19426        let commands = worker
19427            .execute_workflow_task(workflow)
19428            .expect("typed workflow task");
19429        let workflow_result: TypedContract =
19430            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19431                .expect("workflow result envelope")
19432                .deserialize()
19433                .expect("workflow result type");
19434        assert_eq!(workflow_result, expected);
19435
19436        let activity = ActivityTask {
19437            task_id: "typed-contract-activity".to_string(),
19438            activity_attempt_id: Some("typed-contract-attempt".to_string()),
19439            attempt_id: None,
19440            activity_type: "typed.contract.activity".to_string(),
19441            payload_codec: DEFAULT_CODEC.to_string(),
19442            arguments: Some(envelope),
19443            attempt_number: 1,
19444            lease_owner: Some("rust-worker".to_string()),
19445        };
19446        let activity_result: TypedContract = worker
19447            .execute_activity_task(activity)
19448            .await
19449            .expect("typed activity task")
19450            .deserialize()
19451            .expect("activity result type");
19452        assert_eq!(activity_result, expected);
19453    }
19454
19455    #[tokio::test]
19456    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
19457        let client = Client::new("http://127.0.0.1:8080").expect("client");
19458        let mut worker = Worker::new(client, "rust-workers");
19459        worker.register_typed_workflow(
19460            "typed.shape.workflow",
19461            |_ctx, input: TypedContract| async move { Ok(input) },
19462        );
19463        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
19464            Ok(f64::NAN)
19465        });
19466
19467        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
19468        workflow.arguments = Some(
19469            encode_typed_envelope(
19470                &AvroValue::Array(vec![
19471                    AvroValue::String("first".to_string()),
19472                    AvroValue::String("second".to_string()),
19473                ]),
19474                DEFAULT_CODEC,
19475            )
19476            .expect("malformed typed arguments"),
19477        );
19478        let commands = worker
19479            .execute_workflow_task(workflow)
19480            .expect("shape mismatch becomes a workflow failure");
19481        let message = commands[0]["message"].as_str().expect("failure message");
19482        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
19483        assert!(message.contains(type_name::<TypedContract>()));
19484        assert!(message.contains("task carried 2 arguments"));
19485
19486        let activity = ActivityTask {
19487            task_id: "typed-unsupported-activity".to_string(),
19488            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
19489            attempt_id: None,
19490            activity_type: "typed.unsupported.activity".to_string(),
19491            payload_codec: DEFAULT_CODEC.to_string(),
19492            arguments: Some(
19493                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19494                    .expect("unit arguments"),
19495            ),
19496            attempt_number: 1,
19497            lease_owner: Some("rust-worker".to_string()),
19498        };
19499        let Error::HandlerType {
19500            handler_kind,
19501            handler_name,
19502            value_kind,
19503            rust_type,
19504            message,
19505        } = worker
19506            .execute_activity_task(activity)
19507            .await
19508            .expect_err("non-finite handler output must fail")
19509        else {
19510            panic!("expected contextual handler type failure");
19511        };
19512        assert_eq!(handler_kind, HandlerKind::Activity);
19513        assert_eq!(handler_name, "typed.unsupported.activity");
19514        assert_eq!(value_kind, HandlerValueKind::Result);
19515        assert_eq!(rust_type, type_name::<f64>());
19516        assert!(message.contains("non_finite_float"));
19517    }
19518
19519    #[tokio::test]
19520    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
19521        #[derive(Clone, Default)]
19522        struct State {
19523            observed: Option<TypedContract>,
19524        }
19525
19526        let client = Client::new("http://127.0.0.1:8080").expect("client");
19527        let mut worker = Worker::new(client, "rust-workers");
19528        worker.register_typed_replayed_workflow(
19529            "typed.contract.replayed",
19530            State::default,
19531            |ctx, input: TypedContract, state| async move {
19532                let result: TypedContract =
19533                    ctx.activity_typed("typed.contract.activity", input).await?;
19534                state.update(|current| current.observed = Some(result.clone()))?;
19535                Ok(result)
19536            },
19537        );
19538        worker.register_replayed_query::<State, _, _>(
19539            "typed.contract.replayed",
19540            "observed",
19541            |_ctx, state, _args| async move {
19542                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
19543            },
19544        );
19545
19546        let expected = typed_contract();
19547        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
19548        let workflow_arguments =
19549            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
19550                .expect("workflow arguments");
19551        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
19552        let task = QueryTask {
19553            query_task_id: "typed-replay-query".to_string(),
19554            query_task_attempt: 1,
19555            lease_owner: Some("rust-worker".to_string()),
19556            workflow_id: Some("typed-replay".to_string()),
19557            run_id: Some("typed-replay-run".to_string()),
19558            workflow_type: "typed.contract.replayed".to_string(),
19559            query_name: "observed".to_string(),
19560            payload_codec: DEFAULT_CODEC.to_string(),
19561            workflow_arguments: Some(workflow_arguments),
19562            query_arguments: Some(
19563                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19564                    .expect("query arguments"),
19565            ),
19566            history_events: vec![
19567                history_event(
19568                    "ActivityScheduled",
19569                    json!({
19570                        "sequence": 1,
19571                        "activity_type": "typed.contract.activity"
19572                    }),
19573                ),
19574                history_event(
19575                    "ActivityCompleted",
19576                    json!({
19577                        "sequence": 1,
19578                        "activity_type": "typed.contract.activity",
19579                        "payload_codec": DEFAULT_CODEC,
19580                        "result": result
19581                    }),
19582                ),
19583            ],
19584            history_export: None,
19585            run_status: Some("completed".to_string()),
19586        };
19587
19588        assert_eq!(
19589            worker
19590                .execute_query_task(task)
19591                .await
19592                .expect("typed replay query")
19593                .deserialize::<i64>()
19594                .expect("query result"),
19595            expected.signed
19596        );
19597    }
19598
19599    #[tokio::test]
19600    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
19601        let client = Client::new("http://127.0.0.1:8080").expect("client");
19602        let mut worker = Worker::new(client, "rust-workers");
19603        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
19604        worker
19605            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
19606        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
19607            Ok(input)
19608        });
19609        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
19610            Ok(input)
19611        });
19612        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
19613            Ok(AvroValue::Array(
19614                ctx.wait_signal_avro_value("changed").await?,
19615            ))
19616        });
19617
19618        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
19619        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
19620
19621        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
19622        workflow.arguments = Some(envelope.clone());
19623        let commands = worker
19624            .execute_workflow_task(workflow)
19625            .expect("typed workflow task");
19626        assert_eq!(commands[0]["type"], "complete_workflow");
19627        assert_eq!(
19628            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19629                .expect("typed workflow result"),
19630            arguments
19631        );
19632
19633        let activity = ActivityTask {
19634            task_id: "activity-typed".to_string(),
19635            activity_attempt_id: Some("attempt-typed".to_string()),
19636            attempt_id: None,
19637            activity_type: "typed.activity".to_string(),
19638            payload_codec: DEFAULT_CODEC.to_string(),
19639            arguments: Some(envelope.clone()),
19640            attempt_number: 1,
19641            lease_owner: Some("rust-worker".to_string()),
19642        };
19643        assert_eq!(
19644            worker
19645                .execute_activity_task(activity)
19646                .await
19647                .expect("typed activity result"),
19648            arguments
19649        );
19650
19651        let query = QueryTask {
19652            query_task_id: "query-typed".to_string(),
19653            query_task_attempt: 1,
19654            lease_owner: Some("rust-worker".to_string()),
19655            workflow_id: Some("typed-1".to_string()),
19656            run_id: Some("run-typed".to_string()),
19657            workflow_type: "typed.echo".to_string(),
19658            query_name: "inspect".to_string(),
19659            payload_codec: DEFAULT_CODEC.to_string(),
19660            workflow_arguments: Some(
19661                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19662                    .expect("workflow input"),
19663            ),
19664            query_arguments: Some(envelope.clone()),
19665            history_events: Vec::new(),
19666            history_export: None,
19667            run_status: Some("running".to_string()),
19668        };
19669        assert_eq!(
19670            worker
19671                .execute_query_task(query)
19672                .await
19673                .expect("typed query result"),
19674            arguments
19675        );
19676
19677        let mut update = workflow_task(
19678            "typed.echo",
19679            vec![history_event(
19680                "UpdateAccepted",
19681                json!({
19682                    "update_id": "update-typed",
19683                    "update_name": "replace",
19684                    "arguments": envelope.clone(),
19685                }),
19686            )],
19687            DEFAULT_CODEC,
19688        );
19689        update.workflow_update_id = Some("update-typed".to_string());
19690        update.update_name = Some("replace".to_string());
19691        let commands = worker
19692            .execute_workflow_task(update)
19693            .expect("typed update task");
19694        assert_eq!(commands[0]["type"], "complete_update");
19695        assert_eq!(
19696            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19697                .expect("typed update result"),
19698            arguments
19699        );
19700
19701        let mut signal = workflow_task(
19702            "typed.signal",
19703            vec![history_event(
19704                "SignalReceived",
19705                json!({
19706                    "signal_id": "signal-typed",
19707                    "signal_name": "changed",
19708                    "arguments": envelope.clone(),
19709                }),
19710            )],
19711            DEFAULT_CODEC,
19712        );
19713        signal.workflow_signal_id = Some("signal-typed".to_string());
19714        signal.signal_name = Some("changed".to_string());
19715        signal.signal_arguments = Some(envelope);
19716        let commands = worker
19717            .execute_workflow_task(signal)
19718            .expect("typed signal resume");
19719        assert_eq!(
19720            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19721                .expect("typed signal result"),
19722            arguments
19723        );
19724    }
19725
19726    #[tokio::test]
19727    async fn typed_helpers_never_parse_json_inspection_projection() {
19728        let collision_values = projection_collision_probe();
19729        let expected = AvroValue::Array(collision_values.clone());
19730        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
19731
19732        let activity_context = workflow_context_with_codec(
19733            vec![history_event(
19734                "ActivityCompleted",
19735                json!({
19736                    "sequence": 1,
19737                    "activity_type": "collision.activity",
19738                    "payload_codec": DEFAULT_CODEC,
19739                    "result": envelope.clone(),
19740                }),
19741            )],
19742            DEFAULT_CODEC,
19743        );
19744        assert_eq!(
19745            activity_context
19746                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
19747                .await
19748                .expect("typed activity collision result"),
19749            expected
19750        );
19751
19752        let signal_context = workflow_context_with_codec(
19753            vec![
19754                history_event(
19755                    "SignalWaitOpened",
19756                    json!({"sequence": 1, "signal_name": "collision"}),
19757                ),
19758                history_event(
19759                    "SignalApplied",
19760                    json!({
19761                        "sequence": 1,
19762                        "signal_name": "collision",
19763                        "payload_codec": DEFAULT_CODEC,
19764                        "value": envelope.clone(),
19765                    }),
19766                ),
19767            ],
19768            DEFAULT_CODEC,
19769        );
19770        assert_eq!(
19771            signal_context
19772                .wait_signal_avro_value("collision")
19773                .await
19774                .expect("typed signal collision arguments"),
19775            collision_values
19776        );
19777
19778        let child_context = workflow_context_with_codec(
19779            vec![
19780                history_event(
19781                    "ChildWorkflowScheduled",
19782                    json!({
19783                        "sequence": 1,
19784                        "child_workflow_instance_id": "collision-child",
19785                        "child_workflow_run_id": "collision-run",
19786                        "child_workflow_type": "collision.child",
19787                    }),
19788                ),
19789                history_event(
19790                    "ChildRunCompleted",
19791                    json!({
19792                        "sequence": 1,
19793                        "child_workflow_instance_id": "collision-child",
19794                        "child_workflow_run_id": "collision-run",
19795                        "child_workflow_type": "collision.child",
19796                        "payload_codec": DEFAULT_CODEC,
19797                        "result": envelope,
19798                    }),
19799                ),
19800            ],
19801            DEFAULT_CODEC,
19802        );
19803        let child = child_context
19804            .start_child_workflow_avro_value(
19805                "collision.child",
19806                ChildWorkflowOptions::new("collision-workers"),
19807                AvroValue::Array(Vec::new()),
19808            )
19809            .await
19810            .expect("typed child collision result");
19811        assert_eq!(child.result, expected);
19812    }
19813
19814    #[tokio::test]
19815    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
19816        let client = Client::new("http://127.0.0.1:8080").expect("client");
19817        let mut worker = Worker::new(client, "rust-workers");
19818        worker.register_replayed_workflow_avro_value(
19819            "typed.replayed",
19820            || (),
19821            |_ctx, input, _state| async move { Ok(input) },
19822        );
19823        worker.register_replayed_query_avro_value::<(), _, _>(
19824            "typed.replayed",
19825            "inspect",
19826            |ctx, _state, args| async move {
19827                let mut signals = ctx.signals_avro_value("collision");
19828                let signal = signals
19829                    .pop()
19830                    .map(AvroValue::Array)
19831                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
19832                Ok(AvroValue::Array(vec![
19833                    ctx.workflow_input_avro_value().clone(),
19834                    signal,
19835                    args,
19836                ]))
19837            },
19838        );
19839        let arguments = AvroValue::Array(projection_collision_probe());
19840        let signal_arguments =
19841            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
19842        let task = QueryTask {
19843            query_task_id: "query-typed-replay".to_string(),
19844            query_task_attempt: 1,
19845            lease_owner: Some("rust-worker".to_string()),
19846            workflow_id: Some("typed-replay".to_string()),
19847            run_id: Some("run-typed-replay".to_string()),
19848            workflow_type: "typed.replayed".to_string(),
19849            query_name: "inspect".to_string(),
19850            payload_codec: DEFAULT_CODEC.to_string(),
19851            workflow_arguments: Some(
19852                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
19853            ),
19854            query_arguments: Some(
19855                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
19856            ),
19857            history_events: vec![history_event(
19858                "SignalReceived",
19859                json!({
19860                    "signal_id": "collision-signal",
19861                    "signal_name": "collision",
19862                    "workflow_sequence": 1,
19863                    "payload_codec": DEFAULT_CODEC,
19864                    "arguments": signal_arguments,
19865                }),
19866            )],
19867            history_export: None,
19868            run_status: Some("completed".to_string()),
19869        };
19870
19871        assert_eq!(
19872            worker
19873                .execute_query_task(task)
19874                .await
19875                .expect("typed replay query"),
19876            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
19877        );
19878    }
19879
19880    #[test]
19881    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
19882        let value = BTreeMap::from([(1_i32, "integer key")]);
19883        let error = PayloadEnvelope::avro(&value)
19884            .expect_err("integer map keys must fail")
19885            .to_string();
19886
19887        assert!(error.contains("invalid_map_key"));
19888    }
19889
19890    #[test]
19891    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
19892        let envelope = PayloadEnvelope {
19893            codec: "json".to_string(),
19894            blob: r#"{"greeting":"hello"}"#.to_string(),
19895        };
19896
19897        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
19898        let diagnostic = error.to_string();
19899        assert!(diagnostic.contains("unsupported_payload_codec"));
19900        assert!(diagnostic.contains("codec=\"avro\""));
19901        assert!(diagnostic.contains("HTTP document transport"));
19902    }
19903
19904    #[test]
19905    fn untagged_json_payload_value_fails_closed() {
19906        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
19907            .expect_err("untagged JSON payload values must fail");
19908        let diagnostic = error.to_string();
19909        assert!(diagnostic.contains("unsupported_payload_codec"));
19910        assert!(diagnostic.contains("untagged durable payload"));
19911        assert!(diagnostic.contains("HTTP document transport"));
19912    }
19913
19914    #[test]
19915    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
19916        let envelope = PayloadEnvelope {
19917            codec: DEFAULT_CODEC.to_string(),
19918            blob: BASE64.encode([0x01]),
19919        };
19920
19921        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
19922        assert!(error.to_string().contains("invalid_payload_framing"));
19923    }
19924
19925    #[tokio::test]
19926    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
19927        let server = MockWorkerServer::start();
19928        let client = Client::builder(server.base_url())
19929            .timeout(Duration::from_secs(2))
19930            .build()
19931            .expect("client");
19932        let invalid_commands = [
19933            json!({
19934                "type": "complete_workflow",
19935                "result": {"codec": "json", "blob": null}
19936            }),
19937            json!({
19938                "type": "schedule_activity",
19939                "arguments": {"codec": "yaml", "blob": "ignored"}
19940            }),
19941            json!({
19942                "type": "start_child_workflow",
19943                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
19944            }),
19945            json!({"type": "continue_as_new", "arguments": []}),
19946            json!({"type": "complete_update"}),
19947            json!({"type": "record_side_effect", "result": null}),
19948            json!({
19949                "type": "start_service_operation",
19950                "payload_codec": DEFAULT_CODEC,
19951                "request_payload": "raw-avro-bytes"
19952            }),
19953        ];
19954
19955        for command in invalid_commands {
19956            let error = client
19957                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
19958                .await
19959                .expect_err("invalid durable payload must fail locally");
19960            let diagnostic = error.to_string();
19961            assert!(
19962                diagnostic.contains("unsupported_payload_codec")
19963                    || diagnostic.contains("invalid_payload_envelope")
19964                    || diagnostic.contains("untagged durable payload"),
19965                "unexpected validation diagnostic: {diagnostic}"
19966            );
19967        }
19968
19969        assert_eq!(
19970            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
19971            0,
19972            "invalid command payloads must not reach HTTP transport"
19973        );
19974    }
19975
19976    #[test]
19977    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
19978        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
19979        let commands = [
19980            json!({"type": "complete_workflow", "result": envelope.clone()}),
19981            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
19982            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
19983            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
19984            json!({"type": "complete_update", "result": envelope.clone()}),
19985            json!({"type": "record_side_effect", "result": envelope.clone()}),
19986            json!({
19987                "type": "start_service_operation",
19988                "payload_codec": DEFAULT_CODEC,
19989                "request_payload": envelope.clone()
19990            }),
19991            json!({
19992                "type": "complete_workflow",
19993                "result": envelope,
19994                "metadata": {
19995                    "codec": "json",
19996                    "payload_codec": "customer-codec",
19997                    "result": {"codec": "yaml", "blob": null}
19998                }
19999            }),
20000        ];
20001
20002        validate_workflow_task_commands(&commands)
20003            .expect("customer metadata must not become a protocol codec declaration");
20004    }
20005
20006    #[test]
20007    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
20008        assert_eq!(
20009            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
20010            AvroValue::Array(Vec::new())
20011        );
20012        assert_eq!(
20013            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
20014            AvroValue::Array(Vec::new())
20015        );
20016
20017        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
20018        signal.signal_name = Some("empty-signal".to_string());
20019        signal.signal_arguments = None;
20020        let decoded = decode_resume_signal(&signal)
20021            .expect("valid Avro signal")
20022            .expect("named signal resumes the workflow");
20023        assert!(decoded.arguments.is_empty());
20024    }
20025
20026    #[tokio::test]
20027    async fn malformed_task_level_codecs_become_pre_handler_failures() {
20028        let client = Client::new("http://127.0.0.1:8080").expect("client");
20029        let mut worker = Worker::new(client, "rust-workers");
20030        let handler_calls = Arc::new(AtomicUsize::new(0));
20031
20032        let calls = Arc::clone(&handler_calls);
20033        worker.register_workflow("codec.workflow", move |_ctx, _args| {
20034            calls.fetch_add(1, Ordering::SeqCst);
20035            async move { Ok(Value::Null) }
20036        });
20037        let calls = Arc::clone(&handler_calls);
20038        worker.register_activity("codec.activity", move |_ctx, _args| {
20039            calls.fetch_add(1, Ordering::SeqCst);
20040            async move { Ok(Value::Null) }
20041        });
20042        let calls = Arc::clone(&handler_calls);
20043        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20044            calls.fetch_add(1, Ordering::SeqCst);
20045            async move { Ok(Value::Null) }
20046        });
20047
20048        let mut failures = Vec::new();
20049        for codec_case in [
20050            InvalidTaskPayloadCodec::Missing,
20051            InvalidTaskPayloadCodec::Null,
20052            InvalidTaskPayloadCodec::NonString,
20053        ] {
20054            let mut workflow = json!({
20055                "task_id": format!("workflow-{}", codec_case.label()),
20056                "workflow_type": "codec.workflow"
20057            });
20058            codec_case.apply(&mut workflow);
20059            match serde_json::from_value::<WorkflowTask>(workflow) {
20060                Ok(task) => match worker.execute_workflow_task(task) {
20061                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
20062                    outcome => failures.push(format!(
20063                        "workflow {} codec returned {outcome:?}",
20064                        codec_case.label()
20065                    )),
20066                },
20067                Err(error) => failures.push(format!(
20068                    "workflow {} codec failed transport deserialization: {error}",
20069                    codec_case.label()
20070                )),
20071            }
20072
20073            let mut activity = json!({
20074                "task_id": format!("activity-{}", codec_case.label()),
20075                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
20076                "activity_type": "codec.activity",
20077                "attempt_number": 1
20078            });
20079            codec_case.apply(&mut activity);
20080            match serde_json::from_value::<ActivityTask>(activity) {
20081                Ok(task) => match worker.execute_activity_task(task).await {
20082                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
20083                    outcome => failures.push(format!(
20084                        "activity {} codec returned {outcome:?}",
20085                        codec_case.label()
20086                    )),
20087                },
20088                Err(error) => failures.push(format!(
20089                    "activity {} codec failed transport deserialization: {error}",
20090                    codec_case.label()
20091                )),
20092            }
20093
20094            let mut query = json!({
20095                "query_task_id": format!("query-{}", codec_case.label()),
20096                "workflow_type": "codec.workflow",
20097                "query_name": "known"
20098            });
20099            codec_case.apply(&mut query);
20100            match serde_json::from_value::<QueryTask>(query) {
20101                Ok(task) => match worker.execute_query_task(task).await {
20102                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
20103                    outcome => failures.push(format!(
20104                        "query {} codec returned {outcome:?}",
20105                        codec_case.label()
20106                    )),
20107                },
20108                Err(error) => failures.push(format!(
20109                    "query {} codec failed transport deserialization: {error}",
20110                    codec_case.label()
20111                )),
20112            }
20113        }
20114
20115        assert!(failures.is_empty(), "{}", failures.join("\n"));
20116        assert_eq!(
20117            handler_calls.load(Ordering::SeqCst),
20118            0,
20119            "invalid task codecs must not invoke a handler"
20120        );
20121    }
20122
20123    #[tokio::test]
20124    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
20125        for codec_case in [
20126            InvalidTaskPayloadCodec::Missing,
20127            InvalidTaskPayloadCodec::Null,
20128            InvalidTaskPayloadCodec::NonString,
20129        ] {
20130            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
20131            let client = Client::builder(server.base_url())
20132                .timeout(Duration::from_secs(2))
20133                .build()
20134                .expect("client");
20135            let mut worker = Worker::new(client, "rust-workers")
20136                .worker_id("codec-worker")
20137                .poll_timeout(Duration::from_millis(10));
20138            let handler_calls = Arc::new(AtomicUsize::new(0));
20139
20140            let calls = Arc::clone(&handler_calls);
20141            worker.register_workflow("codec.workflow", move |_ctx, _args| {
20142                calls.fetch_add(1, Ordering::SeqCst);
20143                async move { Ok(Value::Null) }
20144            });
20145            let calls = Arc::clone(&handler_calls);
20146            worker.register_activity("codec.activity", move |_ctx, _args| {
20147                calls.fetch_add(1, Ordering::SeqCst);
20148                async move { Ok(Value::Null) }
20149            });
20150            let calls = Arc::clone(&handler_calls);
20151            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20152                calls.fetch_add(1, Ordering::SeqCst);
20153                async move { Ok(Value::Null) }
20154            });
20155
20156            assert_eq!(
20157                worker.run_once().await.expect("invalid tasks are settled"),
20158                3,
20159                "all {} codec tasks must be handled",
20160                codec_case.label()
20161            );
20162            assert_eq!(
20163                handler_calls.load(Ordering::SeqCst),
20164                0,
20165                "{} task codecs must fail before every handler",
20166                codec_case.label()
20167            );
20168
20169            for path in [
20170                "/api/worker/workflow-tasks/codec-workflow/fail",
20171                "/api/worker/activity-tasks/codec-activity/fail",
20172                "/api/worker/query-tasks/codec-query/fail",
20173            ] {
20174                let body = server.request_body(path);
20175                assert!(
20176                    body["failure"]["message"]
20177                        .as_str()
20178                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
20179                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
20180                    codec_case.label()
20181                );
20182            }
20183            assert_eq!(
20184                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
20185                    ["reason"],
20186                "query_payload_decode_failed"
20187            );
20188            for path in [
20189                "/api/worker/workflow-tasks/codec-workflow/complete",
20190                "/api/worker/activity-tasks/codec-activity/complete",
20191                "/api/worker/query-tasks/codec-query/complete",
20192            ] {
20193                assert_eq!(
20194                    server.request_count(path),
20195                    0,
20196                    "invalid {} codec task reached {path}",
20197                    codec_case.label()
20198                );
20199            }
20200        }
20201    }
20202
20203    #[tokio::test]
20204    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
20205        let client = Client::new("http://127.0.0.1:8080").expect("client");
20206        let mut worker = Worker::new(client, "rust-workers");
20207        let handler_calls = Arc::new(AtomicUsize::new(0));
20208
20209        let calls = Arc::clone(&handler_calls);
20210        worker.register_workflow("codec.workflow", move |_ctx, _args| {
20211            calls.fetch_add(1, Ordering::SeqCst);
20212            async move { Ok(Value::Null) }
20213        });
20214        let calls = Arc::clone(&handler_calls);
20215        worker.register_activity("codec.activity", move |_ctx, _args| {
20216            calls.fetch_add(1, Ordering::SeqCst);
20217            async move { Ok(Value::Null) }
20218        });
20219        let calls = Arc::clone(&handler_calls);
20220        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
20221            calls.fetch_add(1, Ordering::SeqCst);
20222            async move { Ok(Value::Null) }
20223        });
20224        let calls = Arc::clone(&handler_calls);
20225        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20226            calls.fetch_add(1, Ordering::SeqCst);
20227            async move { Ok(Value::Null) }
20228        });
20229
20230        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20231        workflow.payload_codec = "json".to_string();
20232        workflow.arguments = None;
20233        let error = worker
20234            .execute_workflow_task(workflow)
20235            .expect_err("task codec must be checked before workflow invocation");
20236        assert!(error.to_string().contains("unsupported_payload_codec"));
20237
20238        let activity = ActivityTask {
20239            task_id: "activity-invalid-codec".to_string(),
20240            activity_attempt_id: None,
20241            attempt_id: None,
20242            activity_type: "codec.activity".to_string(),
20243            payload_codec: "unknown".to_string(),
20244            arguments: None,
20245            attempt_number: 1,
20246            lease_owner: None,
20247        };
20248        let error = worker
20249            .execute_activity_task(activity)
20250            .await
20251            .expect_err("task codec must be checked before activity invocation");
20252        assert!(error.to_string().contains("unsupported_payload_codec"));
20253
20254        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20255        update.workflow_update_id = Some("update-invalid-codec".to_string());
20256        update.update_name = Some("known".to_string());
20257        update.history_events.push(history_event(
20258            "UpdateAccepted",
20259            json!({
20260                "update_id": "update-invalid-codec",
20261                "update_name": "known",
20262                "arguments": {"codec": "json", "blob": null}
20263            }),
20264        ));
20265        let error = worker
20266            .execute_workflow_task(update)
20267            .expect_err("nested update codec must be checked before handler lookup");
20268        assert!(error.to_string().contains("unsupported_payload_codec"));
20269
20270        let query: QueryTask = serde_json::from_value(json!({
20271            "query_task_id": "query-invalid-codec",
20272            "workflow_type": "codec.workflow",
20273            "query_name": "known",
20274            "payload_codec": DEFAULT_CODEC,
20275            "workflow_arguments": null,
20276            "query_arguments": null,
20277            "history_export": {
20278                "payloads": {"codec": DEFAULT_CODEC},
20279                "signals": [{
20280                    "name": "empty",
20281                    "payload_codec": "json",
20282                    "arguments": null
20283                }]
20284            }
20285        }))
20286        .expect("query task");
20287        let failure = worker
20288            .execute_query_task(query)
20289            .await
20290            .expect_err("exported signal codec must be checked before query invocation");
20291        assert_eq!(failure.reason, "query_payload_decode_failed");
20292        assert!(failure.message.contains("unsupported_payload_codec"));
20293
20294        let exported_history: QueryTask = serde_json::from_value(json!({
20295            "query_task_id": "query-invalid-history-codec",
20296            "workflow_type": "codec.workflow",
20297            "query_name": "known",
20298            "payload_codec": DEFAULT_CODEC,
20299            "history_export": {
20300                "payloads": {"codec": DEFAULT_CODEC},
20301                "history_events": [{
20302                    "type": "ActivityCompleted",
20303                    "payload": {"payload_codec": "unknown", "result": null}
20304                }]
20305            }
20306        }))
20307        .expect("query task");
20308        let failure = worker
20309            .execute_query_task(exported_history)
20310            .await
20311            .expect_err("exported history codec must be checked before query invocation");
20312        assert_eq!(failure.reason, "query_payload_decode_failed");
20313        assert!(failure.message.contains("unsupported_payload_codec"));
20314        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
20315
20316        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
20317        unknown_workflow.arguments = None;
20318        unknown_workflow.history_events.push(history_event(
20319            "SignalReceived",
20320            json!({
20321                "signal_name": "empty",
20322                "payload_codec": "json",
20323                "arguments": null
20324            }),
20325        ));
20326        let error = worker
20327            .execute_workflow_task(unknown_workflow)
20328            .expect_err("history codec must precede unknown workflow outcome");
20329        assert!(error.to_string().contains("unsupported_payload_codec"));
20330
20331        let unknown_activity = ActivityTask {
20332            task_id: "activity-unknown".to_string(),
20333            activity_attempt_id: None,
20334            attempt_id: None,
20335            activity_type: "missing".to_string(),
20336            payload_codec: "json".to_string(),
20337            arguments: None,
20338            attempt_number: 1,
20339            lease_owner: None,
20340        };
20341        let error = worker
20342            .execute_activity_task(unknown_activity)
20343            .await
20344            .expect_err("codec must precede unknown activity outcome");
20345        assert!(error.to_string().contains("unsupported_payload_codec"));
20346
20347        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20348        unknown_update.payload_codec = "json".to_string();
20349        unknown_update.arguments = None;
20350        unknown_update.workflow_update_id = Some("update-unknown".to_string());
20351        unknown_update.update_name = Some("missing".to_string());
20352        let error = worker
20353            .execute_workflow_task(unknown_update)
20354            .expect_err("codec must precede fail_update shortcut");
20355        assert!(error.to_string().contains("unsupported_payload_codec"));
20356
20357        let unknown_query: QueryTask = serde_json::from_value(json!({
20358            "query_task_id": "query-unknown",
20359            "workflow_type": "missing",
20360            "query_name": "missing",
20361            "payload_codec": "json",
20362            "workflow_arguments": null,
20363            "query_arguments": null
20364        }))
20365        .expect("query task");
20366        let failure = worker
20367            .execute_query_task(unknown_query)
20368            .await
20369            .expect_err("codec must precede unknown query outcome");
20370        assert_eq!(failure.reason, "query_payload_decode_failed");
20371        assert!(failure.message.contains("unsupported_payload_codec"));
20372    }
20373
20374    #[tokio::test]
20375    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
20376        let client = Client::new("http://127.0.0.1:8080").expect("client");
20377        let worker = Worker::new(client, "rust-workers");
20378
20379        for event_type in ["SignalReceived", "SignalApplied"] {
20380            for (payload_field, codec) in [
20381                ("value", "json"),
20382                ("input", "unknown"),
20383                ("arguments", "json"),
20384            ] {
20385                let payload = json!({
20386                    "signal_name": "empty",
20387                    payload_field: {"codec": codec, "blob": null}
20388                });
20389                let workflow = workflow_task(
20390                    "missing",
20391                    vec![history_event(event_type, payload.clone())],
20392                    DEFAULT_CODEC,
20393                );
20394                let error = worker
20395                    .execute_workflow_task(workflow)
20396                    .expect_err("signal payload codec must precede unknown workflow outcome");
20397                assert!(
20398                    error.to_string().contains("unsupported_payload_codec"),
20399                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
20400                );
20401
20402                let query: QueryTask = serde_json::from_value(json!({
20403                    "query_task_id": format!("query-{event_type}-{payload_field}"),
20404                    "workflow_type": "missing",
20405                    "query_name": "missing",
20406                    "payload_codec": DEFAULT_CODEC,
20407                    "workflow_arguments": null,
20408                    "query_arguments": null,
20409                    "history_events": [{
20410                        "event_type": event_type,
20411                        "payload": payload
20412                    }]
20413                }))
20414                .expect("query task");
20415                let failure = worker
20416                    .execute_query_task(query)
20417                    .await
20418                    .expect_err("signal payload codec must precede unknown query outcome");
20419                assert_eq!(
20420                    failure.reason, "query_payload_decode_failed",
20421                    "{event_type}.{payload_field} returned an unrelated query outcome"
20422                );
20423                assert!(
20424                    failure.message.contains("unsupported_payload_codec"),
20425                    "{event_type}.{payload_field} returned an unrelated query error: {}",
20426                    failure.message
20427                );
20428            }
20429        }
20430    }
20431
20432    #[test]
20433    fn workflow_context_schedules_activity_until_completion_is_in_history() {
20434        let ctx = WorkflowContext {
20435            cancellation_scope_id: "root".into(),
20436            state: Arc::new(Mutex::new(
20437                WorkflowState::new_with_identity(
20438                    Vec::new(),
20439                    Some("wf-parent".to_string()),
20440                    Some("run-parent".to_string()),
20441                    "rust-workers".to_string(),
20442                    DEFAULT_CODEC.to_string(),
20443                    None,
20444                )
20445                .expect("workflow state"),
20446            )),
20447        };
20448
20449        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
20450        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20451        assert!(matches!(
20452            call.as_mut().poll(&mut task_context),
20453            Poll::Pending
20454        ));
20455
20456        let commands = ctx.take_commands().expect("commands");
20457        assert_eq!(commands[0]["type"], "schedule_activity");
20458        assert_eq!(commands[0]["activity_type"], "hello.activity");
20459    }
20460
20461    #[test]
20462    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
20463        let ctx = workflow_context(Vec::new());
20464        let options = ActivityOptions::new()
20465            .task_queue("payments")
20466            .retry_policy(
20467                ActivityRetryPolicy::new(4)
20468                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
20469                    .non_retryable_error_type("ValidationError"),
20470            )
20471            .start_to_close_timeout(Duration::from_secs(120))
20472            .schedule_to_start_timeout(Duration::from_secs(10))
20473            .schedule_to_close_timeout(Duration::from_secs(300))
20474            .heartbeat_timeout(Duration::from_secs(15));
20475        let mut call = Box::pin(ctx.activity_with_options(
20476            "charge-card",
20477            options,
20478            json!([{"order_id": "o-1"}]),
20479        ));
20480        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20481
20482        assert!(matches!(
20483            call.as_mut().poll(&mut task_context),
20484            Poll::Pending
20485        ));
20486        assert!(matches!(
20487            call.as_mut().poll(&mut task_context),
20488            Poll::Pending
20489        ));
20490
20491        let commands = ctx.take_commands().expect("activity command");
20492        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
20493        assert_eq!(commands[0]["queue"], "payments");
20494        assert_eq!(
20495            commands[0]["retry_policy"],
20496            json!({
20497                "max_attempts": 4,
20498                "backoff_seconds": [1, 3, 9],
20499                "non_retryable_error_types": ["ValidationError"],
20500            })
20501        );
20502        assert_eq!(commands[0]["start_to_close_timeout"], 120);
20503        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
20504        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
20505        assert_eq!(commands[0]["heartbeat_timeout"], 15);
20506    }
20507
20508    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
20509        vec![
20510            history_event(
20511                "ActivityScheduled",
20512                json!({"sequence":1,"activity_type":"render",
20513                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
20514            ),
20515            history_event(
20516                "ActivityCompleted",
20517                json!({"sequence":1,"activity_type":"render",
20518                "payload_codec":DEFAULT_CODEC,
20519                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
20520            ),
20521        ]
20522    }
20523
20524    #[test]
20525    fn worker_session_activity_routes_to_session_queue_once() {
20526        let ctx = workflow_context(Vec::new());
20527        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20528        let mut call = Box::pin(
20529            ctx.activity("render", json!([]))
20530                .in_worker_session(session.clone()),
20531        );
20532        let mut cx = TaskContext::from_waker(noop_waker_ref());
20533        assert!(call.as_mut().poll(&mut cx).is_pending());
20534        assert!(call.as_mut().poll(&mut cx).is_pending());
20535        let commands = ctx.take_commands().unwrap();
20536        assert_eq!(commands.len(), 1);
20537        assert_eq!(commands[0]["queue"], "gpu-workers");
20538        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
20539    }
20540
20541    #[tokio::test]
20542    async fn worker_session_cold_replay_uses_recorded_avro_result() {
20543        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20544        for _replacement in 0..2 {
20545            let ctx = workflow_context(completed_worker_session_history(&session));
20546            let result: i64 = ctx
20547                .activity("render", json!([]))
20548                .in_worker_session(session.clone())
20549                .typed()
20550                .await
20551                .unwrap();
20552            assert_eq!(result, 42);
20553            assert!(ctx.take_commands().unwrap().is_empty());
20554        }
20555    }
20556
20557    #[test]
20558    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
20559        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20560        for changed in [
20561            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
20562            Some(original.clone().ttl_seconds(60)),
20563            Some(original.clone().requirements(["gpu:l4"])),
20564            None,
20565        ] {
20566            let ctx = workflow_context(completed_worker_session_history(&original));
20567            let mut call = ctx.activity_with_options(
20568                "render",
20569                ActivityOptions::new().task_queue("gpu-workers"),
20570                json!([]),
20571            );
20572            if let Some(changed) = changed {
20573                call = call.in_worker_session(changed);
20574            }
20575            let mut call = Box::pin(call);
20576            let mut cx = TaskContext::from_waker(noop_waker_ref());
20577            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20578                call.as_mut().poll(&mut cx)
20579            else {
20580                panic!("changed session must fail replay");
20581            };
20582            assert_eq!(failure.reason, "activity_worker_session_mismatch");
20583            assert!(ctx.take_commands().unwrap().is_empty());
20584        }
20585    }
20586
20587    #[test]
20588    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
20589        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20590        let ctx = workflow_context(Vec::new());
20591        let mut local = Box::pin(
20592            ctx.local_activity("render", json!([]))
20593                .in_worker_session(session.clone()),
20594        );
20595        let mut cx = TaskContext::from_waker(noop_waker_ref());
20596        assert!(matches!(
20597            local.as_mut().poll(&mut cx),
20598            Poll::Ready(Err(Error::WorkerLoop(_)))
20599        ));
20600        assert!(ctx.take_commands().unwrap().is_empty());
20601        let mut remote = Box::pin(
20602            ctx.activity_with_options(
20603                "render",
20604                ActivityOptions::new().task_queue("other"),
20605                json!([]),
20606            )
20607            .in_worker_session(session),
20608        );
20609        assert!(matches!(
20610            remote.as_mut().poll(&mut cx),
20611            Poll::Ready(Err(Error::WorkerLoop(_)))
20612        ));
20613        assert!(ctx.take_commands().unwrap().is_empty());
20614    }
20615
20616    #[test]
20617    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
20618        let ctx = workflow_context(Vec::new());
20619        let options = ActivityOptions::new().retry_policy(
20620            ActivityRetryPolicy::new(3)
20621                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
20622        );
20623        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
20624        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20625
20626        assert!(matches!(
20627            call.as_mut().poll(&mut task_context),
20628            Poll::Pending
20629        ));
20630        assert_eq!(
20631            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
20632            json!([1, 2])
20633        );
20634    }
20635
20636    #[test]
20637    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
20638        let cases = [
20639            (
20640                ActivityOptions::new().task_queue("  "),
20641                ActivityOptionsErrorKind::EmptyTaskQueue,
20642            ),
20643            (
20644                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
20645                ActivityOptionsErrorKind::EmptyRetryPolicy,
20646            ),
20647            (
20648                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
20649                ActivityOptionsErrorKind::InvalidMaxAttempts,
20650            ),
20651            (
20652                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
20653                    max_attempts: None,
20654                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
20655                    non_retryable_error_types: Vec::new(),
20656                }),
20657                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
20658            ),
20659            (
20660                ActivityOptions::new().retry_policy(
20661                    ActivityRetryPolicy::new(2)
20662                        .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
20663                ),
20664                ActivityOptionsErrorKind::TooManyBackoffIntervals,
20665            ),
20666            (
20667                ActivityOptions::new().retry_policy(
20668                    ActivityRetryPolicy::new(2).exponential_backoff(
20669                        Duration::from_secs(1),
20670                        0,
20671                        None,
20672                    ),
20673                ),
20674                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
20675            ),
20676            (
20677                ActivityOptions::new()
20678                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
20679                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
20680            ),
20681            (
20682                ActivityOptions::new().retry_policy(
20683                    ActivityRetryPolicy::new(10_002).exponential_backoff(
20684                        Duration::from_secs(1),
20685                        1,
20686                        None,
20687                    ),
20688                ),
20689                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
20690            ),
20691            (
20692                ActivityOptions::new().retry_policy(
20693                    ActivityRetryPolicy::new(2)
20694                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
20695                ),
20696                ActivityOptionsErrorKind::BackoffOverflow,
20697            ),
20698        ];
20699
20700        for (options, expected_kind) in cases {
20701            let ctx = workflow_context(Vec::new());
20702            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
20703            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20704            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
20705                call.as_mut().poll(&mut task_context)
20706            else {
20707                panic!("expected typed activity validation error");
20708            };
20709            assert_eq!(error.kind, expected_kind);
20710            assert!(ctx.take_commands().expect("commands").is_empty());
20711        }
20712    }
20713
20714    #[test]
20715    fn activity_options_validate_positive_and_ordered_timeouts() {
20716        let zero_timeout_cases = [
20717            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
20718            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
20719            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
20720            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
20721        ];
20722        for options in zero_timeout_cases {
20723            assert_eq!(
20724                options.validate().expect_err("zero timeout").kind,
20725                ActivityOptionsErrorKind::TimeoutNotPositive
20726            );
20727        }
20728
20729        let ordering_cases = [
20730            ActivityOptions::new()
20731                .heartbeat_timeout(Duration::from_secs(11))
20732                .start_to_close_timeout(Duration::from_secs(10)),
20733            ActivityOptions::new()
20734                .start_to_close_timeout(Duration::from_secs(31))
20735                .schedule_to_close_timeout(Duration::from_secs(30)),
20736            ActivityOptions::new()
20737                .schedule_to_start_timeout(Duration::from_secs(31))
20738                .schedule_to_close_timeout(Duration::from_secs(30)),
20739        ];
20740        for options in ordering_cases {
20741            assert_eq!(
20742                options.validate().expect_err("timeout order").kind,
20743                ActivityOptionsErrorKind::TimeoutOrder
20744            );
20745        }
20746
20747        assert_eq!(
20748            ActivityOptions::new()
20749                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
20750                .validate()
20751                .expect_err("protocol integer overflow")
20752                .kind,
20753            ActivityOptionsErrorKind::TimeoutOverflow
20754        );
20755    }
20756
20757    #[test]
20758    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
20759        let ctx = workflow_context(completed_retry_activity_history());
20760        let mut call =
20761            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20762        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20763
20764        assert!(matches!(
20765            call.as_mut().poll(&mut task_context),
20766            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20767        ));
20768        assert!(ctx.take_commands().expect("commands").is_empty());
20769        ctx.ensure_history_consumed().expect("history consumed");
20770    }
20771
20772    #[test]
20773    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
20774        let mut options = retry_activity_options();
20775        options
20776            .retry_policy
20777            .as_mut()
20778            .expect("retry policy")
20779            .non_retryable_error_types
20780            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
20781
20782        let new_ctx = workflow_context(Vec::new());
20783        let mut new_call =
20784            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
20785        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20786        assert!(matches!(
20787            new_call.as_mut().poll(&mut task_context),
20788            Poll::Pending
20789        ));
20790        let commands = new_ctx.take_commands().expect("commands");
20791        assert_eq!(commands.len(), 1);
20792        assert_eq!(
20793            commands[0]["retry_policy"]["non_retryable_error_types"],
20794            json!(["PermanentError"])
20795        );
20796
20797        let replay_ctx = workflow_context(completed_retry_activity_history());
20798        let mut replay_call =
20799            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
20800        assert!(matches!(
20801            replay_call.as_mut().poll(&mut task_context),
20802            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20803        ));
20804        assert!(replay_ctx.take_commands().expect("commands").is_empty());
20805        replay_ctx
20806            .ensure_history_consumed()
20807            .expect("history consumed");
20808    }
20809
20810    #[test]
20811    fn replayed_intermediate_retry_remains_pending_across_restarts() {
20812        let history = completed_retry_activity_history()
20813            .into_iter()
20814            .take(3)
20815            .collect::<Vec<_>>();
20816
20817        for _restart in 0..2 {
20818            let ctx = workflow_context(history.clone());
20819            let mut call =
20820                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20821            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20822            assert!(matches!(
20823                call.as_mut().poll(&mut task_context),
20824                Poll::Pending
20825            ));
20826            assert!(ctx.take_commands().expect("commands").is_empty());
20827        }
20828    }
20829
20830    #[test]
20831    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
20832        let mut changed_queue = retry_activity_options();
20833        changed_queue.task_queue = Some("different-queue".to_string());
20834
20835        let mut changed_max_attempts = retry_activity_options();
20836        let retry_policy = changed_max_attempts
20837            .retry_policy
20838            .as_mut()
20839            .expect("retry policy");
20840        retry_policy.max_attempts = Some(4);
20841
20842        let mut changed_backoff = retry_activity_options();
20843        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
20844        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
20845            Duration::from_secs(3),
20846            Duration::from_secs(4),
20847        ]));
20848
20849        let mut changed_non_retryable_types = retry_activity_options();
20850        let retry_policy = changed_non_retryable_types
20851            .retry_policy
20852            .as_mut()
20853            .expect("retry policy");
20854        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
20855
20856        let mut changed_start_to_close = retry_activity_options();
20857        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
20858        let mut changed_schedule_to_start = retry_activity_options();
20859        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
20860        let mut changed_schedule_to_close = retry_activity_options();
20861        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
20862        let mut changed_heartbeat = retry_activity_options();
20863        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
20864
20865        let cases = [
20866            (changed_queue, "activity_task_queue_mismatch"),
20867            (changed_max_attempts, "activity_retry_policy_mismatch"),
20868            (changed_backoff, "activity_retry_policy_mismatch"),
20869            (
20870                changed_non_retryable_types,
20871                "activity_retry_policy_mismatch",
20872            ),
20873            (changed_start_to_close, "activity_retry_policy_mismatch"),
20874            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
20875            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
20876            (changed_heartbeat, "activity_retry_policy_mismatch"),
20877        ];
20878
20879        for (options, expected_reason) in cases {
20880            let ctx = workflow_context(completed_retry_activity_history());
20881            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
20882            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20883            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20884                call.as_mut().poll(&mut task_context)
20885            else {
20886                panic!("changed activity options must fail replay");
20887            };
20888            assert_eq!(failure.reason, expected_reason);
20889            assert_eq!(failure.sequence, Some(1));
20890            assert!(ctx.take_commands().expect("commands").is_empty());
20891        }
20892    }
20893
20894    #[test]
20895    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
20896        let cases = [
20897            (
20898                "execution_mode",
20899                json!("local"),
20900                "activity_execution_mode_mismatch",
20901            ),
20902            (
20903                "snapshot_version",
20904                json!(2),
20905                "activity_retry_policy_mismatch",
20906            ),
20907        ];
20908
20909        for (field, value, expected_reason) in cases {
20910            let mut history = completed_retry_activity_history();
20911            let activity = history[0].payload["activity"]
20912                .as_object_mut()
20913                .expect("activity snapshot");
20914            if field == "execution_mode" {
20915                activity.insert(field.to_string(), value);
20916            } else {
20917                activity["retry_policy"]
20918                    .as_object_mut()
20919                    .expect("retry snapshot")
20920                    .insert(field.to_string(), value);
20921            }
20922
20923            let ctx = workflow_context(history);
20924            let mut call =
20925                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20926            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20927            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20928                call.as_mut().poll(&mut task_context)
20929            else {
20930                panic!("changed {field} must fail replay");
20931            };
20932            assert_eq!(failure.reason, expected_reason);
20933            assert_eq!(failure.sequence, Some(1));
20934            assert!(ctx.take_commands().expect("commands").is_empty());
20935        }
20936    }
20937
20938    #[test]
20939    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
20940        for (nested, field, value, terminal_only) in [
20941            (false, "execution_mode", json!("local"), false),
20942            (false, "local_activity", json!(true), false),
20943            (true, "local_activity", json!(true), false),
20944            (false, "local_activity", json!(true), true),
20945        ] {
20946            let mut history = completed_retry_activity_history();
20947            history[0]
20948                .payload
20949                .as_object_mut()
20950                .unwrap()
20951                .remove("activity");
20952            let event = if terminal_only {
20953                history.last_mut().unwrap()
20954            } else {
20955                &mut history[0]
20956            };
20957            if nested {
20958                event.payload["activity"] = json!({(field): value});
20959            } else {
20960                event.payload[field] = value;
20961            }
20962            let ctx = workflow_context(history);
20963            let mut call =
20964                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20965            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20966            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20967                call.as_mut().poll(&mut task_context)
20968            else {
20969                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
20970            };
20971            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
20972            assert_eq!(failure.sequence, Some(1));
20973            assert!(ctx.take_commands().expect("commands").is_empty());
20974        }
20975    }
20976
20977    #[test]
20978    fn activity_history_rejects_conflicting_local_execution_markers() {
20979        let mut history = completed_retry_activity_history();
20980        history.last_mut().unwrap().payload["local_activity"] = json!(true);
20981        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
20982            .expect_err("remote schedule cannot become a local completion");
20983        assert!(
20984            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
20985            if reason == "activity_execution_mode_conflict")
20986        );
20987    }
20988
20989    #[test]
20990    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
20991        let mut history = completed_retry_activity_history();
20992        let activity = history[0].payload["activity"]
20993            .as_object_mut()
20994            .expect("activity snapshot");
20995        activity.remove("execution_mode");
20996        activity.remove("retry_policy");
20997
20998        let mut current = retry_activity_options();
20999        current.start_to_close_timeout = Some(Duration::from_secs(45));
21000        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
21001        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
21002        current.heartbeat_timeout = Some(Duration::from_secs(12));
21003
21004        let ctx = workflow_context(history);
21005        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
21006        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21007        assert!(matches!(
21008            call.as_mut().poll(&mut task_context),
21009            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21010        ));
21011        assert!(ctx.take_commands().expect("commands").is_empty());
21012        ctx.ensure_history_consumed().expect("history consumed");
21013    }
21014
21015    #[test]
21016    fn terminal_activity_failed_after_start_returns_typed_failure() {
21017        let history = vec![
21018            history_event(
21019                "ActivityScheduled",
21020                json!({
21021                    "sequence": 1,
21022                    "activity_type": "flaky",
21023                    "activity_execution_id": "act-terminal",
21024                    "activity": {
21025                        "id": "act-terminal",
21026                        "sequence": 1,
21027                        "type": "flaky",
21028                        "queue": "critical-activities",
21029                        "retry_policy": {
21030                            "snapshot_version": 1,
21031                            "max_attempts": 3,
21032                            "backoff_seconds": [2, 4],
21033                            "non_retryable_error_types": ["PermanentError"]
21034                        }
21035                    }
21036                }),
21037            ),
21038            history_event(
21039                "ActivityStarted",
21040                json!({
21041                    "sequence": 1,
21042                    "activity_type": "flaky",
21043                    "activity_execution_id": "act-terminal",
21044                    "activity_attempt_id": "attempt-1",
21045                    "attempt_number": 1
21046                }),
21047            ),
21048            history_event(
21049                "ActivityFailed",
21050                json!({
21051                    "sequence": 1,
21052                    "activity_type": "flaky",
21053                    "activity_execution_id": "act-terminal",
21054                    "activity_attempt_id": "attempt-1",
21055                    "attempt_number": 1,
21056                    "failure_id": "failure-terminal",
21057                    "failure_category": "activity",
21058                    "exception_type": "PermanentError",
21059                    "message": "cannot retry",
21060                    "non_retryable": true
21061                }),
21062            ),
21063        ];
21064        let ctx = workflow_context(history);
21065        let mut call =
21066            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21067        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21068
21069        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21070            call.as_mut().poll(&mut task_context)
21071        else {
21072            panic!("terminal ActivityFailed must settle the activity future");
21073        };
21074        assert_eq!(failure.kind, ActivityFailureKind::Failed);
21075        assert_eq!(
21076            failure.activity_execution_id.as_deref(),
21077            Some("act-terminal")
21078        );
21079        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
21080        assert!(failure.non_retryable);
21081        assert!(ctx.take_commands().expect("commands").is_empty());
21082        ctx.ensure_history_consumed().expect("history consumed");
21083    }
21084
21085    #[test]
21086    fn activity_terminal_events_return_machine_readable_failures() {
21087        let cases = [
21088            (
21089                "ActivityFailed",
21090                json!({
21091                    "sequence": 1,
21092                    "activity_type": "charge-card",
21093                    "activity_execution_id": "act-1",
21094                    "activity_attempt_id": "attempt-2",
21095                    "attempt_number": 2,
21096                    "failure_id": "failure-1",
21097                    "failure_category": "activity",
21098                    "exception_type": "PaymentDeclined",
21099                    "exception_class": "payments.PaymentDeclined",
21100                    "message": "card declined",
21101                    "non_retryable": true
21102                }),
21103                ActivityFailureKind::Failed,
21104                "activity",
21105            ),
21106            (
21107                "ActivityCancelled",
21108                json!({
21109                    "sequence": 1,
21110                    "activity_type": "charge-card",
21111                    "activity_execution_id": "act-1",
21112                    "activity_attempt_id": "attempt-1"
21113                }),
21114                ActivityFailureKind::Cancelled,
21115                "cancelled",
21116            ),
21117        ];
21118
21119        for (event_type, payload, expected_kind, expected_reason) in cases {
21120            let ctx = workflow_context(vec![history_event(event_type, payload)]);
21121            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
21122            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21123            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21124                call.as_mut().poll(&mut task_context)
21125            else {
21126                panic!("expected terminal activity failure");
21127            };
21128            assert_eq!(failure.kind, expected_kind);
21129            assert_eq!(failure.reason, expected_reason);
21130            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
21131            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
21132        }
21133    }
21134
21135    #[test]
21136    fn every_activity_timeout_class_is_typed() {
21137        for timeout_kind in [
21138            "start_to_close",
21139            "schedule_to_start",
21140            "schedule_to_close",
21141            "heartbeat",
21142        ] {
21143            let ctx = workflow_context(vec![history_event(
21144                "ActivityTimedOut",
21145                json!({
21146                    "sequence": 1,
21147                    "activity_type": "slow",
21148                    "activity_execution_id": "act-timeout",
21149                    "activity_attempt_id": "attempt-timeout",
21150                    "failure_category": "timeout",
21151                    "timeout_kind": timeout_kind,
21152                    "message": "deadline expired"
21153                }),
21154            )]);
21155            let mut call = Box::pin(ctx.activity("slow", json!([])));
21156            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21157            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21158                call.as_mut().poll(&mut task_context)
21159            else {
21160                panic!("expected timeout failure");
21161            };
21162            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
21163            assert_eq!(failure.reason, timeout_kind);
21164            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
21165            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
21166        }
21167    }
21168
21169    #[test]
21170    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
21171        let ctx = workflow_context(Vec::new());
21172        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
21173        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21174
21175        assert!(matches!(
21176            sleep.as_mut().poll(&mut task_context),
21177            Poll::Pending
21178        ));
21179        assert!(matches!(
21180            sleep.as_mut().poll(&mut task_context),
21181            Poll::Pending
21182        ));
21183
21184        let commands = ctx.take_commands().expect("timer command");
21185        assert_eq!(
21186            commands,
21187            vec![json!({
21188                "type": "start_timer",
21189                "delay_seconds": 2,
21190            })]
21191        );
21192    }
21193
21194    #[test]
21195    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
21196        let history = vec![
21197            history_event(
21198                "TimerScheduled",
21199                json!({
21200                    "sequence": 1,
21201                    "timer_id": "timer-1",
21202                    "delay_seconds": 5,
21203                    "fire_at": "2026-07-11T12:00:05Z",
21204                }),
21205            ),
21206            history_event(
21207                "TimerFired",
21208                json!({
21209                    "sequence": 1,
21210                    "timer_id": "timer-1",
21211                    "delay_seconds": 5,
21212                    "fire_at": "2026-07-11T12:00:05Z",
21213                    "fired_at": "2026-07-11T12:00:05Z",
21214                }),
21215            ),
21216        ];
21217
21218        for _restart in 0..2 {
21219            let ctx = workflow_context(history.clone());
21220            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
21221            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21222            assert!(matches!(
21223                sleep.as_mut().poll(&mut task_context),
21224                Poll::Ready(Ok(()))
21225            ));
21226            assert!(ctx.take_commands().expect("commands").is_empty());
21227            ctx.ensure_history_consumed().expect("history consumed");
21228        }
21229    }
21230
21231    #[test]
21232    fn workflow_sleep_rejects_changed_delay_during_replay() {
21233        let ctx = workflow_context(vec![
21234            history_event(
21235                "TimerScheduled",
21236                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21237            ),
21238            history_event(
21239                "TimerFired",
21240                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21241            ),
21242        ]);
21243        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
21244        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21245
21246        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21247            sleep.as_mut().poll(&mut task_context)
21248        else {
21249            panic!("changed timer delay must be rejected");
21250        };
21251        assert_eq!(failure.reason, "timer_delay_mismatch");
21252        assert_eq!(failure.sequence, Some(1));
21253    }
21254
21255    #[test]
21256    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
21257        let ctx = workflow_context(Vec::new());
21258        let mut wait = Box::pin(
21259            ctx.wait_condition(
21260                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
21261                    .timeout(Duration::from_millis(60_001)),
21262                || Ok(false),
21263            ),
21264        );
21265        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21266
21267        assert!(matches!(
21268            wait.as_mut().poll(&mut task_context),
21269            Poll::Pending
21270        ));
21271        assert!(matches!(
21272            wait.as_mut().poll(&mut task_context),
21273            Poll::Pending
21274        ));
21275        assert_eq!(
21276            ctx.take_commands().expect("condition command"),
21277            vec![json!({
21278                "type": "open_condition_wait",
21279                "condition_wait_occurrence_id": "rust:condition-wait:0",
21280                "condition_key": "approval.ready",
21281                "condition_definition_fingerprint": "sha256:approval-v1",
21282                "timeout_seconds": 61,
21283            })]
21284        );
21285    }
21286
21287    #[test]
21288    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
21289        let ctx = workflow_context(Vec::new());
21290        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
21291        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21292        assert!(matches!(
21293            satisfied.as_mut().poll(&mut task_context),
21294            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21295        ));
21296
21297        let mut timed_out = Box::pin(wait_condition!(
21298            ctx,
21299            "no-wait",
21300            timeout: Duration::ZERO,
21301            || Ok(false),
21302        ));
21303        assert!(matches!(
21304            timed_out.as_mut().poll(&mut task_context),
21305            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
21306        ));
21307        assert!(ctx.take_commands().expect("commands").is_empty());
21308    }
21309
21310    #[test]
21311    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
21312        let signal_history = vec![
21313            history_event(
21314                "ConditionWaitOpened",
21315                json!({
21316                    "sequence": 4,
21317                    "condition_wait_id": "condition:4",
21318                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21319                    "condition_key": "approval",
21320                    "condition_definition_fingerprint": "sha256:approval-v1",
21321                    "timeout_seconds": 30,
21322                }),
21323            ),
21324            history_event(
21325                "SignalReceived",
21326                json!({
21327                    "workflow_sequence": 4,
21328                    "signal_name": "approve",
21329                    "arguments": fixture_envelope(json!(["Ada"])),
21330                }),
21331            ),
21332        ];
21333        for _worker_before_or_after_restart in 0..2 {
21334            let ctx = workflow_context(signal_history.clone());
21335            let predicate_ctx = ctx.clone();
21336            let mut wait = Box::pin(
21337                ctx.wait_condition(
21338                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
21339                        .timeout(Duration::from_secs(30)),
21340                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
21341                ),
21342            );
21343            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21344            assert!(matches!(
21345                wait.as_mut().poll(&mut task_context),
21346                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21347            ));
21348            assert!(ctx.take_commands().expect("commands").is_empty());
21349            ctx.ensure_history_consumed().expect("condition consumed");
21350        }
21351
21352        let update_history = vec![
21353            history_event(
21354                "ConditionWaitOpened",
21355                json!({
21356                    "sequence": 7,
21357                    "condition_wait_id": "condition:7",
21358                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21359                    "condition_key": "update-approval",
21360                    "condition_definition_fingerprint": "sha256:update-approval-v1",
21361                }),
21362            ),
21363            history_event(
21364                "UpdateApplied",
21365                json!({
21366                    "sequence": 7,
21367                    "update_id": "update-1",
21368                    "update_name": "approve",
21369                    "arguments": fixture_envelope(json!([true])),
21370                }),
21371            ),
21372        ];
21373        let ctx = workflow_context(update_history);
21374        let predicate_ctx = ctx.clone();
21375        let mut wait = Box::pin(ctx.wait_condition(
21376            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
21377            move || {
21378                Ok(predicate_ctx
21379                    .updates("approve")?
21380                    .first()
21381                    .and_then(|arguments| arguments.first())
21382                    .and_then(Value::as_bool)
21383                    == Some(true))
21384            },
21385        ));
21386        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21387        assert!(matches!(
21388            wait.as_mut().poll(&mut task_context),
21389            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21390        ));
21391        assert!(ctx.take_commands().expect("commands").is_empty());
21392        ctx.ensure_history_consumed().expect("condition consumed");
21393    }
21394
21395    #[test]
21396    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
21397        let open_history = vec![
21398            history_event(
21399                "ConditionWaitOpened",
21400                json!({
21401                    "sequence": 3,
21402                    "condition_wait_id": "condition:3",
21403                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21404                    "condition_key": "two-votes",
21405                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21406                    "timeout_seconds": 120,
21407                }),
21408            ),
21409            history_event(
21410                "SignalReceived",
21411                json!({
21412                    "workflow_sequence": 3,
21413                    "signal_name": "vote",
21414                    "arguments": fixture_envelope(json!(["first"])),
21415                }),
21416            ),
21417        ];
21418        for _worker_before_or_after_restart in 0..2 {
21419            let ctx = workflow_context(open_history.clone());
21420            let predicate_ctx = ctx.clone();
21421            let mut wait = Box::pin(
21422                ctx.wait_condition(
21423                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21424                        .timeout(Duration::from_secs(120)),
21425                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
21426                ),
21427            );
21428            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21429            assert!(matches!(
21430                wait.as_mut().poll(&mut task_context),
21431                Poll::Pending
21432            ));
21433            assert_eq!(
21434                ctx.take_commands().expect("reopened condition"),
21435                vec![json!({
21436                    "type": "open_condition_wait",
21437                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21438                    "condition_key": "two-votes",
21439                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21440                    "timeout_seconds": 120,
21441                })]
21442            );
21443        }
21444
21445        let satisfied_ctx = workflow_context(vec![
21446            history_event(
21447                "ConditionWaitOpened",
21448                json!({
21449                    "sequence": 5,
21450                    "condition_wait_id": "condition:5",
21451                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21452                    "condition_key": "approval",
21453                    "condition_definition_fingerprint": "sha256:approval-v1",
21454                }),
21455            ),
21456            history_event(
21457                "ConditionWaitSatisfied",
21458                json!({
21459                    "sequence": 5,
21460                    "condition_wait_id": "condition:5",
21461                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21462                    "condition_key": "approval",
21463                    "condition_definition_fingerprint": "sha256:approval-v1",
21464                }),
21465            ),
21466        ]);
21467        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
21468            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
21469            || Ok(false),
21470        ));
21471        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21472        assert!(matches!(
21473            satisfied.as_mut().poll(&mut task_context),
21474            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21475        ));
21476
21477        let timed_out_ctx = workflow_context(vec![
21478            history_event(
21479                "ConditionWaitOpened",
21480                json!({
21481                    "sequence": 8,
21482                    "condition_wait_id": "condition:8",
21483                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21484                    "condition_key": "approval-timeout",
21485                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
21486                    "timeout_seconds": 5,
21487                }),
21488            ),
21489            history_event(
21490                "TimerScheduled",
21491                json!({
21492                    "sequence": 9,
21493                    "timer_id": "condition-timer:9",
21494                    "timer_kind": "condition_timeout",
21495                    "condition_wait_id": "condition:8",
21496                    "delay_seconds": 5,
21497                }),
21498            ),
21499            history_event(
21500                "TimerFired",
21501                json!({
21502                    "sequence": 9,
21503                    "timer_id": "condition-timer:9",
21504                    "timer_kind": "condition_timeout",
21505                    "condition_wait_id": "condition:8",
21506                    "delay_seconds": 5,
21507                }),
21508            ),
21509        ]);
21510        let mut timed_out = Box::pin(
21511            timed_out_ctx.wait_condition(
21512                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
21513                    .timeout(Duration::from_secs(5)),
21514                || Ok(true),
21515            ),
21516        );
21517        assert!(matches!(
21518            timed_out.as_mut().poll(&mut task_context),
21519            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
21520        ));
21521    }
21522
21523    #[test]
21524    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
21525        let ctx = workflow_context(reopened_selection_condition_history());
21526        {
21527            let state = ctx.state.lock().unwrap();
21528            assert!(matches!(
21529                selection_member_recorded_command(&state, 2),
21530                Some(RecordedCommand::ConditionWait {
21531                    sequence: 3,
21532                    result: None,
21533                    ..
21534                })
21535            ));
21536        }
21537        let mut selected = Box::pin(ctx.select_keyed(vec![
21538            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
21539            (
21540                "votes",
21541                ParallelOperation::condition(
21542                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
21543                    || Ok(true),
21544                ),
21545            ),
21546        ]));
21547        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21548        assert!(selected.as_mut().poll(&mut task_context).is_pending());
21549        assert!(
21550            ctx.take_commands().unwrap().is_empty(),
21551            "true predicate must not reopen the recorded wait"
21552        );
21553        ctx.ensure_history_consumed()
21554            .expect("physical reopens are consumed while canonical selection is pending");
21555    }
21556
21557    #[test]
21558    fn reopened_selection_condition_replays_its_latest_physical_winner() {
21559        for (terminal_type, acknowledge_timeout) in [
21560            ("ConditionWaitSatisfied", false),
21561            ("ConditionWaitTimedOut", false),
21562            ("TimerFired", false),
21563            ("TimerFired", true),
21564        ] {
21565            let mut history = reopened_selection_condition_history();
21566            let original_identity = history[1].payload["condition_wait_id"].clone();
21567            let uses_timer = terminal_type == "TimerFired";
21568            let mut resolution_payload = history[3].payload.clone();
21569            if uses_timer {
21570                for event in &mut history[1..] {
21571                    event.payload["timeout_seconds"] = json!(3);
21572                }
21573                resolution_payload = history[3].payload.clone();
21574                resolution_payload["timer_kind"] = json!("condition_timeout");
21575                resolution_payload["timer_id"] = json!("condition-timeout-3");
21576                resolution_payload["delay_seconds"] = json!(3);
21577                history.push(history_event("TimerScheduled", resolution_payload.clone()));
21578            }
21579            let mut resolution = history_event(terminal_type, resolution_payload.clone());
21580            resolution
21581                .raw
21582                .insert("id".into(), json!("latest-condition-resolution"));
21583            history.push(resolution);
21584            history.push(history_event(
21585                "SelectionResolved",
21586                json!({
21587                    "selection_group_id": "select-calls:1:2",
21588                    "selection_group_base_sequence": 1,
21589                    "selection_group_size": 2,
21590                    "member_key": "votes",
21591                    "member_index": 1,
21592                    "member_base_sequence": 2,
21593                    "member_size": 1,
21594                    "operation_kind": "condition",
21595                    "operation_identity": original_identity,
21596                    "outcome": "completed",
21597                    "resolution_event_id": "latest-condition-resolution",
21598                    "resolution_event_type": terminal_type,
21599                }),
21600            ));
21601            if acknowledge_timeout {
21602                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
21603            }
21604            let ctx = workflow_context(history);
21605            let mut selected = Box::pin(ctx.select_keyed(vec![
21606                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
21607                (
21608                    "votes",
21609                    ParallelOperation::condition(
21610                        if uses_timer {
21611                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21612                                .timeout(Duration::from_secs(3))
21613                        } else {
21614                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21615                        },
21616                        || Ok(true),
21617                    ),
21618                ),
21619            ]));
21620            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21621            match selected.as_mut().poll(&mut task_context) {
21622                Poll::Ready(Ok(result)) => {
21623                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
21624                    let expected = if terminal_type == "ConditionWaitSatisfied" {
21625                        ConditionWaitResult::Satisfied
21626                    } else {
21627                        ConditionWaitResult::TimedOut
21628                    };
21629                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
21630                }
21631                other => panic!("latest physical winner must replay: {other:?}"),
21632            }
21633            assert!(ctx.take_commands().unwrap().is_empty());
21634            ctx.ensure_history_consumed()
21635                .expect("winner history consumed");
21636        }
21637    }
21638
21639    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
21640        let fixture: Value = serde_json::from_str(include_str!(
21641            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
21642        ))
21643        .expect("grouped condition fixture");
21644        fixture["history"]
21645            .as_array()
21646            .unwrap()
21647            .iter()
21648            .map(|event| {
21649                let mut payload = event["payload"].clone();
21650                let index = payload["parallel_group_index"].as_u64().unwrap();
21651                payload["parallel_group_id"] = json!("select-calls:1:2");
21652                payload["parallel_group_mode"] = json!("select");
21653                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
21654                payload["selection_member_index"] = json!(index);
21655                payload["selection_member_base_sequence"] = json!(index + 1);
21656                payload["selection_member_size"] = json!(1);
21657                payload["selection_member_kind"] =
21658                    json!(if index == 0 { "timer" } else { "condition" });
21659                history_event(event["event_type"].as_str().unwrap(), payload)
21660            })
21661            .collect()
21662    }
21663
21664    #[test]
21665    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
21666        let fixture: Value = serde_json::from_str(include_str!(
21667            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
21668        ))
21669        .expect("grouped condition fixture");
21670        let original = fixture["history"].as_array().expect("fixture history");
21671        let decode = |events: &[Value]| {
21672            let history = events
21673                .iter()
21674                .map(|event| {
21675                    history_event(
21676                        event["event_type"].as_str().unwrap(),
21677                        event["payload"].clone(),
21678                    )
21679                })
21680                .collect::<Vec<_>>();
21681            recorded_commands(
21682                &history,
21683                DEFAULT_CODEC,
21684                WorkflowIdentity {
21685                    workflow_id: None,
21686                    run_id: None,
21687                },
21688            )
21689        };
21690        assert!(decode(original).is_ok());
21691        for field in [
21692            "condition_wait_occurrence_id",
21693            "condition_key",
21694            "condition_definition_fingerprint",
21695            "timeout_seconds",
21696            "parallel_group_id",
21697            "parallel_group_size",
21698            "parallel_group_index",
21699        ] {
21700            let mut changed = original.clone();
21701            changed[3]["payload"][field] = match field {
21702                "timeout_seconds" | "parallel_group_size" => json!(30),
21703                "parallel_group_index" => json!(0),
21704                _ => json!("changed"),
21705            };
21706            assert!(
21707                decode(&changed).is_err(),
21708                "reopen must reject changed {field}"
21709            );
21710        }
21711        let mut unsettled = original.clone();
21712        unsettled.remove(2);
21713        assert!(
21714            decode(&unsettled).is_err(),
21715            "physical predecessor must be resolved"
21716        );
21717        let mut timed_out = original.clone();
21718        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
21719        assert!(decode(&timed_out).is_err(), "timeout is terminal");
21720        let mut late_resolution = original.clone();
21721        late_resolution.swap(2, 3);
21722        assert!(
21723            decode(&late_resolution).is_err(),
21724            "later history cannot authorize a reopen"
21725        );
21726    }
21727
21728    #[test]
21729    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
21730        let history = vec![
21731            history_event(
21732                "ConditionWaitOpened",
21733                json!({
21734                    "sequence": 3,
21735                    "condition_wait_id": "condition:3",
21736                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21737                    "condition_key": "two-votes",
21738                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21739                }),
21740            ),
21741            history_event(
21742                "SignalReceived",
21743                json!({
21744                    "workflow_sequence": 3,
21745                    "signal_name": "vote",
21746                    "arguments": fixture_envelope(json!(["first"])),
21747                }),
21748            ),
21749            history_event(
21750                "ConditionWaitSatisfied",
21751                json!({
21752                    "sequence": 3,
21753                    "condition_wait_id": "condition:3",
21754                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21755                    "condition_key": "two-votes",
21756                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21757                }),
21758            ),
21759            history_event(
21760                "ConditionWaitOpened",
21761                json!({
21762                    "sequence": 5,
21763                    "condition_wait_id": "condition:5",
21764                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21765                    "condition_key": "two-votes",
21766                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21767                }),
21768            ),
21769            history_event(
21770                "SignalReceived",
21771                json!({
21772                    "workflow_sequence": 5,
21773                    "signal_name": "vote",
21774                    "arguments": fixture_envelope(json!(["second"])),
21775                }),
21776            ),
21777            history_event(
21778                "ConditionWaitSatisfied",
21779                json!({
21780                    "sequence": 5,
21781                    "condition_wait_id": "condition:5",
21782                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21783                    "condition_key": "two-votes",
21784                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21785                }),
21786            ),
21787        ];
21788        for _cold_worker_or_restart in 0..2 {
21789            let ctx = workflow_context(history.clone());
21790            let predicate_ctx = ctx.clone();
21791            let mut wait = Box::pin(ctx.wait_condition(
21792                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
21793                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
21794            ));
21795            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21796
21797            assert!(matches!(
21798                wait.as_mut().poll(&mut task_context),
21799                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21800            ));
21801            assert!(ctx.take_commands().expect("commands").is_empty());
21802            ctx.ensure_history_consumed()
21803                .expect("every physical wait-open is consumed");
21804        }
21805    }
21806
21807    #[test]
21808    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
21809        let history = vec![
21810            history_event(
21811                "ConditionWaitOpened",
21812                json!({
21813                    "sequence": 3,
21814                    "condition_wait_id": "condition:3",
21815                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21816                    "condition_key": "approved",
21817                    "condition_definition_fingerprint": "sha256:approved-v1",
21818                }),
21819            ),
21820            history_event(
21821                "UpdateApplied",
21822                json!({
21823                    "sequence": 3,
21824                    "update_id": "update-1",
21825                    "update_name": "approve",
21826                    "arguments": fixture_envelope(json!([false])),
21827                }),
21828            ),
21829            history_event(
21830                "ConditionWaitOpened",
21831                json!({
21832                    "sequence": 5,
21833                    "condition_wait_id": "condition:5",
21834                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21835                    "condition_key": "approved",
21836                    "condition_definition_fingerprint": "sha256:approved-v1",
21837                }),
21838            ),
21839            history_event(
21840                "UpdateApplied",
21841                json!({
21842                    "sequence": 5,
21843                    "update_id": "update-2",
21844                    "update_name": "approve",
21845                    "arguments": fixture_envelope(json!([true])),
21846                }),
21847            ),
21848        ];
21849
21850        for _cold_worker_or_restart in 0..2 {
21851            let ctx = workflow_context(history.clone());
21852            let predicate_ctx = ctx.clone();
21853            let mut wait = Box::pin(ctx.wait_condition(
21854                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
21855                move || {
21856                    Ok(predicate_ctx
21857                        .updates("approve")?
21858                        .last()
21859                        .and_then(|arguments| arguments.first())
21860                        .and_then(Value::as_bool)
21861                        == Some(true))
21862                },
21863            ));
21864            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21865
21866            assert!(matches!(
21867                wait.as_mut().poll(&mut task_context),
21868                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21869            ));
21870            assert!(ctx.take_commands().expect("commands").is_empty());
21871            ctx.ensure_history_consumed()
21872                .expect("every update-driven reopen is consumed");
21873        }
21874    }
21875
21876    #[test]
21877    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
21878        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
21879            ("shared", "sha256:first", "shared", "sha256:second"),
21880            ("first", "sha256:shared", "second", "sha256:shared"),
21881            ("shared", "sha256:shared", "shared", "sha256:shared"),
21882            ("first", "sha256:first", "second", "sha256:second"),
21883        ] {
21884            let history = vec![
21885                history_event(
21886                    "ConditionWaitOpened",
21887                    json!({
21888                        "sequence": 3,
21889                        "condition_wait_id": "condition:3",
21890                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21891                        "condition_key": first_key,
21892                        "condition_definition_fingerprint": first_fingerprint,
21893                    }),
21894                ),
21895                history_event(
21896                    "ConditionWaitSatisfied",
21897                    json!({
21898                        "sequence": 3,
21899                        "condition_wait_id": "condition:3",
21900                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21901                        "condition_key": first_key,
21902                        "condition_definition_fingerprint": first_fingerprint,
21903                    }),
21904                ),
21905                history_event(
21906                    "ConditionWaitOpened",
21907                    json!({
21908                        "sequence": 4,
21909                        "condition_wait_id": "condition:4",
21910                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21911                        "condition_key": second_key,
21912                        "condition_definition_fingerprint": second_fingerprint,
21913                    }),
21914                ),
21915                history_event(
21916                    "ConditionWaitSatisfied",
21917                    json!({
21918                        "sequence": 4,
21919                        "condition_wait_id": "condition:4",
21920                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21921                        "condition_key": second_key,
21922                        "condition_definition_fingerprint": second_fingerprint,
21923                    }),
21924                ),
21925            ];
21926            for _cold_worker_or_restart in 0..2 {
21927                let ctx = workflow_context(history.clone());
21928                let mut task_context = TaskContext::from_waker(noop_waker_ref());
21929                let mut first = Box::pin(ctx.wait_condition(
21930                    ConditionWaitOptions::new(first_key, first_fingerprint),
21931                    || Ok(false),
21932                ));
21933                assert!(matches!(
21934                    first.as_mut().poll(&mut task_context),
21935                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21936                ));
21937
21938                let mut second = Box::pin(ctx.wait_condition(
21939                    ConditionWaitOptions::new(second_key, second_fingerprint),
21940                    || Ok(false),
21941                ));
21942                assert!(matches!(
21943                    second.as_mut().poll(&mut task_context),
21944                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21945                ));
21946                assert!(ctx.take_commands().expect("commands").is_empty());
21947                ctx.ensure_history_consumed()
21948                    .expect("each authored wait consumes one occurrence");
21949            }
21950        }
21951    }
21952
21953    #[test]
21954    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
21955        fn worker() -> Worker {
21956            let client = Client::new("http://127.0.0.1:8080").expect("client");
21957            let mut worker = Worker::new(client, "rust-workers");
21958            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
21959                let mut outcomes = Vec::new();
21960                for _ in 0..2 {
21961                    outcomes.push(
21962                        ctx.wait_condition(
21963                            ConditionWaitOptions::new("shared", "sha256:shared"),
21964                            || Ok(false),
21965                        )
21966                        .await?,
21967                    );
21968                }
21969                Ok(json!(outcomes))
21970            });
21971            worker
21972        }
21973
21974        let task = workflow_task(
21975            "rust.condition-loop",
21976            vec![
21977                history_event(
21978                    "ConditionWaitOpened",
21979                    json!({
21980                        "sequence": 1,
21981                        "condition_wait_id": "condition:1",
21982                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21983                        "condition_key": "shared",
21984                        "condition_definition_fingerprint": "sha256:shared",
21985                    }),
21986                ),
21987                history_event(
21988                    "ConditionWaitSatisfied",
21989                    json!({
21990                        "sequence": 1,
21991                        "condition_wait_id": "condition:1",
21992                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21993                        "condition_key": "shared",
21994                        "condition_definition_fingerprint": "sha256:shared",
21995                    }),
21996                ),
21997                history_event(
21998                    "ConditionWaitOpened",
21999                    json!({
22000                        "sequence": 2,
22001                        "condition_wait_id": "condition:2",
22002                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22003                        "condition_key": "shared",
22004                        "condition_definition_fingerprint": "sha256:shared",
22005                    }),
22006                ),
22007                history_event(
22008                    "ConditionWaitSatisfied",
22009                    json!({
22010                        "sequence": 2,
22011                        "condition_wait_id": "condition:2",
22012                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22013                        "condition_key": "shared",
22014                        "condition_definition_fingerprint": "sha256:shared",
22015                    }),
22016                ),
22017            ],
22018            DEFAULT_CODEC,
22019        );
22020
22021        for _cold_worker_or_restart in 0..2 {
22022            let commands = worker()
22023                .execute_workflow_task(task.clone())
22024                .expect("adjacent loop waits replay deterministically");
22025            assert_eq!(commands.len(), 1);
22026            assert_eq!(commands[0]["type"], "complete_workflow");
22027            assert_eq!(
22028                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
22029                json!(["satisfied", "satisfied"])
22030            );
22031        }
22032    }
22033
22034    #[test]
22035    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
22036        let history = vec![history_event(
22037            "ConditionWaitOpened",
22038            json!({
22039                "sequence": 12,
22040                "condition_wait_id": "condition:12",
22041                "condition_wait_occurrence_id": "rust:condition-wait:0",
22042                "condition_key": "approval",
22043                "condition_definition_fingerprint": "sha256:approval-v1",
22044                "timeout_seconds": 30,
22045            }),
22046        )];
22047        for (options, expected_reason) in [
22048            (
22049                ConditionWaitOptions::new("changed", "sha256:approval-v1")
22050                    .timeout(Duration::from_secs(30)),
22051                "condition_wait_key_mismatch",
22052            ),
22053            (
22054                ConditionWaitOptions::new("approval", "sha256:approval-v2")
22055                    .timeout(Duration::from_secs(30)),
22056                "condition_wait_predicate_mismatch",
22057            ),
22058            (
22059                ConditionWaitOptions::new("approval", "sha256:approval-v1")
22060                    .timeout(Duration::from_secs(29)),
22061                "condition_wait_timeout_mismatch",
22062            ),
22063        ] {
22064            let ctx = workflow_context(history.clone());
22065            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
22066            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22067            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22068                wait.as_mut().poll(&mut task_context)
22069            else {
22070                panic!("changed condition definition must fail replay");
22071            };
22072            assert_eq!(failure.reason, expected_reason);
22073            assert_eq!(failure.sequence, Some(12));
22074        }
22075    }
22076
22077    #[test]
22078    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
22079        let error = WorkflowState::new(
22080            vec![history_event(
22081                "ConditionWaitOpened",
22082                json!({
22083                    "sequence": 12,
22084                    "condition_wait_id": "condition:12",
22085                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22086                    "condition_key": "approval",
22087                }),
22088            )],
22089            "rust-workers".to_string(),
22090            DEFAULT_CODEC.to_string(),
22091            None,
22092        )
22093        .expect_err("condition history without a predicate fingerprint must fail");
22094
22095        assert!(matches!(
22096            error,
22097            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22098                if reason == "condition_wait_predicate_fingerprint_missing"
22099        ));
22100    }
22101
22102    #[test]
22103    fn condition_wait_history_requires_authored_occurrence_identity() {
22104        let error = WorkflowState::new(
22105            vec![history_event(
22106                "ConditionWaitOpened",
22107                json!({
22108                    "sequence": 12,
22109                    "condition_wait_id": "condition:12",
22110                    "condition_key": "approval",
22111                    "condition_definition_fingerprint": "sha256:approval-v1",
22112                }),
22113            )],
22114            "rust-workers".to_string(),
22115            DEFAULT_CODEC.to_string(),
22116            None,
22117        )
22118        .expect_err("condition history without occurrence identity must fail");
22119
22120        assert!(matches!(
22121            error,
22122            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22123                if reason == "condition_wait_occurrence_id_missing"
22124        ));
22125    }
22126
22127    #[test]
22128    fn typed_search_attribute_updates_validate_emit_and_replay() {
22129        let update = SearchAttributeUpdate::new()
22130            .keyword("OrderStatus", " waiting ")
22131            .expect("keyword")
22132            .int("Attempt", 3)
22133            .expect("int")
22134            .bool("Escalated", false)
22135            .expect("bool")
22136            .keyword_list("Regions", ["us-east", "eu-west"])
22137            .expect("list")
22138            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
22139            .expect("datetime")
22140            .delete("LegacyStatus")
22141            .expect("delete");
22142        let ctx = workflow_context(Vec::new());
22143        ctx.upsert_search_attributes(update.clone())
22144            .expect("typed update");
22145        assert_eq!(
22146            ctx.take_commands().expect("search-attribute command"),
22147            vec![json!({
22148                "type": "upsert_search_attributes",
22149                "attributes": {
22150                    "Attempt": 3,
22151                    "Escalated": false,
22152                    "LegacyStatus": null,
22153                    "OrderStatus": "waiting",
22154                    "Regions": ["us-east", "eu-west"],
22155                    "UpdatedAt": "2026-08-22T04:00:00Z",
22156                },
22157                "attribute_types": {
22158                    "Attempt": "int",
22159                    "Escalated": "bool",
22160                    "OrderStatus": "keyword",
22161                    "Regions": "keyword_list",
22162                    "UpdatedAt": "datetime",
22163                },
22164            })]
22165        );
22166
22167        let replay = workflow_context(vec![history_event(
22168            "SearchAttributesUpserted",
22169            json!({
22170                "sequence": 6,
22171                "attributes": {
22172                    "Attempt": 3,
22173                    "Escalated": false,
22174                    "LegacyStatus": null,
22175                    "OrderStatus": "waiting",
22176                    "Regions": ["us-east", "eu-west"],
22177                    "UpdatedAt": "2026-08-22T04:00:00Z",
22178                },
22179                "attribute_types": {
22180                    "Attempt": "int",
22181                    "Escalated": "bool",
22182                    "OrderStatus": "keyword",
22183                    "Regions": "keyword_list",
22184                    "UpdatedAt": "datetime",
22185                },
22186                "merged": {},
22187            }),
22188        )]);
22189        replay
22190            .upsert_search_attributes(update)
22191            .expect("matching update replays");
22192        assert!(replay.take_commands().expect("commands").is_empty());
22193        replay.ensure_history_consumed().expect("history consumed");
22194
22195        let type_drift = workflow_context(vec![history_event(
22196            "SearchAttributesUpserted",
22197            json!({
22198                "sequence": 7,
22199                "attributes": {"OrderStatus": "waiting"},
22200                "attribute_types": {"OrderStatus": "keyword"},
22201                "merged": {"OrderStatus": "waiting"},
22202            }),
22203        )]);
22204        let error = type_drift
22205            .upsert_search_attributes(
22206                SearchAttributeUpdate::new()
22207                    .string("OrderStatus", "waiting")
22208                    .expect("string update"),
22209            )
22210            .expect_err("same JSON value with a changed type must fail replay");
22211        assert!(matches!(
22212            error,
22213            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22214                if reason == "search_attribute_type_mismatch"
22215        ));
22216
22217        let malformed_types = WorkflowState::new(
22218            vec![history_event(
22219                "SearchAttributesUpserted",
22220                json!({
22221                    "sequence": 8,
22222                    "attributes": {"OrderStatus": "waiting"},
22223                    "attribute_types": {"OrderStatus": "unsupported"},
22224                    "merged": {"OrderStatus": "waiting"},
22225                }),
22226            )],
22227            "rust-workers".to_string(),
22228            DEFAULT_CODEC.to_string(),
22229            None,
22230        )
22231        .expect_err("unsupported search-attribute type metadata must fail");
22232        assert!(matches!(
22233            malformed_types,
22234            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22235                if reason == "search_attribute_types_malformed"
22236        ));
22237
22238        assert!(matches!(
22239            SearchAttributeUpdate::new().keyword("bad key", "value"),
22240            Err(SearchAttributeUpdateError::InvalidKey(_))
22241        ));
22242        assert!(matches!(
22243            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
22244            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
22245        ));
22246        assert!(matches!(
22247            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
22248            Err(SearchAttributeUpdateError::ValueTooLong { .. })
22249        ));
22250        assert!(matches!(
22251            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
22252            Err(SearchAttributeUpdateError::InvalidDateTime(_))
22253        ));
22254        assert!(matches!(
22255            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
22256            Err(Error::InvalidSearchAttributeUpdate(
22257                SearchAttributeUpdateError::Empty
22258            ))
22259        ));
22260    }
22261
22262    #[test]
22263    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
22264        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
22265        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
22266
22267        assert!(SearchAttributeUpdate::new()
22268            .string("AsciiDescription", ascii)
22269            .is_ok());
22270        assert!(SearchAttributeUpdate::new()
22271            .string("Utf8Description", utf8)
22272            .is_ok());
22273        assert!(matches!(
22274            SearchAttributeUpdate::new().string(
22275                "TooLongDescription",
22276                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
22277            ),
22278            Err(SearchAttributeUpdateError::ValueTooLong {
22279                kind: "string",
22280                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
22281                ..
22282            })
22283        ));
22284    }
22285
22286    #[test]
22287    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
22288        let lone_fire = WorkflowState::new(
22289            vec![history_event(
22290                "TimerFired",
22291                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22292            )],
22293            "rust-workers".to_string(),
22294            DEFAULT_CODEC.to_string(),
22295            None,
22296        )
22297        .expect_err("TimerFired requires TimerScheduled");
22298        assert!(matches!(
22299            lone_fire,
22300            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22301                if reason == "timer_schedule_missing_or_duplicate"
22302        ));
22303
22304        let wrong_identity = WorkflowState::new(
22305            vec![
22306                history_event(
22307                    "TimerScheduled",
22308                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22309                ),
22310                history_event(
22311                    "TimerFired",
22312                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
22313                ),
22314            ],
22315            "rust-workers".to_string(),
22316            DEFAULT_CODEC.to_string(),
22317            None,
22318        )
22319        .expect_err("fire must match scheduled timer identity");
22320        assert!(matches!(
22321            wrong_identity,
22322            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22323                if reason == "timer_identity_mismatch"
22324        ));
22325
22326        let duplicate_fire = WorkflowState::new(
22327            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                    "TimerFired",
22338                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22339                ),
22340            ],
22341            "rust-workers".to_string(),
22342            DEFAULT_CODEC.to_string(),
22343            None,
22344        )
22345        .expect_err("a durable timer cannot fire twice");
22346        assert!(matches!(
22347            duplicate_fire,
22348            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22349                if reason == "duplicate_timer_fire"
22350        ));
22351
22352        let wrong_fired_delay = WorkflowState::new(
22353            vec![
22354                history_event(
22355                    "TimerScheduled",
22356                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22357                ),
22358                history_event(
22359                    "TimerFired",
22360                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
22361                ),
22362            ],
22363            "rust-workers".to_string(),
22364            DEFAULT_CODEC.to_string(),
22365            None,
22366        )
22367        .expect_err("timer schedule and fire delays must agree");
22368        assert!(matches!(
22369            wrong_fired_delay,
22370            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22371                if reason == "timer_history_delay_mismatch"
22372        ));
22373    }
22374
22375    #[test]
22376    fn replay_rejects_activity_moved_before_recorded_timer() {
22377        let ctx = workflow_context(vec![
22378            history_event(
22379                "TimerScheduled",
22380                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22381            ),
22382            history_event(
22383                "TimerFired",
22384                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22385            ),
22386            history_event(
22387                "ActivityCompleted",
22388                json!({
22389                    "sequence": 2,
22390                    "activity_type": "after-timer",
22391                    "payload_codec": DEFAULT_CODEC,
22392                    "result": fixture_envelope(json!("done")),
22393                }),
22394            ),
22395        ]);
22396        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
22397        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22398
22399        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22400            activity.as_mut().poll(&mut task_context)
22401        else {
22402            panic!("reordered durable command must be rejected");
22403        };
22404        assert_eq!(failure.reason, "recorded_command_mismatch");
22405        assert_eq!(failure.sequence, Some(1));
22406        assert_eq!(failure.expected.as_deref(), Some("timer"));
22407        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
22408    }
22409
22410    #[test]
22411    fn workflow_context_emits_a_typed_named_signal_wait() {
22412        let ctx = workflow_context(Vec::new());
22413        let mut signal = Box::pin(ctx.wait_signal("finish"));
22414        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22415
22416        assert!(matches!(
22417            signal.as_mut().poll(&mut task_context),
22418            Poll::Pending
22419        ));
22420        assert_eq!(
22421            ctx.take_commands().expect("signal-wait command"),
22422            vec![json!({
22423                "type": "open_signal_wait",
22424                "signal_name": "finish",
22425            })]
22426        );
22427    }
22428
22429    #[test]
22430    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
22431        let ctx = workflow_context(Vec::new());
22432        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
22433        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22434
22435        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
22436        else {
22437            panic!("runtime-reserved signal should be rejected");
22438        };
22439        assert!(message.contains("reserved by the workflow runtime"));
22440        assert!(ctx.take_commands().expect("commands").is_empty());
22441    }
22442
22443    #[tokio::test]
22444    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
22445        let client = Client::builder("http://127.0.0.1:9")
22446            .build()
22447            .expect("client");
22448        let error = client
22449            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
22450            .await
22451            .expect_err("runtime-reserved signal should be rejected before transport");
22452
22453        assert!(
22454            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
22455        );
22456    }
22457
22458    #[test]
22459    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
22460        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22461            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22462                value.to_string(),
22463            )]))
22464            .expect("message payload");
22465            json!({
22466                "schema": MESSAGE_STREAM_SCHEMA,
22467                "stream_name": "orders",
22468                "message_id": message_id,
22469                "position": position,
22470                "payload_envelope": payload,
22471            })
22472        }
22473
22474        fn opened(sequence: u64) -> HistoryEvent {
22475            history_event(
22476                "SignalWaitOpened",
22477                json!({
22478                    "sequence": sequence,
22479                    "signal_name": MESSAGE_STREAM_SIGNAL,
22480                }),
22481            )
22482        }
22483
22484        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22485            history_event(
22486                "SignalApplied",
22487                json!({
22488                    "sequence": sequence,
22489                    "signal_name": MESSAGE_STREAM_SIGNAL,
22490                    "value": fixture_envelope(json!([delivery])),
22491                }),
22492            )
22493        }
22494
22495        fn received(delivery: Value) -> HistoryEvent {
22496            history_event(
22497                "SignalReceived",
22498                json!({
22499                    "signal_name": MESSAGE_STREAM_SIGNAL,
22500                    "arguments": fixture_envelope(json!([delivery])),
22501                    "payload_codec": DEFAULT_CODEC,
22502                }),
22503            )
22504        }
22505
22506        let client = Client::new("http://127.0.0.1:8080").expect("client");
22507        let mut worker = Worker::new(client, "rust-workers");
22508        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
22509            let messages = ctx.message_stream("orders")?.receive(2).await?;
22510            Ok(json!(messages
22511                .into_iter()
22512                .map(|message| message.message_id)
22513                .collect::<Vec<_>>()))
22514        });
22515
22516        let first = delivery("message-1", 1, "one");
22517        let second = delivery("message-2", 2, "two");
22518        let batch = worker
22519            .execute_workflow_task_decision(workflow_task(
22520                "rust.message-stream-batch",
22521                vec![
22522                    opened(1),
22523                    received(first.clone()),
22524                    applied(1, first.clone()),
22525                    received(first.clone()),
22526                    received(second),
22527                ],
22528                DEFAULT_CODEC,
22529            ))
22530            .expect("worker task consumes the available batch");
22531
22532        assert_eq!(batch.commands.len(), 1);
22533        assert_eq!(batch.commands[0]["type"], "complete_workflow");
22534        assert_eq!(
22535            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
22536                .expect("workflow result"),
22537            json!(["message-1", "message-2"])
22538        );
22539        assert_eq!(
22540            batch.message_stream_cursors,
22541            vec![json!({"stream_name": "orders", "through_position": 2})]
22542        );
22543        assert!(batch.message_stream_waits.is_empty());
22544
22545        let partial = worker
22546            .execute_workflow_task_decision(workflow_task(
22547                "rust.message-stream-batch",
22548                vec![opened(1), received(first.clone()), applied(1, first)],
22549                DEFAULT_CODEC,
22550            ))
22551            .expect("worker task returns without waiting for a missing second item");
22552        assert_eq!(partial.commands.len(), 1);
22553        assert_eq!(partial.commands[0]["type"], "complete_workflow");
22554        assert_eq!(
22555            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
22556                .expect("workflow result"),
22557            json!(["message-1"])
22558        );
22559        assert_eq!(
22560            partial.message_stream_cursors,
22561            vec![json!({"stream_name": "orders", "through_position": 1})]
22562        );
22563        assert!(partial.message_stream_waits.is_empty());
22564    }
22565
22566    #[test]
22567    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
22568        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22569            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22570                value.to_string(),
22571            )]))
22572            .expect("message payload");
22573            json!({
22574                "schema": MESSAGE_STREAM_SCHEMA,
22575                "stream_name": "orders",
22576                "message_id": message_id,
22577                "position": position,
22578                "payload_envelope": payload,
22579            })
22580        }
22581
22582        fn opened(sequence: u64) -> HistoryEvent {
22583            history_event(
22584                "SignalWaitOpened",
22585                json!({
22586                    "sequence": sequence,
22587                    "signal_name": MESSAGE_STREAM_SIGNAL,
22588                }),
22589            )
22590        }
22591
22592        fn received(delivery: Value) -> HistoryEvent {
22593            history_event(
22594                "SignalReceived",
22595                json!({
22596                    "signal_name": MESSAGE_STREAM_SIGNAL,
22597                    "arguments": fixture_envelope(json!([delivery])),
22598                    "payload_codec": DEFAULT_CODEC,
22599                }),
22600            )
22601        }
22602
22603        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22604            history_event(
22605                "SignalApplied",
22606                json!({
22607                    "sequence": sequence,
22608                    "signal_name": MESSAGE_STREAM_SIGNAL,
22609                    "value": fixture_envelope(json!([delivery])),
22610                }),
22611            )
22612        }
22613
22614        let client = Client::new("http://127.0.0.1:8080").expect("client");
22615        let mut worker = Worker::new(client, "rust-workers");
22616        worker.register_workflow(
22617            "rust.message-stream-partial-batches",
22618            |ctx, _input| async move {
22619                let stream = ctx.message_stream("orders")?;
22620                let first = stream.receive(10).await?;
22621                let second = stream.receive(10).await?;
22622                Ok(json!([
22623                    first
22624                        .into_iter()
22625                        .map(|message| message.message_id)
22626                        .collect::<Vec<_>>(),
22627                    second
22628                        .into_iter()
22629                        .map(|message| message.message_id)
22630                        .collect::<Vec<_>>(),
22631                ]))
22632            },
22633        );
22634
22635        let first = delivery("message-1", 1, "one");
22636        let second = delivery("message-2", 2, "two");
22637        let decision = worker
22638            .execute_workflow_task_decision(workflow_task(
22639                "rust.message-stream-partial-batches",
22640                vec![
22641                    opened(1),
22642                    received(first.clone()),
22643                    applied(1, first),
22644                    opened(2),
22645                    received(second.clone()),
22646                    applied(2, second),
22647                ],
22648                DEFAULT_CODEC,
22649            ))
22650            .expect("cold replay preserves both authored receive boundaries");
22651
22652        assert_eq!(decision.commands.len(), 1);
22653        assert_eq!(decision.commands[0]["type"], "complete_workflow");
22654        assert_eq!(
22655            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
22656                .expect("workflow result"),
22657            json!([["message-1"], ["message-2"]])
22658        );
22659        assert_eq!(
22660            decision.message_stream_cursors,
22661            vec![json!({"stream_name": "orders", "through_position": 2})]
22662        );
22663        assert!(decision.message_stream_waits.is_empty());
22664    }
22665
22666    #[test]
22667    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
22668        let ctx = workflow_context(Vec::new());
22669        let stream = ctx.message_stream("orders").expect("message stream");
22670        let mut receive = Box::pin(stream.receive(10));
22671        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22672
22673        assert!(matches!(
22674            receive.as_mut().poll(&mut task_context),
22675            Poll::Pending
22676        ));
22677        assert_eq!(
22678            ctx.take_commands().expect("message-stream wait command"),
22679            vec![json!({
22680                "type": "open_signal_wait",
22681                "signal_name": MESSAGE_STREAM_SIGNAL,
22682            })]
22683        );
22684        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
22685        assert!(cursors.is_empty());
22686        assert_eq!(
22687            waits,
22688            vec![json!({"stream_name": "orders", "after_position": 0})]
22689        );
22690    }
22691
22692    #[test]
22693    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
22694        let ctx = workflow_context(vec![history_event(
22695            "SignalReceived",
22696            json!({
22697                "signal_name": MESSAGE_STREAM_SIGNAL,
22698                "arguments": fixture_envelope(json!([{
22699                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
22700                    "stream_name": "orders",
22701                    "through_position": 2,
22702                }])),
22703                "payload_codec": DEFAULT_CODEC,
22704            }),
22705        )]);
22706        let stream = ctx.message_stream("orders").expect("message stream");
22707        let mut receive = Box::pin(stream.receive(10));
22708        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22709
22710        assert!(matches!(
22711            receive.as_mut().poll(&mut task_context),
22712            Poll::Pending
22713        ));
22714        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
22715        assert_eq!(
22716            cursors,
22717            vec![json!({"stream_name": "orders", "through_position": 2})]
22718        );
22719        assert_eq!(
22720            waits,
22721            vec![json!({"stream_name": "orders", "after_position": 2})]
22722        );
22723    }
22724
22725    #[test]
22726    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
22727        let mut empty_map = BTreeMap::new();
22728        let mut nested = BTreeMap::new();
22729        nested.insert(
22730            "value".to_string(),
22731            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
22732        );
22733        let values = vec![
22734            AvroValue::Bytes(vec![0, 255]),
22735            AvroValue::Long(1),
22736            AvroValue::Double(1.0),
22737            AvroValue::Array(Vec::new()),
22738            AvroValue::Map(std::mem::take(&mut empty_map)),
22739            AvroValue::Map(nested),
22740        ];
22741        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
22742        let transport = vec![json!({
22743            "schema": MESSAGE_STREAM_SCHEMA,
22744            "stream_name": "orders",
22745            "message_id": "message-1",
22746            "position": 1,
22747            "payload_envelope": payload,
22748        })];
22749
22750        for _ in 0..2 {
22751            let Some(MessageStreamDelivery::Message(message)) =
22752                decode_message_stream_delivery(transport.clone()).expect("delivery")
22753            else {
22754                panic!("message delivery expected");
22755            };
22756            assert_eq!(message.arguments, values);
22757            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
22758            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
22759        }
22760    }
22761
22762    #[test]
22763    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
22764        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22765            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22766                value.to_string(),
22767            )]))
22768            .expect("message payload");
22769            json!({
22770                "schema": MESSAGE_STREAM_SCHEMA,
22771                "stream_name": "orders",
22772                "message_id": message_id,
22773                "position": position,
22774                "payload_envelope": payload,
22775            })
22776        }
22777
22778        fn opened(sequence: u64) -> HistoryEvent {
22779            history_event(
22780                "SignalWaitOpened",
22781                json!({
22782                    "sequence": sequence,
22783                    "signal_name": MESSAGE_STREAM_SIGNAL,
22784                }),
22785            )
22786        }
22787
22788        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22789            history_event(
22790                "SignalApplied",
22791                json!({
22792                    "sequence": sequence,
22793                    "signal_name": MESSAGE_STREAM_SIGNAL,
22794                    "value": fixture_envelope(json!([delivery])),
22795                }),
22796            )
22797        }
22798
22799        fn worker() -> Worker {
22800            let client = Client::new("http://127.0.0.1:8080").expect("client");
22801            let mut worker = Worker::new(client, "rust-workers");
22802            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
22803                let stream = ctx.message_stream("orders")?;
22804                let first = stream.receive_one().await?;
22805                let second = stream.receive_one().await?;
22806                Ok(json!([first.message_id, second.message_id]))
22807            });
22808            worker
22809        }
22810
22811        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
22812            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
22813            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
22814            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
22815            task
22816        }
22817
22818        let waiting = worker()
22819            .execute_workflow_task_decision(workflow_task(
22820                "rust.message-stream",
22821                Vec::new(),
22822                DEFAULT_CODEC,
22823            ))
22824            .expect("first worker opens the stream wait");
22825        assert_eq!(
22826            waiting.commands,
22827            vec![json!({
22828                "type": "open_signal_wait",
22829                "signal_name": MESSAGE_STREAM_SIGNAL,
22830            })]
22831        );
22832        assert!(waiting.message_stream_cursors.is_empty());
22833        assert_eq!(
22834            waiting.message_stream_waits,
22835            vec![json!({"stream_name": "orders", "after_position": 0})]
22836        );
22837
22838        let first_delivery = delivery("message-1", 1, "one");
22839        let first_arrival = worker()
22840            .execute_workflow_task_decision(task_with_resume(
22841                vec![opened(1)],
22842                first_delivery.clone(),
22843            ))
22844            .expect("replacement worker consumes the first arrival");
22845        assert_eq!(
22846            first_arrival.commands,
22847            vec![json!({
22848                "type": "open_signal_wait",
22849                "signal_name": MESSAGE_STREAM_SIGNAL,
22850            })]
22851        );
22852        assert_eq!(
22853            first_arrival.message_stream_cursors,
22854            vec![json!({"stream_name": "orders", "through_position": 1})]
22855        );
22856        assert_eq!(
22857            first_arrival.message_stream_waits,
22858            vec![json!({"stream_name": "orders", "after_position": 1})]
22859        );
22860
22861        let second_delivery = delivery("message-2", 2, "two");
22862        let first_applied = applied(1, first_delivery);
22863        let completed = worker()
22864            .execute_workflow_task_decision(task_with_resume(
22865                vec![opened(1), first_applied.clone(), opened(2)],
22866                second_delivery.clone(),
22867            ))
22868            .expect("next replacement worker consumes the second arrival");
22869        assert_eq!(completed.commands.len(), 1);
22870        assert_eq!(completed.commands[0]["type"], "complete_workflow");
22871        assert_eq!(
22872            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
22873                .expect("workflow result"),
22874            json!(["message-1", "message-2"])
22875        );
22876        assert_eq!(
22877            completed.message_stream_cursors,
22878            vec![json!({"stream_name": "orders", "through_position": 2})]
22879        );
22880        assert!(completed.message_stream_waits.is_empty());
22881
22882        let replay_history = vec![
22883            opened(1),
22884            first_applied,
22885            opened(2),
22886            applied(2, second_delivery),
22887        ];
22888        for _cold_worker_or_restart in 0..2 {
22889            let replayed = worker()
22890                .execute_workflow_task_decision(workflow_task(
22891                    "rust.message-stream",
22892                    replay_history.clone(),
22893                    DEFAULT_CODEC,
22894                ))
22895                .expect("cold worker replays each logical message exactly once");
22896            assert_eq!(replayed.commands.len(), 1);
22897            assert_eq!(
22898                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
22899                    .expect("replayed workflow result"),
22900                json!(["message-1", "message-2"])
22901            );
22902            assert_eq!(
22903                replayed.message_stream_cursors,
22904                vec![json!({"stream_name": "orders", "through_position": 2})]
22905            );
22906            assert!(replayed.message_stream_waits.is_empty());
22907        }
22908    }
22909
22910    #[test]
22911    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
22912        assert!(!worker_protocol_supports_message_streams("1.14"));
22913        assert!(worker_protocol_supports_message_streams("1.15"));
22914        assert!(worker_protocol_supports_message_streams("1.16"));
22915        assert!(worker_protocol_supports_message_streams(
22916            WORKER_PROTOCOL_VERSION
22917        ));
22918        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
22919    }
22920
22921    #[test]
22922    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
22923        let ctx = workflow_context(vec![
22924            history_event(
22925                "ConditionWaitOpened",
22926                json!({
22927                    "sequence": 1,
22928                    "condition_wait_id": "condition:1",
22929                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22930                    "condition_key": "signal:finish",
22931                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
22932                }),
22933            ),
22934            history_event(
22935                "ConditionWaitSatisfied",
22936                json!({
22937                    "sequence": 1,
22938                    "condition_wait_id": "condition:1",
22939                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22940                    "condition_key": "signal:finish",
22941                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
22942                }),
22943            ),
22944            history_event(
22945                "SignalReceived",
22946                json!({"signal_name": "finish", "arguments": []}),
22947            ),
22948        ]);
22949        let mut signal = Box::pin(ctx.wait_signal("finish"));
22950        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22951
22952        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22953            signal.as_mut().poll(&mut task_context)
22954        else {
22955            panic!("condition history must not resolve as a typed signal wait");
22956        };
22957        assert_eq!(failure.reason, "recorded_command_mismatch");
22958        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
22959    }
22960
22961    #[test]
22962    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
22963        let signal_then_timer = vec![
22964            history_event(
22965                "SignalWaitOpened",
22966                json!({"sequence": 1, "signal_name": "go"}),
22967            ),
22968            history_event(
22969                "SignalApplied",
22970                json!({
22971                    "sequence": 1,
22972                    "signal_name": "go",
22973                    "value": fixture_envelope(json!(["now"])),
22974                }),
22975            ),
22976            history_event(
22977                "TimerScheduled",
22978                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
22979            ),
22980            history_event(
22981                "TimerFired",
22982                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
22983            ),
22984        ];
22985
22986        let ctx = workflow_context(signal_then_timer.clone());
22987        let mut signal = Box::pin(ctx.wait_signal("go"));
22988        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22989        assert!(matches!(
22990            signal.as_mut().poll(&mut task_context),
22991            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
22992        ));
22993        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
22994        assert!(matches!(
22995            timer.as_mut().poll(&mut task_context),
22996            Poll::Ready(Ok(()))
22997        ));
22998        ctx.ensure_history_consumed()
22999            .expect("signal and timer history consumed in order");
23000
23001        let reordered = workflow_context(signal_then_timer);
23002        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
23003        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23004            timer_first.as_mut().poll(&mut task_context)
23005        else {
23006            panic!("timer cannot consume signal-wait-first history");
23007        };
23008        assert_eq!(failure.reason, "recorded_command_mismatch");
23009        assert_eq!(failure.sequence, Some(1));
23010        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
23011
23012        let timer_then_signal = vec![
23013            history_event(
23014                "TimerScheduled",
23015                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23016            ),
23017            history_event(
23018                "TimerFired",
23019                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23020            ),
23021            history_event(
23022                "SignalWaitOpened",
23023                json!({"sequence": 2, "signal_name": "go"}),
23024            ),
23025            history_event(
23026                "SignalApplied",
23027                json!({
23028                    "sequence": 2,
23029                    "signal_name": "go",
23030                    "value": fixture_envelope(json!([])),
23031                }),
23032            ),
23033        ];
23034        let reordered = workflow_context(timer_then_signal);
23035        let mut signal_first = Box::pin(reordered.wait_signal("go"));
23036        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23037            signal_first.as_mut().poll(&mut task_context)
23038        else {
23039            panic!("signal wait cannot consume timer-first history");
23040        };
23041        assert_eq!(failure.reason, "recorded_command_mismatch");
23042        assert_eq!(failure.sequence, Some(1));
23043        assert_eq!(failure.expected.as_deref(), Some("timer"));
23044    }
23045
23046    #[test]
23047    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
23048        let duplicate_timer = WorkflowState::new(
23049            vec![
23050                history_event(
23051                    "TimerScheduled",
23052                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23053                ),
23054                history_event(
23055                    "TimerScheduled",
23056                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23057                ),
23058            ],
23059            "rust-workers".to_string(),
23060            DEFAULT_CODEC.to_string(),
23061            None,
23062        )
23063        .expect_err("one workflow sequence cannot schedule two timers");
23064        assert!(matches!(
23065            duplicate_timer,
23066            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23067                if reason == "timer_schedule_missing_or_duplicate"
23068        ));
23069
23070        let colliding_kinds = WorkflowState::new(
23071            vec![
23072                history_event(
23073                    "TimerScheduled",
23074                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23075                ),
23076                history_event(
23077                    "ActivityCompleted",
23078                    json!({"sequence": 1, "activity_type": "same-sequence"}),
23079                ),
23080            ],
23081            "rust-workers".to_string(),
23082            DEFAULT_CODEC.to_string(),
23083            None,
23084        )
23085        .expect_err("one workflow sequence cannot identify two command kinds");
23086        assert!(matches!(
23087            colliding_kinds,
23088            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23089                if reason == "durable_command_sequence_collision"
23090        ));
23091
23092        let duplicate_signal_wait = WorkflowState::new(
23093            vec![
23094                history_event(
23095                    "SignalWaitOpened",
23096                    json!({"sequence": 1, "signal_name": "go"}),
23097                ),
23098                history_event(
23099                    "SignalWaitOpened",
23100                    json!({"sequence": 1, "signal_name": "go"}),
23101                ),
23102            ],
23103            "rust-workers".to_string(),
23104            DEFAULT_CODEC.to_string(),
23105            None,
23106        )
23107        .expect_err("one workflow sequence cannot open two signal waits");
23108        assert!(matches!(
23109            duplicate_signal_wait,
23110            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23111                if reason == "signal_wait_open_missing_or_duplicate"
23112        ));
23113    }
23114
23115    #[test]
23116    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
23117        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
23118            .expect("side-effect result");
23119        let ctx = workflow_context(vec![history_event(
23120            "SideEffectRecorded",
23121            json!({"sequence": 99, "result": result}),
23122        )]);
23123
23124        let replayed: Value = ctx
23125            .side_effect(|| panic!("recorded side effect must not run"))
23126            .expect("positive global workflow sequence is valid");
23127        assert_eq!(replayed, json!({"captured": true}));
23128        ctx.ensure_history_consumed().expect("history consumed");
23129    }
23130
23131    #[test]
23132    fn workflow_history_rejects_zero_and_descending_command_sequences() {
23133        let result =
23134            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
23135        let zero = WorkflowState::new(
23136            vec![history_event(
23137                "SideEffectRecorded",
23138                json!({"sequence": 0, "result": result.clone()}),
23139            )],
23140            "rust-workers".to_string(),
23141            DEFAULT_CODEC.to_string(),
23142            None,
23143        )
23144        .expect_err("durable command sequences must be positive");
23145        assert!(matches!(
23146            zero,
23147            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23148                if reason == "durable_command_sequence_invalid"
23149        ));
23150
23151        let descending = WorkflowState::new(
23152            vec![
23153                history_event(
23154                    "SideEffectRecorded",
23155                    json!({"sequence": 3, "result": result}),
23156                ),
23157                history_event(
23158                    "VersionMarkerRecorded",
23159                    json!({
23160                        "sequence": 2,
23161                        "change_id": "descending-marker",
23162                        "version": 1,
23163                        "min_supported": 1,
23164                        "max_supported": 1,
23165                    }),
23166                ),
23167            ],
23168            "rust-workers".to_string(),
23169            DEFAULT_CODEC.to_string(),
23170            None,
23171        )
23172        .expect_err("new durable commands must remain strictly ordered");
23173        let Error::NonDeterministicReplay(failure) = descending else {
23174            panic!("expected typed replay failure");
23175        };
23176        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
23177        assert_eq!(failure.sequence, Some(2));
23178        assert_eq!(
23179            failure.expected.as_deref(),
23180            Some("workflow sequence greater than 3")
23181        );
23182        assert_eq!(failure.actual.as_deref(), Some("2"));
23183    }
23184
23185    #[test]
23186    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
23187        fn worker() -> Worker {
23188            let client = Client::new("http://127.0.0.1:8080").expect("client");
23189            let mut worker = Worker::new(client, "rust-workers");
23190            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
23191                ctx.wait_signal("finish").await?;
23192                let marker: String =
23193                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
23194                assert_eq!(marker, "after-finish");
23195                Ok(json!("finished"))
23196            });
23197            worker
23198        }
23199
23200        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
23201            .expect("side-effect result");
23202        let task = workflow_task(
23203            "rust.finish-after-gaps",
23204            vec![
23205                history_event(
23206                    "SignalWaitOpened",
23207                    json!({"sequence": 1, "signal_name": "finish"}),
23208                ),
23209                history_event(
23210                    "SignalReceived",
23211                    json!({
23212                        "signal_id": "increment-3",
23213                        "signal_name": "increment",
23214                        "workflow_sequence": 2,
23215                        "payload_codec": DEFAULT_CODEC,
23216                        "arguments": fixture_envelope(json!([3])),
23217                    }),
23218                ),
23219                history_event(
23220                    "SignalReceived",
23221                    json!({
23222                        "signal_id": "increment-5",
23223                        "signal_name": "increment",
23224                        "workflow_sequence": 3,
23225                        "payload_codec": DEFAULT_CODEC,
23226                        "arguments": fixture_envelope(json!([5])),
23227                    }),
23228                ),
23229                history_event(
23230                    "SignalReceived",
23231                    json!({
23232                        "signal_id": "finish",
23233                        "signal_name": "finish",
23234                        "workflow_sequence": 4,
23235                        "payload_codec": DEFAULT_CODEC,
23236                        "arguments": fixture_envelope(json!([])),
23237                    }),
23238                ),
23239                history_event(
23240                    "SignalApplied",
23241                    json!({
23242                        "sequence": 1,
23243                        "signal_id": "finish",
23244                        "signal_name": "finish",
23245                        "payload_codec": DEFAULT_CODEC,
23246                        "value": fixture_envelope(json!([])),
23247                    }),
23248                ),
23249                history_event(
23250                    "SideEffectRecorded",
23251                    json!({"sequence": 5, "result": marker}),
23252                ),
23253            ],
23254            DEFAULT_CODEC,
23255        );
23256
23257        for _original_or_cold_worker in 0..2 {
23258            let commands = worker()
23259                .execute_workflow_task(task.clone())
23260                .expect("signal gaps preserve deterministic replay");
23261            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
23262            assert_eq!(commands[0]["type"], "complete_workflow");
23263            assert_eq!(
23264                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23265                json!("finished")
23266            );
23267        }
23268    }
23269
23270    #[test]
23271    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
23272        let ctx = workflow_context(Vec::new());
23273        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
23274        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23275        assert!(matches!(
23276            sleep.as_mut().poll(&mut task_context),
23277            Poll::Ready(Err(Error::TimerDurationOverflow))
23278        ));
23279        assert!(ctx.take_commands().expect("commands").is_empty());
23280    }
23281
23282    #[test]
23283    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
23284        let entries = AvroValue::Map(BTreeMap::from([
23285            ("text".to_string(), AvroValue::String("same".to_string())),
23286            (
23287                "nested".to_string(),
23288                AvroValue::Map(BTreeMap::from([
23289                    ("beta".to_string(), AvroValue::Long(2)),
23290                    ("alpha".to_string(), AvroValue::Long(1)),
23291                ])),
23292            ),
23293            ("long".to_string(), AvroValue::Long(7)),
23294            ("double".to_string(), AvroValue::Double(7.0)),
23295            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
23296        ]));
23297        let ctx = workflow_context(Vec::new());
23298        ctx.upsert_memo(entries.clone()).expect("valid memo update");
23299        let commands = ctx.take_commands().expect("commands");
23300
23301        assert_eq!(commands.len(), 1);
23302        assert_eq!(commands[0]["type"], "upsert_memo");
23303        let server_entries = json!({
23304            "codec": "avro",
23305            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
23306        });
23307        assert_eq!(
23308            commands[0]["entries"]
23309                .as_object()
23310                .expect("entries envelope")
23311                .keys()
23312                .collect::<Vec<_>>(),
23313            vec!["blob", "codec"]
23314        );
23315        assert_eq!(commands[0]["entries"], server_entries);
23316        let wire_entries =
23317            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
23318        assert_eq!(wire_entries, entries);
23319
23320        let history = vec![history_event(
23321            "MemoUpserted",
23322            json!({
23323                "sequence": 1,
23324                "entries": server_entries.clone(),
23325                "merged": server_entries,
23326            }),
23327        )];
23328        let replay = workflow_context(history.clone());
23329        replay
23330            .upsert_memo(entries.clone())
23331            .expect("matching replay identity");
23332        assert!(replay.take_commands().expect("replay commands").is_empty());
23333
23334        let changed_types = AvroValue::Map(BTreeMap::from([
23335            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
23336            (
23337                "nested".to_string(),
23338                AvroValue::Map(BTreeMap::from([
23339                    ("alpha".to_string(), AvroValue::Long(1)),
23340                    ("beta".to_string(), AvroValue::Long(2)),
23341                ])),
23342            ),
23343            ("long".to_string(), AvroValue::Double(7.0)),
23344            ("double".to_string(), AvroValue::Long(7)),
23345            ("binary".to_string(), AvroValue::String("same".to_string())),
23346        ]));
23347        let error = workflow_context(history)
23348            .upsert_memo(changed_types)
23349            .expect_err("memo replay identity must preserve Avro value types");
23350        assert!(matches!(
23351            error,
23352            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23353        ));
23354    }
23355
23356    #[test]
23357    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
23358        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
23359            .expect("memo envelope");
23360        let replay = workflow_context(vec![history_event(
23361            "MemoUpserted",
23362            json!({
23363                "sequence": 1,
23364                "entries": original.clone(),
23365                "merged": original
23366            }),
23367        )]);
23368        let error = replay
23369            .upsert_memo(json!({"stage": "changed"}))
23370            .expect_err("changed memo update must fail replay");
23371        assert!(matches!(
23372            error,
23373            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23374        ));
23375
23376        let invalid = workflow_context(Vec::new())
23377            .upsert_memo(
23378                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
23379            )
23380            .expect_err("oversized key");
23381        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
23382    }
23383
23384    #[test]
23385    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
23386        let negative_zero = AvroValue::Map(BTreeMap::from([(
23387            "reading".to_string(),
23388            AvroValue::Double(-0.0),
23389        )]));
23390        let negative_zero_envelope =
23391            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
23392        let history = vec![history_event(
23393            "MemoUpserted",
23394            json!({
23395                "sequence": 1,
23396                "entries": negative_zero_envelope.clone(),
23397                "merged": negative_zero_envelope,
23398            }),
23399        )];
23400
23401        workflow_context(history.clone())
23402            .upsert_memo(negative_zero)
23403            .expect("matching negative-zero history identity");
23404
23405        let error = workflow_context(history)
23406            .upsert_memo(AvroValue::Map(BTreeMap::from([(
23407                "reading".to_string(),
23408                AvroValue::Double(0.0),
23409            )])))
23410            .expect_err("positive zero must not consume negative-zero memo history");
23411        assert!(matches!(
23412            error,
23413            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23414        ));
23415    }
23416
23417    #[test]
23418    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
23419        let supported = json!({
23420            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
23421            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
23422        });
23423        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
23424        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
23425            "workflow_memo_updates": {"supported": false},
23426            "supported_workflow_task_commands": ["upsert_memo"]
23427        }))));
23428        assert!(commands_use_workflow_memo_updates(&[json!({
23429            "type": "upsert_memo",
23430            "entries": {"stage": "processing"}
23431        })]));
23432    }
23433
23434    #[test]
23435    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
23436        let client = Client::new("http://127.0.0.1:8080").expect("client");
23437        let mut worker = Worker::new(client, "rust-workers");
23438        worker.register_workflow("rust.timer", |ctx, _input| async move {
23439            ctx.sleep(Duration::from_secs(5)).await?;
23440            ctx.activity("after-timer", json!([])).await
23441        });
23442
23443        let task = |history_events| WorkflowTask {
23444            task_id: "wft-rust-timer-1".to_string(),
23445            workflow_command_id: None,
23446            workflow_id: Some("wf-rust-timer".to_string()),
23447            run_id: Some("run-rust-timer".to_string()),
23448            workflow_type: "rust.timer".to_string(),
23449            cancel_requested: false,
23450            payload_codec: DEFAULT_CODEC.to_string(),
23451            arguments: Some(
23452                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23453            ),
23454            history_events,
23455            total_history_events: None,
23456            history_size_bytes: None,
23457            continue_as_new_recommended: None,
23458            history_budget_pressure: None,
23459            next_history_page_token: None,
23460            workflow_task_attempt: 1,
23461            workflow_signal_id: None,
23462            signal_name: None,
23463            signal_arguments: None,
23464            workflow_update_id: None,
23465            update_name: None,
23466            lease_owner: Some("rust-worker".to_string()),
23467        };
23468
23469        let initial = worker
23470            .execute_workflow_task(task(Vec::new()))
23471            .expect("initial timer task");
23472        assert_eq!(
23473            initial,
23474            vec![json!({"type": "start_timer", "delay_seconds": 5})]
23475        );
23476
23477        let activity_result =
23478            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
23479        let replayed = worker
23480            .execute_workflow_task(task(vec![
23481                history_event(
23482                    "TimerScheduled",
23483                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23484                ),
23485                history_event(
23486                    "TimerFired",
23487                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23488                ),
23489                history_event(
23490                    "ActivityCompleted",
23491                    json!({
23492                        "sequence": 2,
23493                        "activity_type": "after-timer",
23494                        "payload_codec": DEFAULT_CODEC,
23495                        "result": activity_result,
23496                    }),
23497                ),
23498            ]))
23499            .expect("replayed workflow task");
23500        assert_eq!(replayed.len(), 1);
23501        assert_eq!(replayed[0]["type"], "complete_workflow");
23502        assert_eq!(
23503            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
23504            json!("done")
23505        );
23506    }
23507
23508    #[test]
23509    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
23510        let client = Client::new("http://127.0.0.1:8080").expect("client");
23511        let mut worker = Worker::new(client, "rust-workers");
23512        worker.register_workflow("rust.continue", |ctx, _input| async move {
23513            ctx.continue_as_new_with_options(
23514                ContinueAsNewOptions::new()
23515                    .workflow_type("rust.next")
23516                    .task_queue("next-workers"),
23517                json!([2, {"cursor": "next"}]),
23518            )
23519        });
23520
23521        let commands = worker
23522            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
23523            .expect("continue-as-new command");
23524
23525        assert_eq!(commands.len(), 1);
23526        assert_eq!(commands[0]["type"], "continue_as_new");
23527        assert_eq!(commands[0]["workflow_type"], "rust.next");
23528        assert_eq!(commands[0]["queue"], "next-workers");
23529        assert_eq!(
23530            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
23531                .expect("continue-as-new arguments"),
23532            json!([2, {"cursor": "next"}])
23533        );
23534    }
23535
23536    #[test]
23537    fn continue_as_new_preserves_typed_arguments() {
23538        let client = Client::new("http://127.0.0.1:8080").expect("client");
23539        let mut worker = Worker::new(client, "rust-workers");
23540        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
23541            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
23542            unreachable!("continue-as-new returns a control-flow error")
23543        });
23544
23545        let commands = worker
23546            .execute_workflow_task(workflow_task(
23547                "rust.typed-continue",
23548                Vec::new(),
23549                DEFAULT_CODEC,
23550            ))
23551            .expect("typed continue-as-new command");
23552
23553        assert_eq!(commands[0]["type"], "continue_as_new");
23554        assert_eq!(
23555            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
23556                .expect("typed continue arguments"),
23557            AvroValue::Array(vec![typed_fidelity_probe()])
23558        );
23559    }
23560
23561    #[test]
23562    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
23563        let client = Client::new("http://127.0.0.1:8080").expect("client");
23564        let mut worker = Worker::new(client, "rust-workers");
23565        worker.register_workflow("rust.continue", |ctx, _input| async move {
23566            ctx.continue_as_new(json!([2]))
23567        });
23568        let task = workflow_task(
23569            "rust.continue",
23570            vec![history_event(
23571                "WorkflowContinuedAsNew",
23572                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
23573            )],
23574            DEFAULT_CODEC,
23575        );
23576
23577        for _worker_restart_or_redelivery in 0..2 {
23578            let commands = worker
23579                .execute_workflow_task(task.clone())
23580                .expect("recorded transition replays");
23581            assert!(
23582                commands.is_empty(),
23583                "replay must not emit another successor"
23584            );
23585        }
23586    }
23587
23588    #[test]
23589    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
23590        let ctx = workflow_context(Vec::new());
23591        let error = ctx
23592            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
23593            .expect_err("blank queue must be rejected");
23594
23595        let Error::InvalidContinueAsNewOptions(error) = error else {
23596            panic!("expected typed continue-as-new validation error");
23597        };
23598        assert_eq!(error.field, "task_queue");
23599        assert!(ctx.take_commands().expect("commands").is_empty());
23600    }
23601
23602    #[test]
23603    fn workflow_context_exposes_server_history_budget() {
23604        let client = Client::new("http://127.0.0.1:8080").expect("client");
23605        let mut worker = Worker::new(client, "rust-workers");
23606        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
23607            let budget = ctx.history_budget()?;
23608            Ok(json!({
23609                "events": budget.event_count,
23610                "bytes": budget.size_bytes,
23611                "recommended": budget.continue_as_new_recommended,
23612                "pressure": budget.pressure,
23613            }))
23614        });
23615        let task: WorkflowTask = serde_json::from_value(json!({
23616            "task_id": "task-history-budget",
23617            "workflow_type": "rust.history-budget",
23618            "payload_codec": DEFAULT_CODEC,
23619            "history_events": [],
23620            "total_history_events": 480,
23621            "history_size_bytes": 1_048_576,
23622            "continue_as_new_recommended": true,
23623            "history_budget_pressure": "continue_as_new_recommended",
23624        }))
23625        .expect("published workflow task");
23626
23627        let commands = worker
23628            .execute_workflow_task(task)
23629            .expect("history-budget workflow");
23630        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
23631        assert_eq!(result["events"], 480);
23632        assert_eq!(result["bytes"], 1_048_576);
23633        assert_eq!(result["recommended"], true);
23634        assert_eq!(result["pressure"], "continue_as_new_recommended");
23635    }
23636
23637    #[test]
23638    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
23639        let client = Client::new("http://127.0.0.1:8080").expect("client");
23640        let mut worker = Worker::new(client, "rust-workers");
23641        worker.register_workflow("rust.failing", |_ctx, _input| async move {
23642            Err(Error::Codec("rust_conformance_failure".to_string()))
23643        });
23644        let task = WorkflowTask {
23645            task_id: "wft-rust-failing-1".to_string(),
23646            workflow_command_id: None,
23647            workflow_id: Some("wf-rust-failing".to_string()),
23648            run_id: Some("run-rust-failing".to_string()),
23649            workflow_type: "rust.failing".to_string(),
23650            cancel_requested: false,
23651            payload_codec: DEFAULT_CODEC.to_string(),
23652            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
23653            history_events: Vec::new(),
23654            total_history_events: Some(0),
23655            history_size_bytes: None,
23656            continue_as_new_recommended: None,
23657            history_budget_pressure: None,
23658            next_history_page_token: None,
23659            workflow_task_attempt: 1,
23660            workflow_signal_id: None,
23661            signal_name: None,
23662            signal_arguments: None,
23663            workflow_update_id: None,
23664            update_name: None,
23665            lease_owner: Some("rust-worker".to_string()),
23666        };
23667
23668        let commands = worker
23669            .execute_workflow_task(task)
23670            .expect("handler failure becomes a workflow command");
23671
23672        assert_eq!(commands.len(), 1);
23673        assert_eq!(commands[0]["type"], "fail_workflow");
23674        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
23675        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
23676        assert_eq!(commands[0]["non_retryable"], false);
23677        assert_eq!(
23678            commands[0]["message"],
23679            "codec error: rust_conformance_failure"
23680        );
23681        assert_eq!(
23682            commands[0]["exception"]["message"],
23683            "codec error: rust_conformance_failure"
23684        );
23685    }
23686
23687    #[test]
23688    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
23689        let client = Client::new("http://127.0.0.1:8080").expect("client");
23690        let mut worker = Worker::new(client, "rust-workers");
23691        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
23692            let _: String = ctx.side_effect(|| "captured".to_string())?;
23693            Err(Error::WorkerLoop("application failure".to_string()))
23694        });
23695
23696        let commands = worker
23697            .execute_workflow_task(workflow_task(
23698                "rust.failing-after-side-effect",
23699                Vec::new(),
23700                DEFAULT_CODEC,
23701            ))
23702            .expect("ordinary failure remains a workflow decision");
23703
23704        assert_eq!(commands.len(), 2);
23705        assert_eq!(commands[0]["type"], "record_side_effect");
23706        assert_eq!(commands[1]["type"], "fail_workflow");
23707    }
23708
23709    #[test]
23710    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
23711        let client = Client::new("http://127.0.0.1:8080").expect("client");
23712        let mut worker = Worker::new(client, "rust-workers");
23713        worker.register_workflow("rust.redrive", |ctx, _input| async move {
23714            ctx.activity("greet", json!([])).await?;
23715            Ok(Value::Null)
23716        });
23717        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
23718            match ctx.activity("greet", json!([])).await {
23719                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
23720                result => result,
23721            }
23722        });
23723
23724        let failed = history_event(
23725            "ActivityFailed",
23726            json!({
23727                "sequence": 1,
23728                "activity_type": "greet",
23729                "activity_execution_id": "activity-1",
23730                "message": "failed"
23731            }),
23732        );
23733        let commands = worker
23734            .execute_workflow_task(workflow_task(
23735                "rust.redrive",
23736                vec![failed.clone()],
23737                DEFAULT_CODEC,
23738            ))
23739            .expect("recorded failure becomes a workflow command");
23740        assert_eq!(commands[0]["type"], "fail_workflow");
23741        assert_eq!(commands[0]["failed_step_sequence"], 1);
23742        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
23743
23744        let translated = worker
23745            .execute_workflow_task(workflow_task(
23746                "rust.redrive-translated",
23747                vec![failed],
23748                DEFAULT_CODEC,
23749            ))
23750            .expect("translated failure becomes a workflow command");
23751        assert_eq!(translated[0]["type"], "fail_workflow");
23752        assert!(translated[0].get("failed_step_sequence").is_none());
23753        assert!(translated[0].get("failed_activity_execution_id").is_none());
23754
23755        let without_identity = worker
23756            .execute_workflow_task(workflow_task(
23757                "rust.redrive",
23758                vec![history_event(
23759                    "ActivityFailed",
23760                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
23761                )],
23762                DEFAULT_CODEC,
23763            ))
23764            .expect("incomplete identity still fails the workflow");
23765        assert!(without_identity[0].get("failed_step_sequence").is_none());
23766
23767        let timed_out = worker
23768            .execute_workflow_task(workflow_task(
23769                "rust.redrive",
23770                vec![history_event(
23771                    "ActivityTimedOut",
23772                    json!({
23773                        "sequence": 1,
23774                        "activity_type": "greet",
23775                        "activity_execution_id": "activity-timeout",
23776                    }),
23777                )],
23778                DEFAULT_CODEC,
23779            ))
23780            .expect("timeout still fails the workflow");
23781        assert!(timed_out[0].get("failed_step_sequence").is_none());
23782    }
23783
23784    #[test]
23785    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
23786        let client = Client::new("http://127.0.0.1:8080").expect("client");
23787        let mut worker = Worker::new(client, "rust-workers");
23788        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
23789            let first = ctx.activity("first", json!([])).await?;
23790            let second = ctx.activity("second", json!([first.clone()])).await?;
23791            Ok(json!({"first": first, "second": second}))
23792        });
23793        let first = history_event(
23794            "ActivityCompleted",
23795            json!({
23796                "sequence": 1,
23797                "activity_type": "first",
23798                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
23799                "payload_codec": DEFAULT_CODEC,
23800                "reused_from_run_id": "failed-run",
23801                "reused_activity_execution_id": "original-first",
23802            }),
23803        );
23804
23805        let retry = worker
23806            .execute_workflow_task(workflow_task(
23807                "rust.redrive-successor",
23808                vec![first.clone()],
23809                DEFAULT_CODEC,
23810            ))
23811            .expect("reused result replays before failed step");
23812        assert_eq!(retry.len(), 1);
23813        assert_eq!(retry[0]["type"], "schedule_activity");
23814        assert_eq!(retry[0]["activity_type"], "second");
23815        assert_eq!(
23816            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
23817            json!(["recorded"]),
23818        );
23819
23820        let second = history_event(
23821            "ActivityCompleted",
23822            json!({
23823                "sequence": 2,
23824                "activity_type": "second",
23825                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
23826                "payload_codec": DEFAULT_CODEC,
23827            }),
23828        );
23829        let completed = worker
23830            .execute_workflow_task(workflow_task(
23831                "rust.redrive-successor",
23832                vec![first, second],
23833                DEFAULT_CODEC,
23834            ))
23835            .expect("retried step completes the successor");
23836        assert_eq!(completed.len(), 1);
23837        assert_eq!(completed[0]["type"], "complete_workflow");
23838        assert_eq!(
23839            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
23840            json!({"first": "recorded", "second": "retried"}),
23841        );
23842    }
23843
23844    #[test]
23845    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
23846        let client = Client::new("http://127.0.0.1:8080").expect("client");
23847        let mut worker = Worker::new(client, "rust-workers");
23848        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
23849            Err(Error::WorkerLoop("application failure".to_string()))
23850        });
23851        let result =
23852            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
23853
23854        let error = worker
23855            .execute_workflow_task(workflow_task(
23856                "rust.removed-side-effect",
23857                vec![history_event(
23858                    "SideEffectRecorded",
23859                    json!({"sequence": 1, "result": result}),
23860                )],
23861                DEFAULT_CODEC,
23862            ))
23863            .expect_err("removed committed history must not become fail_workflow");
23864
23865        let Error::NonDeterministicReplay(failure) = error else {
23866            panic!("expected typed replay failure");
23867        };
23868        assert_eq!(failure.reason, "recorded_commands_unconsumed");
23869        assert_eq!(failure.sequence, Some(1));
23870        assert_eq!(failure.expected.as_deref(), Some("side effect"));
23871    }
23872
23873    #[test]
23874    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
23875        let client = Client::new("http://127.0.0.1:8080").expect("client");
23876        let mut worker = Worker::new(client, "rust-workers");
23877        worker.register_workflow(
23878            "rust.side-effect-before-marker-error",
23879            |ctx, _input| async move {
23880                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
23881                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
23882                ctx.get_version("restart-safe", 2, 2)?;
23883                Ok(Value::Null)
23884            },
23885        );
23886
23887        let error = worker
23888            .execute_workflow_task(workflow_task(
23889                "rust.side-effect-before-marker-error",
23890                vec![history_event(
23891                    "VersionMarkerRecorded",
23892                    json!({
23893                        "sequence": 1,
23894                        "change_id": "restart-safe",
23895                        "version": 1,
23896                        "min_supported": 1,
23897                        "max_supported": 1,
23898                    }),
23899                )],
23900                DEFAULT_CODEC,
23901            ))
23902            .expect_err("replay error must return no queued workflow commands");
23903
23904        let Error::NonDeterministicReplay(failure) = error else {
23905            panic!("expected typed replay failure");
23906        };
23907        assert_eq!(failure.reason, "version_marker_incompatible_range");
23908        assert_eq!(failure.sequence, Some(1));
23909    }
23910
23911    #[test]
23912    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
23913        let client = Client::new("http://127.0.0.1:8080").expect("client");
23914        let mut worker = Worker::new(client, "rust-workers");
23915        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
23916            ctx.sleep(Duration::from_secs(5)).await?;
23917            Ok(json!({"status": "timer fired"}))
23918        });
23919
23920        let task = WorkflowTask {
23921            task_id: "wft-rust-timer-pending".to_string(),
23922            workflow_command_id: None,
23923            workflow_id: Some("wf-rust-timer".to_string()),
23924            run_id: Some("run-rust-timer".to_string()),
23925            workflow_type: "rust.timer.pending".to_string(),
23926            cancel_requested: false,
23927            payload_codec: DEFAULT_CODEC.to_string(),
23928            arguments: Some(
23929                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23930            ),
23931            history_events: vec![history_event(
23932                "TimerScheduled",
23933                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23934            )],
23935            total_history_events: Some(1),
23936            history_size_bytes: None,
23937            continue_as_new_recommended: None,
23938            history_budget_pressure: None,
23939            next_history_page_token: None,
23940            workflow_task_attempt: 1,
23941            workflow_signal_id: None,
23942            signal_name: None,
23943            signal_arguments: None,
23944            workflow_update_id: None,
23945            update_name: None,
23946            lease_owner: Some("rust-worker".to_string()),
23947        };
23948
23949        for _redelivery_or_restart in 0..2 {
23950            let commands = worker
23951                .execute_workflow_task(task.clone())
23952                .expect("recorded timer remains pending");
23953            assert!(
23954                commands.is_empty(),
23955                "recorded timer must not be rescheduled"
23956            );
23957        }
23958    }
23959
23960    #[test]
23961    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
23962        let client = Client::new("http://127.0.0.1:8080").expect("client");
23963        let mut worker = Worker::new(client, "rust-workers");
23964        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
23965            Ok(json!({"status": "completed"}))
23966        });
23967        let task = WorkflowTask {
23968            task_id: "wft-rust-timer-removed".to_string(),
23969            workflow_command_id: None,
23970            workflow_id: Some("wf-rust-timer".to_string()),
23971            run_id: Some("run-rust-timer".to_string()),
23972            workflow_type: "rust.timer.removed".to_string(),
23973            cancel_requested: false,
23974            payload_codec: DEFAULT_CODEC.to_string(),
23975            arguments: Some(
23976                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23977            ),
23978            history_events: vec![
23979                history_event(
23980                    "TimerScheduled",
23981                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23982                ),
23983                history_event(
23984                    "TimerFired",
23985                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23986                ),
23987            ],
23988            total_history_events: Some(2),
23989            history_size_bytes: None,
23990            continue_as_new_recommended: None,
23991            history_budget_pressure: None,
23992            next_history_page_token: None,
23993            workflow_task_attempt: 1,
23994            workflow_signal_id: None,
23995            signal_name: None,
23996            signal_arguments: None,
23997            workflow_update_id: None,
23998            update_name: None,
23999            lease_owner: Some("rust-worker".to_string()),
24000        };
24001
24002        let Error::NonDeterministicReplay(failure) = worker
24003            .execute_workflow_task(task)
24004            .expect_err("removed timer must fail replay")
24005        else {
24006            panic!("expected typed replay failure");
24007        };
24008        assert_eq!(failure.reason, "recorded_commands_unconsumed");
24009        assert_eq!(failure.sequence, Some(1));
24010    }
24011
24012    #[test]
24013    fn workflow_context_emits_explicit_child_workflow_contract() {
24014        let ctx = WorkflowContext {
24015            cancellation_scope_id: "root".into(),
24016            state: Arc::new(Mutex::new(
24017                WorkflowState::new_with_identity(
24018                    Vec::new(),
24019                    Some("wf-parent".to_string()),
24020                    Some("run-parent".to_string()),
24021                    "parent-workers".to_string(),
24022                    DEFAULT_CODEC.to_string(),
24023                    None,
24024                )
24025                .expect("workflow state"),
24026            )),
24027        };
24028        let options = ChildWorkflowOptions::new("python-workers")
24029            .parent_close_policy(ParentClosePolicy::RequestCancel)
24030            .retry_policy(ChildWorkflowRetryPolicy {
24031                max_attempts: Some(3),
24032                backoff_seconds: vec![1, 5],
24033                non_retryable_error_types: vec!["ValidationError".to_string()],
24034            })
24035            .execution_timeout_seconds(600)
24036            .run_timeout_seconds(120);
24037        let mut call = Box::pin(ctx.start_child_workflow(
24038            "python.fulfil-order",
24039            options,
24040            json!([{"order_id": "order-42"}]),
24041        ));
24042        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24043
24044        assert!(matches!(
24045            call.as_mut().poll(&mut task_context),
24046            Poll::Pending
24047        ));
24048        let commands = ctx.take_commands().expect("commands");
24049        assert_eq!(commands.len(), 1);
24050        let command = &commands[0];
24051        assert_eq!(command["type"], "start_child_workflow");
24052        assert_eq!(command["workflow_type"], "python.fulfil-order");
24053        assert_eq!(command["queue"], "python-workers");
24054        assert_eq!(command["parent_close_policy"], "request_cancel");
24055        assert_eq!(command["retry_policy"]["max_attempts"], 3);
24056        assert_eq!(command["execution_timeout_seconds"], 600);
24057        assert_eq!(command["run_timeout_seconds"], 120);
24058        assert_eq!(
24059            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
24060            json!([{"order_id": "order-42"}])
24061        );
24062    }
24063
24064    fn child_parent_worker() -> Worker {
24065        let client = Client::new("http://127.0.0.1:8080").expect("client");
24066        let mut worker = Worker::new(client, "rust-parent-workers");
24067        worker.register_workflow("rust.parent", |ctx, _input| async move {
24068            let child = ctx
24069                .start_child_workflow(
24070                    "python.child",
24071                    ChildWorkflowOptions::new("python-child-workers")
24072                        .parent_close_policy(ParentClosePolicy::Terminate),
24073                    json!([{"codec_probe": [1, true, "rust"]}]),
24074                )
24075                .await?;
24076            Ok(json!({
24077                "parent_workflow_id": child.parent.workflow_id,
24078                "parent_run_id": child.parent.run_id,
24079                "child_workflow_id": child.child.workflow_id,
24080                "child_run_id": child.child.run_id,
24081                "child_workflow_type": child.child_workflow_type,
24082                "result": child.result,
24083            }))
24084        });
24085        worker
24086    }
24087
24088    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
24089        WorkflowTask {
24090            task_id: "wft-child-parent".to_string(),
24091            workflow_command_id: None,
24092            workflow_id: Some("wf-parent".to_string()),
24093            run_id: Some("run-parent".to_string()),
24094            workflow_type: "rust.parent".to_string(),
24095            cancel_requested: false,
24096            payload_codec: DEFAULT_CODEC.to_string(),
24097            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24098            history_events: vec![
24099                HistoryEvent {
24100                    event_type: "ChildWorkflowScheduled".to_string(),
24101                    payload: json!({
24102                        "sequence": 1,
24103                        "child_call_id": "call-child",
24104                        "child_workflow_instance_id": "wf-child",
24105                        "child_workflow_run_id": "run-child",
24106                        "child_workflow_type": "python.child",
24107                        "parent_close_policy": "terminate",
24108                    }),
24109                    raw: HashMap::new(),
24110                },
24111                HistoryEvent {
24112                    event_type: event_type.to_string(),
24113                    payload,
24114                    raw: HashMap::new(),
24115                },
24116            ],
24117            total_history_events: Some(2),
24118            history_size_bytes: None,
24119            continue_as_new_recommended: None,
24120            history_budget_pressure: None,
24121            next_history_page_token: None,
24122            workflow_task_attempt: 1,
24123            workflow_signal_id: None,
24124            signal_name: None,
24125            signal_arguments: None,
24126            workflow_update_id: None,
24127            update_name: None,
24128            lease_owner: Some("rust-worker".to_string()),
24129        }
24130    }
24131
24132    #[test]
24133    fn committed_child_result_replays_without_starting_a_duplicate() {
24134        let worker = child_parent_worker();
24135        let task = child_parent_task(
24136            "ChildRunCompleted",
24137            json!({
24138                "sequence": 1,
24139                "child_call_id": "call-child",
24140                "child_workflow_instance_id": "wf-child",
24141                "child_workflow_run_id": "run-child",
24142                "child_workflow_type": "python.child",
24143                "payload_codec": DEFAULT_CODEC,
24144                "result": fixture_envelope(json!({"from":"python","ok":true})),
24145            }),
24146        );
24147
24148        for _restart in 0..2 {
24149            let commands = worker
24150                .execute_workflow_task(task.clone())
24151                .expect("replayed parent task");
24152            assert_eq!(commands.len(), 1);
24153            assert_eq!(commands[0]["type"], "complete_workflow");
24154            assert!(!commands
24155                .iter()
24156                .any(|command| command["type"] == "start_child_workflow"));
24157            let output =
24158                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
24159            assert_eq!(output["parent_workflow_id"], "wf-parent");
24160            assert_eq!(output["parent_run_id"], "run-parent");
24161            assert_eq!(output["child_workflow_id"], "wf-child");
24162            assert_eq!(output["child_run_id"], "run-child");
24163            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
24164        }
24165    }
24166
24167    #[test]
24168    fn typed_child_arguments_and_results_survive_replay() {
24169        let client = Client::new("http://127.0.0.1:8080").expect("client");
24170        let mut worker = Worker::new(client, "rust-parent-workers");
24171        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
24172            let child = ctx
24173                .start_child_workflow_avro_value(
24174                    "python.typed-child",
24175                    ChildWorkflowOptions::new("python-workers"),
24176                    AvroValue::Array(vec![typed_fidelity_probe()]),
24177                )
24178                .await?;
24179            Ok(child.result)
24180        });
24181
24182        let initial = worker
24183            .execute_workflow_task(workflow_task(
24184                "rust.typed-parent",
24185                Vec::new(),
24186                DEFAULT_CODEC,
24187            ))
24188            .expect("typed child start");
24189        assert_eq!(initial[0]["type"], "start_child_workflow");
24190        assert_eq!(
24191            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
24192                .expect("typed child arguments"),
24193            AvroValue::Array(vec![typed_fidelity_probe()])
24194        );
24195
24196        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
24197            .expect("typed child result");
24198        let task = workflow_task(
24199            "rust.typed-parent",
24200            vec![
24201                history_event(
24202                    "ChildWorkflowScheduled",
24203                    json!({
24204                        "sequence": 1,
24205                        "child_call_id": "call-typed",
24206                        "child_workflow_instance_id": "wf-child",
24207                        "child_workflow_run_id": "run-child",
24208                        "child_workflow_type": "python.typed-child",
24209                    }),
24210                ),
24211                history_event(
24212                    "ChildRunCompleted",
24213                    json!({
24214                        "sequence": 1,
24215                        "child_call_id": "call-typed",
24216                        "child_workflow_instance_id": "wf-child",
24217                        "child_workflow_run_id": "run-child",
24218                        "child_workflow_type": "python.typed-child",
24219                        "payload_codec": DEFAULT_CODEC,
24220                        "result": result,
24221                    }),
24222                ),
24223            ],
24224            DEFAULT_CODEC,
24225        );
24226
24227        let commands = worker
24228            .execute_workflow_task(task)
24229            .expect("typed child replay");
24230        assert_eq!(commands[0]["type"], "complete_workflow");
24231        assert_eq!(
24232            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
24233                .expect("typed parent result"),
24234            typed_fidelity_probe()
24235        );
24236    }
24237
24238    #[test]
24239    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
24240        let worker = child_parent_worker();
24241        let mut task = child_parent_task("unused", Value::Null);
24242        task.history_events.truncate(1);
24243        task.total_history_events = Some(1);
24244
24245        for _redelivery_or_restart in 0..2 {
24246            let commands = worker
24247                .execute_workflow_task(task.clone())
24248                .expect("recorded child remains pending");
24249            assert!(
24250                commands.is_empty(),
24251                "recorded pending child must not be started again"
24252            );
24253        }
24254    }
24255
24256    #[test]
24257    fn child_cancellation_becomes_stable_parent_failure_command() {
24258        let worker = child_parent_worker();
24259        let task = child_parent_task(
24260            "ChildRunCancelled",
24261            json!({
24262                "sequence": 1,
24263                "child_workflow_instance_id": "wf-child",
24264                "child_workflow_run_id": "run-child",
24265                "child_workflow_type": "python.child",
24266                "failure_id": "failure-child",
24267                "failure_category": "cancelled",
24268                "message": "cancelled by parent-close policy",
24269            }),
24270        );
24271
24272        let commands = worker
24273            .execute_workflow_task(task)
24274            .expect("parent settlement");
24275        assert_eq!(commands.len(), 1);
24276        assert_eq!(commands[0]["type"], "fail_workflow");
24277        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
24278        assert_eq!(
24279            commands[0]["exception"]["properties"]["reason"],
24280            "cancelled"
24281        );
24282        assert_eq!(
24283            commands[0]["exception"]["properties"]["child_workflow_run_id"],
24284            "run-child"
24285        );
24286    }
24287
24288    #[test]
24289    fn workflow_can_handle_typed_child_failure() {
24290        let client = Client::new("http://127.0.0.1:8080").expect("client");
24291        let mut worker = Worker::new(client, "rust-parent-workers");
24292        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
24293            match ctx
24294                .start_child_workflow(
24295                    "python.child",
24296                    ChildWorkflowOptions::new("python-child-workers"),
24297                    json!([]),
24298                )
24299                .await
24300            {
24301                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
24302                    "reason": failure.reason,
24303                    "failure_id": failure.failure_id,
24304                    "exception_class": failure.exception_class,
24305                    "child_run_id": failure.child_workflow_run_id,
24306                })),
24307                Err(error) => Err(error),
24308                Ok(_) => Err(Error::WorkerLoop(
24309                    "child unexpectedly succeeded".to_string(),
24310                )),
24311            }
24312        });
24313        let mut task = child_parent_task(
24314            "ChildRunFailed",
24315            json!({
24316                "sequence": 1,
24317                "child_workflow_instance_id": "wf-child",
24318                "child_workflow_run_id": "run-child",
24319                "child_workflow_type": "python.child",
24320                "failure_id": "failure-child",
24321                "failure_category": "child_workflow",
24322                "message": "payment rejected",
24323                "exception": {
24324                    "type": "PaymentRejected",
24325                    "class": "payments.PaymentRejected",
24326                    "message": "payment rejected"
24327                }
24328            }),
24329        );
24330        task.workflow_type = "rust.handled-parent".to_string();
24331        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
24332
24333        let commands = worker.execute_workflow_task(task).expect("handled failure");
24334        assert_eq!(commands[0]["type"], "complete_workflow");
24335        let output =
24336            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
24337        assert_eq!(output["reason"], "child_workflow");
24338        assert_eq!(output["failure_id"], "failure-child");
24339        assert_eq!(output["exception_class"], "payments.PaymentRejected");
24340        assert_eq!(output["child_run_id"], "run-child");
24341    }
24342
24343    #[test]
24344    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
24345        let client = Client::new("http://127.0.0.1:8080").expect("client");
24346        let mut worker = Worker::new(client, "rust-workers");
24347
24348        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
24349            let signal = ctx.wait_signal("start").await?;
24350            let name = signal
24351                .first()
24352                .and_then(|value| value.as_str())
24353                .unwrap_or("world");
24354            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
24355            Ok(json!({
24356                "greeting": greeting,
24357                "language": "rust"
24358            }))
24359        });
24360
24361        let signal_arguments =
24362            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
24363        let task = WorkflowTask {
24364            task_id: "wft-rust-signal-1".to_string(),
24365            workflow_command_id: None,
24366            workflow_id: Some("wf-rust-hello".to_string()),
24367            run_id: Some("run-rust-hello".to_string()),
24368            workflow_type: "rust.hello_workflow".to_string(),
24369            cancel_requested: false,
24370            payload_codec: DEFAULT_CODEC.to_string(),
24371            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24372            history_events: vec![HistoryEvent {
24373                event_type: "SignalReceived".to_string(),
24374                payload: json!({
24375                    "signal_id": "sig-rust-1",
24376                    "signal_name": "start"
24377                }),
24378                raw: HashMap::new(),
24379            }],
24380            total_history_events: Some(1),
24381            history_size_bytes: None,
24382            continue_as_new_recommended: None,
24383            history_budget_pressure: None,
24384            next_history_page_token: None,
24385            workflow_task_attempt: 1,
24386            workflow_signal_id: Some("sig-rust-1".to_string()),
24387            signal_name: Some("start".to_string()),
24388            signal_arguments: Some(signal_arguments),
24389            workflow_update_id: None,
24390            update_name: None,
24391            lease_owner: Some("rust-worker".to_string()),
24392        };
24393
24394        let commands = worker.execute_workflow_task(task).expect("workflow task");
24395
24396        assert_eq!(commands.len(), 1);
24397        assert_eq!(commands[0]["type"], "schedule_activity");
24398        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
24399        assert_eq!(
24400            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
24401            json!(["Rust"])
24402        );
24403    }
24404
24405    #[test]
24406    fn workflow_task_appends_paginated_history_events() {
24407        let mut task = WorkflowTask {
24408            task_id: "wft-rust-pages-1".to_string(),
24409            workflow_command_id: None,
24410            workflow_id: Some("wf-rust-pages".to_string()),
24411            run_id: Some("run-rust-pages".to_string()),
24412            workflow_type: "rust.hello_workflow".to_string(),
24413            cancel_requested: false,
24414            payload_codec: DEFAULT_CODEC.to_string(),
24415            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24416            history_events: vec![HistoryEvent {
24417                event_type: "WorkflowStarted".to_string(),
24418                payload: json!({}),
24419                raw: HashMap::new(),
24420            }],
24421            total_history_events: Some(3),
24422            history_size_bytes: None,
24423            continue_as_new_recommended: None,
24424            history_budget_pressure: None,
24425            next_history_page_token: Some("MQ==".to_string()),
24426            workflow_task_attempt: 1,
24427            workflow_signal_id: None,
24428            signal_name: None,
24429            signal_arguments: None,
24430            workflow_update_id: None,
24431            update_name: None,
24432            lease_owner: Some("rust-worker".to_string()),
24433        };
24434
24435        task.append_history_page(WorkflowTaskHistoryPage {
24436            history_events: vec![
24437                HistoryEvent {
24438                    event_type: "SignalReceived".to_string(),
24439                    payload: json!({
24440                        "signal_id": "sig-rust-1",
24441                        "signal_name": "start",
24442                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
24443                            .expect("signal arguments")
24444                    }),
24445                    raw: HashMap::new(),
24446                },
24447                HistoryEvent {
24448                    event_type: "MarkerRecorded".to_string(),
24449                    payload: json!({"sequence": 3}),
24450                    raw: HashMap::new(),
24451                },
24452            ],
24453            total_history_events: Some(3),
24454            next_history_page_token: None,
24455        });
24456
24457        assert_eq!(task.history_events.len(), 3);
24458        assert_eq!(task.total_history_events, Some(3));
24459        assert_eq!(task.next_history_page_token, None);
24460
24461        let signal = task
24462            .history_events
24463            .iter()
24464            .find(|event| event.event_type == "SignalReceived")
24465            .expect("signal event");
24466        assert_eq!(
24467            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
24468            vec![AvroValue::String("Rust".to_string())]
24469        );
24470    }
24471
24472    #[tokio::test]
24473    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
24474        let client = Client::new("http://127.0.0.1:8080").expect("client");
24475        let mut worker = Worker::new(client, "rust-workers");
24476        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24477        worker.register_query("counter", "current", |ctx, _args| async move {
24478            let mut count = 0_i64;
24479            for signal in ctx.signal_events() {
24480                let value = signal
24481                    .arguments
24482                    .first()
24483                    .and_then(Value::as_i64)
24484                    .unwrap_or_default();
24485                match signal.name.as_str() {
24486                    "increment" => count += value,
24487                    "set" => count = value,
24488                    _ => {}
24489                }
24490            }
24491            Ok(json!(count))
24492        });
24493
24494        let task = QueryTask {
24495            query_task_id: "query-rust-counter".to_string(),
24496            query_task_attempt: 1,
24497            lease_owner: Some("rust-worker".to_string()),
24498            workflow_id: Some("counter-1".to_string()),
24499            run_id: Some("run-counter-1".to_string()),
24500            workflow_type: "counter".to_string(),
24501            query_name: "current".to_string(),
24502            payload_codec: DEFAULT_CODEC.to_string(),
24503            workflow_arguments: Some(
24504                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24505            ),
24506            query_arguments: Some(
24507                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
24508            ),
24509            history_events: vec![
24510                HistoryEvent {
24511                    event_type: "SignalReceived".to_string(),
24512                    payload: json!({
24513                        "signal_id": "php-signal-1",
24514                        "signal_name": "increment",
24515                        "workflow_sequence": 1,
24516                        "payload_codec": DEFAULT_CODEC,
24517                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
24518                    }),
24519                    raw: HashMap::new(),
24520                },
24521                HistoryEvent {
24522                    event_type: "SignalReceived".to_string(),
24523                    payload: json!({
24524                        "signal_id": "python-signal-2",
24525                        "signal_name": "increment",
24526                        "workflow_sequence": 2,
24527                        "payload_codec": DEFAULT_CODEC,
24528                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
24529                    }),
24530                    raw: HashMap::new(),
24531                },
24532                HistoryEvent {
24533                    event_type: "SignalReceived".to_string(),
24534                    payload: json!({
24535                        "signal_id": "rust-signal-3",
24536                        "signal_name": "set",
24537                        "workflow_sequence": 3,
24538                        "payload_codec": DEFAULT_CODEC,
24539                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
24540                    }),
24541                    raw: HashMap::new(),
24542                },
24543            ],
24544            history_export: None,
24545            run_status: Some("completed".to_string()),
24546        };
24547
24548        let result = worker.execute_query_task(task).await.expect("query result");
24549        assert_eq!(result.into_json().expect("query projection"), json!(0));
24550    }
24551
24552    #[tokio::test]
24553    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
24554        let worker = replay_counter_worker();
24555        let running_history = json!([
24556            {
24557                "type": "ActivityCompleted",
24558                "payload": {
24559                    "sequence": 1,
24560                    "activity_type": "load-counter",
24561                    "payload_codec": DEFAULT_CODEC,
24562                    "result": fixture_envelope(json!("loaded"))
24563                }
24564            },
24565            {
24566                "type": "SignalWaitOpened",
24567                "payload": {
24568                    "sequence": 3,
24569                    "signal_name": "increment"
24570                }
24571            },
24572            {
24573                "type": "SignalReceived",
24574                "payload": {
24575                    "signal_id": "signal-3",
24576                    "signal_name": "increment",
24577                    "workflow_sequence": 2,
24578                    "payload_codec": DEFAULT_CODEC,
24579                    "arguments": fixture_envelope(json!([3]))
24580                }
24581            },
24582            {
24583                "type": "SignalApplied",
24584                "payload": {
24585                    "sequence": 3,
24586                    "signal_id": "signal-3",
24587                    "signal_name": "increment",
24588                    "payload_codec": DEFAULT_CODEC,
24589                    "value": fixture_envelope(json!([3]))
24590                }
24591            }
24592        ]);
24593
24594        let running = worker
24595            .execute_query_task(replay_counter_query(
24596                "current",
24597                running_history.clone(),
24598                "running",
24599            ))
24600            .await
24601            .expect("running replay query");
24602        assert_eq!(
24603            running.clone().into_json().expect("query projection"),
24604            json!({"loaded": "loaded", "count": 3, "finished": false})
24605        );
24606
24607        let detached = worker
24608            .execute_query_task(replay_counter_query(
24609                "detached-mutation",
24610                running_history.clone(),
24611                "running",
24612            ))
24613            .await
24614            .expect("query mutates only its detached state clone");
24615        assert_eq!(detached.into_json().expect("query projection"), json!(999));
24616        let failed = worker
24617            .execute_query_task(replay_counter_query(
24618                "failed-mutation",
24619                running_history.clone(),
24620                "running",
24621            ))
24622            .await
24623            .expect_err("failed query");
24624        assert_eq!(failed.reason, "query_rejected");
24625        let unchanged = worker
24626            .execute_query_task(replay_counter_query("current", running_history, "running"))
24627            .await
24628            .expect("later query reconstructs unchanged state");
24629        assert_eq!(unchanged, running);
24630
24631        let restarted_worker = replay_counter_worker();
24632        let empty_arguments = fixture_envelope(json!([]));
24633        let loaded_result = fixture_envelope(json!("loaded"));
24634        let signal_three = fixture_blob(json!([3]));
24635        let signal_five = fixture_blob(json!([5]));
24636        let restarted_task: QueryTask = serde_json::from_value(json!({
24637            "query_task_id": "query-after-restart",
24638            "workflow_id": "counter-1",
24639            "run_id": "run-counter-1",
24640            "workflow_type": "replay-counter",
24641            "query_name": "current",
24642            "payload_codec": DEFAULT_CODEC,
24643            "workflow_arguments": empty_arguments.clone(),
24644            "query_arguments": empty_arguments,
24645            "history_events": [],
24646            "history_export": {
24647                "payloads": {"codec": DEFAULT_CODEC},
24648                "history_events": [
24649                    {
24650                        "type": "ActivityCompleted",
24651                        "payload": {
24652                            "sequence": 1,
24653                            "activity_type": "load-counter",
24654                            "payload_codec": DEFAULT_CODEC,
24655                            "result": null
24656                        }
24657                    },
24658                    {
24659                        "type": "SignalWaitOpened",
24660                        "payload": {
24661                            "sequence": 3,
24662                            "signal_name": "increment"
24663                        }
24664                    },
24665                    {
24666                        "type": "SignalReceived",
24667                        "payload": {
24668                            "signal_id": "signal-3",
24669                            "signal_name": "increment",
24670                            "workflow_sequence": 2
24671                        }
24672                    },
24673                    {
24674                        "type": "SignalApplied",
24675                        "payload": {
24676                            "sequence": 3,
24677                            "signal_id": "signal-3",
24678                            "signal_name": "increment"
24679                        }
24680                    },
24681                    {
24682                        "type": "SignalWaitOpened",
24683                        "payload": {
24684                            "sequence": 5,
24685                            "signal_name": "increment"
24686                        }
24687                    },
24688                    {
24689                        "type": "SignalReceived",
24690                        "payload": {
24691                            "signal_id": "signal-5",
24692                            "signal_name": "increment",
24693                            "workflow_sequence": 4
24694                        }
24695                    },
24696                    {
24697                        "type": "SignalApplied",
24698                        "payload": {
24699                            "sequence": 5,
24700                            "signal_id": "signal-5",
24701                            "signal_name": "increment"
24702                        }
24703                    }
24704                ],
24705                "activities": [{
24706                    "sequence": 1,
24707                    "activity_type": "load-counter",
24708                    "payload_codec": DEFAULT_CODEC,
24709                    "result": loaded_result
24710                }],
24711                "signals": [
24712                    {
24713                        "id": "signal-3",
24714                        "name": "increment",
24715                        "workflow_sequence": 2,
24716                        "payload_codec": DEFAULT_CODEC,
24717                        "arguments": signal_three
24718                    },
24719                    {
24720                        "id": "signal-5",
24721                        "name": "increment",
24722                        "workflow_sequence": 4,
24723                        "payload_codec": DEFAULT_CODEC,
24724                        "arguments": signal_five
24725                    }
24726                ]
24727            },
24728            "run_status": "completed"
24729        }))
24730        .expect("cold replay query task");
24731        let completed = restarted_worker
24732            .execute_query_task(restarted_task)
24733            .await
24734            .expect("completed cold replay query");
24735        assert_eq!(
24736            completed.into_json().expect("query projection"),
24737            json!({"loaded": "loaded", "count": 8, "finished": true})
24738        );
24739    }
24740
24741    #[tokio::test]
24742    async fn replayed_query_replay_failures_are_machine_readable() {
24743        let worker = replay_counter_worker();
24744        let task = replay_counter_query(
24745            "current",
24746            json!([{
24747                "type": "ActivityCompleted",
24748                "payload": {
24749                    "sequence": 1,
24750                    "payload_codec": DEFAULT_CODEC,
24751                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
24752                }
24753            }]),
24754            "running",
24755        );
24756        let failure = worker
24757            .execute_query_task(task)
24758            .await
24759            .expect_err("invalid replay history payload");
24760        assert_eq!(failure.reason, "query_payload_decode_failed");
24761        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
24762        assert!(failure.message.contains("invalid_payload_framing"));
24763    }
24764
24765    #[tokio::test]
24766    async fn query_task_restores_compact_history_from_export() {
24767        let client = Client::new("http://127.0.0.1:8080").expect("client");
24768        let mut worker = Worker::new(client, "rust-workers");
24769        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24770        worker.register_query("counter", "current", |ctx, _args| async move {
24771            Ok(json!(ctx.signals("increment")[0][0]))
24772        });
24773        let empty_arguments = fixture_envelope(json!([]));
24774        let exported_signal = fixture_blob(json!([9]));
24775        let task: QueryTask = serde_json::from_value(json!({
24776            "query_task_id": "query-export",
24777            "workflow_type": "counter",
24778            "query_name": "current",
24779            "payload_codec": DEFAULT_CODEC,
24780            "workflow_arguments": empty_arguments.clone(),
24781            "query_arguments": empty_arguments,
24782            "history_events": [],
24783            "history_export": {
24784                "payloads": {"codec": DEFAULT_CODEC},
24785                "history_events": [{
24786                    "type": "SignalReceived",
24787                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
24788                }],
24789                "signals": [{
24790                    "id": "signal-export",
24791                    "name": "increment",
24792                    "status": "applied",
24793                    "workflow_sequence": 1,
24794                    "payload_codec": DEFAULT_CODEC,
24795                    "arguments": exported_signal
24796                }]
24797            }
24798        }))
24799        .expect("query task");
24800
24801        let result = worker.execute_query_task(task).await.expect("query result");
24802        assert_eq!(result.into_json().expect("query projection"), json!(9));
24803    }
24804
24805    #[tokio::test]
24806    async fn query_task_failures_have_stable_reasons() {
24807        let client = Client::new("http://127.0.0.1:8080").expect("client");
24808        let mut worker = Worker::new(client, "rust-workers");
24809        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24810        worker.register_query(
24811            "counter",
24812            "current",
24813            |_ctx, _args| async move { Ok(json!(0)) },
24814        );
24815
24816        let base_task = QueryTask {
24817            query_task_id: "query-errors".to_string(),
24818            query_task_attempt: 1,
24819            lease_owner: None,
24820            workflow_id: Some("counter-errors".to_string()),
24821            run_id: Some("run-errors".to_string()),
24822            workflow_type: "counter".to_string(),
24823            query_name: "missing".to_string(),
24824            payload_codec: DEFAULT_CODEC.to_string(),
24825            workflow_arguments: Some(fixture_envelope(json!([]))),
24826            query_arguments: Some(fixture_envelope(json!([]))),
24827            history_events: Vec::new(),
24828            history_export: None,
24829            run_status: Some("running".to_string()),
24830        };
24831
24832        let unknown = worker
24833            .execute_query_task(base_task.clone())
24834            .await
24835            .expect_err("unknown query");
24836        assert_eq!(unknown.reason, "rejected_unknown_query");
24837
24838        let mut malformed = base_task;
24839        malformed.query_name = "current".to_string();
24840        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
24841        let malformed = worker
24842            .execute_query_task(malformed)
24843            .await
24844            .expect_err("malformed payload");
24845        assert_eq!(malformed.reason, "query_payload_decode_failed");
24846
24847        let client = Client::new("http://127.0.0.1:8080").expect("client");
24848        let mut unavailable_worker = Worker::new(client, "rust-workers");
24849        unavailable_worker
24850            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24851        let empty_arguments = fixture_envelope(json!([]));
24852        let unavailable_task: QueryTask = serde_json::from_value(json!({
24853            "query_task_id": "query-unavailable",
24854            "workflow_type": "counter",
24855            "query_name": "current",
24856            "payload_codec": DEFAULT_CODEC,
24857            "workflow_arguments": empty_arguments.clone(),
24858            "query_arguments": empty_arguments
24859        }))
24860        .expect("query task");
24861        let unavailable = unavailable_worker
24862            .execute_query_task(unavailable_task)
24863            .await
24864            .expect_err("query handler unavailable");
24865        assert_eq!(unavailable.reason, "query_handler_unavailable");
24866    }
24867
24868    #[tokio::test]
24869    async fn client_query_decodes_result_and_typed_failure() {
24870        let server = MockWorkerServer::start();
24871        let client = Client::builder(server.base_url())
24872            .timeout(Duration::from_secs(2))
24873            .build()
24874            .expect("client");
24875
24876        let result = client
24877            .query_workflow("counter-1", "current", json!([]))
24878            .await
24879            .expect("query result");
24880        assert_eq!(result, json!({"count": 8}));
24881
24882        let error = client
24883            .query_workflow("counter-1", "missing", json!([]))
24884            .await
24885            .expect_err("unknown query");
24886        let Error::QueryFailed(failure) = error else {
24887            panic!("expected typed query failure");
24888        };
24889        assert_eq!(failure.status, 404);
24890        assert_eq!(failure.reason, "rejected_unknown_query");
24891    }
24892
24893    #[tokio::test]
24894    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
24895        let server = MockWorkerServer::start();
24896        let client = Client::builder(server.base_url())
24897            .timeout(Duration::from_secs(2))
24898            .build()
24899            .expect("client");
24900        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
24901
24902        client
24903            .start_workflow(
24904                "typed.echo",
24905                "rust-workers",
24906                "typed-start",
24907                arguments.clone(),
24908            )
24909            .await
24910            .expect("typed workflow start");
24911        assert_eq!(
24912            decode_wire_avro_value(
24913                &server.request_body("/api/workflows")["input"],
24914                DEFAULT_CODEC,
24915            )
24916            .expect("typed start input"),
24917            arguments
24918        );
24919
24920        client
24921            .signal_workflow("typed-1", "changed", arguments.clone())
24922            .await
24923            .expect("typed signal");
24924        assert_eq!(
24925            decode_wire_avro_value(
24926                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
24927                DEFAULT_CODEC,
24928            )
24929            .expect("typed signal input"),
24930            arguments
24931        );
24932
24933        assert_eq!(
24934            client
24935                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
24936                .await
24937                .expect("typed query"),
24938            typed_fidelity_probe()
24939        );
24940        assert_eq!(
24941            decode_wire_avro_value(
24942                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
24943                DEFAULT_CODEC,
24944            )
24945            .expect("typed query input"),
24946            arguments
24947        );
24948
24949        assert_eq!(
24950            client
24951                .update_workflow_avro_value(
24952                    "typed-1",
24953                    "replace",
24954                    arguments.clone(),
24955                    Some("typed-request"),
24956                )
24957                .await
24958                .expect("typed update"),
24959            typed_fidelity_probe()
24960        );
24961        let update = server.request_body("/api/workflows/typed-1/update/replace");
24962        assert_eq!(update["request_id"], "typed-request");
24963        assert_eq!(
24964            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
24965            arguments
24966        );
24967
24968        let handle = WorkflowHandle {
24969            client: client.clone(),
24970            workflow_id: "typed-1".to_string(),
24971            run_id: Some("run-typed-1".to_string()),
24972            workflow_type: "typed.echo".to_string(),
24973        };
24974        assert_eq!(
24975            handle
24976                .result_avro_value(WorkflowResultOptions::default())
24977                .await
24978                .expect("typed workflow result"),
24979            typed_fidelity_probe()
24980        );
24981
24982        client
24983            .complete_activity_task(
24984                "activity-typed",
24985                "attempt-typed",
24986                "rust-worker",
24987                typed_fidelity_probe(),
24988                DEFAULT_CODEC,
24989            )
24990            .await
24991            .expect("typed activity completion");
24992        assert_eq!(
24993            decode_wire_avro_value(
24994                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
24995                    ["result"],
24996                DEFAULT_CODEC,
24997            )
24998            .expect("typed activity result"),
24999            typed_fidelity_probe()
25000        );
25001        client
25002            .fail_activity_task(
25003                "activity-typed",
25004                "attempt-typed",
25005                "rust-worker",
25006                "typed failure",
25007                true,
25008            )
25009            .await
25010            .expect("activity failure");
25011    }
25012
25013    #[tokio::test]
25014    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
25015        let server = MockWorkerServer::start();
25016        let client = Client::builder(server.base_url())
25017            .timeout(Duration::from_secs(2))
25018            .build()
25019            .expect("client");
25020
25021        let options = WorkflowCommandOptions::new()
25022            .reason("cleanup requested")
25023            .request_id("cancel-17");
25024        let cancelled = client
25025            .cancel_workflow("wf-lifecycle", options)
25026            .await
25027            .expect("instance cancellation");
25028        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
25029        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
25030        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
25031        assert_eq!(
25032            server.request_body("/api/workflows/wf-lifecycle/cancel"),
25033            json!({"reason":"cleanup requested","request_id":"cancel-17"})
25034        );
25035
25036        let terminated = client
25037            .terminate_workflow(
25038                "wf-lifecycle",
25039                WorkflowCommandOptions::new().reason("forced stop"),
25040            )
25041            .await
25042            .expect("instance termination");
25043        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
25044        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
25045
25046        client
25047            .cancel_workflow_run(
25048                "wf-lifecycle",
25049                "run-current",
25050                WorkflowCommandOptions::default(),
25051            )
25052            .await
25053            .expect("selected run cancellation");
25054        client
25055            .terminate_workflow_run(
25056                "wf-lifecycle",
25057                "run-current",
25058                WorkflowCommandOptions::default(),
25059            )
25060            .await
25061            .expect("selected run termination");
25062
25063        for (command, error) in [
25064            (
25065                WorkflowCommandKind::Cancel,
25066                client
25067                    .cancel_workflow_run(
25068                        "wf-lifecycle",
25069                        "run-stale",
25070                        WorkflowCommandOptions::default(),
25071                    )
25072                    .await
25073                    .expect_err("stale cancellation must be rejected"),
25074            ),
25075            (
25076                WorkflowCommandKind::Terminate,
25077                client
25078                    .terminate_workflow_run(
25079                        "wf-lifecycle",
25080                        "run-stale",
25081                        WorkflowCommandOptions::default(),
25082                    )
25083                    .await
25084                    .expect_err("stale termination must be rejected"),
25085            ),
25086        ] {
25087            let Error::WorkflowCommandRejected(rejection) = error else {
25088                panic!("expected typed command rejection");
25089            };
25090            assert_eq!(rejection.command, command);
25091            assert_eq!(rejection.status, 409);
25092            assert_eq!(rejection.reason, "historical_run_command_rejected");
25093            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
25094            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
25095        }
25096    }
25097
25098    #[tokio::test]
25099    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
25100        let server = MockWorkerServer::start();
25101        let client = Client::builder(server.base_url())
25102            .timeout(Duration::from_secs(2))
25103            .build()
25104            .expect("client");
25105
25106        let result = client
25107            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
25108            .await
25109            .expect("redrive accepted");
25110        assert_eq!(result.workflow_id, "wf-lifecycle");
25111        assert_eq!(result.source_run_id, "run-failed");
25112        assert_eq!(result.run_id, "run-successor");
25113        assert_eq!(result.resume_step_sequence, 2);
25114        assert_eq!(
25115            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
25116            json!({"request_id":"retry-1"})
25117        );
25118
25119        let repeated = client
25120            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
25121            .await
25122            .expect("idempotent redrive response accepted");
25123        assert_eq!(repeated.run_id, "run-successor");
25124
25125        let error = client
25126            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
25127            .await
25128            .expect_err("completed run must be rejected");
25129        let Error::Http { status, body } = error else {
25130            panic!("expected HTTP redrive rejection");
25131        };
25132        assert_eq!(status.as_u16(), 409);
25133        assert!(body.contains("run_not_failed"));
25134        assert_eq!(
25135            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
25136            json!({})
25137        );
25138
25139        let handle = WorkflowHandle {
25140            client: client.clone(),
25141            workflow_id: "wf-lifecycle".to_string(),
25142            run_id: Some("run-failed".to_string()),
25143            workflow_type: "test".to_string(),
25144        };
25145        assert_eq!(
25146            handle.redrive(None).await.expect("handle redrive").run_id,
25147            "run-successor"
25148        );
25149        let missing_run = WorkflowHandle {
25150            run_id: None,
25151            ..handle
25152        };
25153        assert!(matches!(
25154            missing_run.redrive(None).await,
25155            Err(Error::Codec(_))
25156        ));
25157    }
25158
25159    #[tokio::test]
25160    async fn workflow_start_options_send_server_enforced_deadlines() {
25161        let server = MockWorkerServer::start();
25162        let client = Client::builder(server.base_url())
25163            .timeout(Duration::from_secs(2))
25164            .build()
25165            .expect("client");
25166
25167        let handle = client
25168            .start_workflow_with_options(
25169                "rust.timeout",
25170                "rust-timeouts",
25171                "wf-start-options",
25172                WorkflowStartOptions::new()
25173                    .execution_timeout_seconds(30)
25174                    .run_timeout_seconds(1),
25175                json!([]),
25176            )
25177            .await
25178            .expect("workflow start");
25179
25180        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
25181        let body = server.request_body("/api/workflows");
25182        assert_eq!(body["execution_timeout_seconds"], 30);
25183        assert_eq!(body["run_timeout_seconds"], 1);
25184
25185        let invalid = client
25186            .start_workflow_with_options(
25187                "rust.timeout",
25188                "rust-timeouts",
25189                "wf-invalid-options",
25190                WorkflowStartOptions::new()
25191                    .execution_timeout_seconds(1)
25192                    .run_timeout_seconds(2),
25193                json!([]),
25194            )
25195            .await
25196            .expect_err("invalid deadline ordering");
25197        assert!(invalid
25198            .to_string()
25199            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
25200    }
25201
25202    #[tokio::test]
25203    async fn workflow_result_returns_each_typed_terminal_outcome() {
25204        let server = MockWorkerServer::start();
25205        let client = Client::builder(server.base_url())
25206            .timeout(Duration::from_secs(2))
25207            .build()
25208            .expect("client");
25209        let options = WorkflowResultOptions {
25210            poll_interval: Duration::ZERO,
25211            timeout: Duration::from_secs(1),
25212        };
25213
25214        let failed = WorkflowHandle {
25215            client: client.clone(),
25216            workflow_id: "wf-failed".to_string(),
25217            run_id: Some("run-failed".to_string()),
25218            workflow_type: "failure".to_string(),
25219        }
25220        .result(options)
25221        .await
25222        .expect_err("failed outcome");
25223        let Error::WorkflowFailed(failure) = failed else {
25224            panic!("expected WorkflowFailed");
25225        };
25226        assert_eq!(failure.workflow_id, "wf-failed");
25227        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
25228        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
25229        assert_eq!(failure.failure_category.as_deref(), Some("application"));
25230        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
25231        assert_eq!(
25232            failure.exception_class.as_deref(),
25233            Some("billing::PaymentError")
25234        );
25235        assert_eq!(failure.non_retryable, Some(true));
25236
25237        for (workflow_id, expected_kind, expected_reason) in [
25238            (
25239                "wf-cancelled",
25240                WorkflowTerminalKind::Cancelled,
25241                "cleanup requested",
25242            ),
25243            (
25244                "wf-terminated",
25245                WorkflowTerminalKind::Terminated,
25246                "forced stop",
25247            ),
25248            (
25249                "wf-timed-out",
25250                WorkflowTerminalKind::TimedOut,
25251                "run_timeout",
25252            ),
25253        ] {
25254            let error = WorkflowHandle {
25255                client: client.clone(),
25256                workflow_id: workflow_id.to_string(),
25257                run_id: None,
25258                workflow_type: "terminal".to_string(),
25259            }
25260            .result(options)
25261            .await
25262            .expect_err("typed terminal outcome");
25263            let outcome = match error {
25264                Error::WorkflowCancelled(outcome) => outcome,
25265                Error::WorkflowTerminated(outcome) => outcome,
25266                Error::WorkflowTimedOut(outcome) => outcome,
25267                other => panic!("unexpected terminal error: {other}"),
25268            };
25269            assert_eq!(outcome.kind, expected_kind);
25270            assert_eq!(outcome.workflow_id, workflow_id);
25271            assert_eq!(outcome.reason, expected_reason);
25272        }
25273
25274        let wait_timeout = WorkflowHandle {
25275            client,
25276            workflow_id: "wf-waiting".to_string(),
25277            run_id: Some("run-waiting".to_string()),
25278            workflow_type: "waiting".to_string(),
25279        }
25280        .result(WorkflowResultOptions {
25281            poll_interval: Duration::ZERO,
25282            timeout: Duration::ZERO,
25283        })
25284        .await
25285        .expect_err("client wait timeout");
25286        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
25287            panic!("expected typed client timeout");
25288        };
25289        assert_eq!(timeout.reason, "result_wait_timeout");
25290        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
25291        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
25292    }
25293
25294    #[tokio::test]
25295    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
25296        let server = MockWorkerServer::start();
25297        let client = Client::builder(server.base_url())
25298            .timeout(Duration::from_secs(2))
25299            .build()
25300            .expect("client");
25301
25302        let handle = WorkflowHandle {
25303            client,
25304            workflow_id: "wf-selected".to_string(),
25305            run_id: Some("run-selected".to_string()),
25306            workflow_type: "selected".to_string(),
25307        };
25308        let options = WorkflowResultOptions {
25309            poll_interval: Duration::ZERO,
25310            timeout: Duration::from_secs(1),
25311        };
25312
25313        let current = handle
25314            .result(options)
25315            .await
25316            .expect("instance result follows the current run");
25317        assert_eq!(current, json!("current run output"));
25318
25319        let error = handle
25320            .result_selected_run(options)
25321            .await
25322            .expect_err("the selected run is cancelled even though the current run completed");
25323
25324        let Error::WorkflowCancelled(outcome) = error else {
25325            panic!("expected selected run cancellation");
25326        };
25327        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
25328        assert_eq!(outcome.reason, "selected run cancelled");
25329        assert_eq!(
25330            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
25331            1
25332        );
25333        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
25334    }
25335
25336    #[tokio::test]
25337    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
25338        let server = MockWorkerServer::draining_polls();
25339        let client = Client::builder(server.base_url())
25340            .timeout(Duration::from_secs(2))
25341            .build()
25342            .expect("client");
25343
25344        let workflow = client
25345            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
25346            .await
25347            .expect("workflow drain response");
25348        let activity = client
25349            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
25350            .await
25351            .expect("activity drain response");
25352        let query = client
25353            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
25354            .await
25355            .expect("query drain response");
25356
25357        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
25358            assert_eq!(
25359                outcome,
25360                WorkerPollOutcome::Stop {
25361                    poll_status: Some("draining".to_string()),
25362                    reason: Some("worker_draining".to_string()),
25363                }
25364            );
25365        }
25366
25367        assert!(client
25368            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
25369            .await
25370            .expect("compatibility poll")
25371            .is_none());
25372    }
25373
25374    #[tokio::test]
25375    async fn managed_worker_honors_drain_stop_for_every_task_family() {
25376        let server = MockWorkerServer::draining_polls();
25377        let client = Client::builder(server.base_url())
25378            .timeout(Duration::from_secs(2))
25379            .build()
25380            .expect("client");
25381
25382        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
25383            .worker_id("draining-workflow-worker")
25384            .poll_timeout(Duration::ZERO);
25385        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
25386        workflow_worker
25387            .run()
25388            .await
25389            .expect("workflow drain is a clean stop");
25390
25391        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
25392            .worker_id("draining-activity-worker")
25393            .poll_timeout(Duration::ZERO);
25394        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
25395        activity_worker
25396            .run()
25397            .await
25398            .expect("activity drain is a clean stop");
25399
25400        let mut query_worker = Worker::new(client, "rust-workers")
25401            .worker_id("draining-query-worker")
25402            .poll_timeout(Duration::ZERO);
25403        query_worker.register_query("counter", "current", |_ctx, _args| async {
25404            Ok(Value::Null)
25405        });
25406        query_worker
25407            .run()
25408            .await
25409            .expect("query drain is a clean stop");
25410    }
25411
25412    #[tokio::test]
25413    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
25414        let server = MockWorkerServer::start();
25415        let client = Client::builder(server.base_url())
25416            .timeout(Duration::from_secs(2))
25417            .build()
25418            .expect("client");
25419
25420        let heartbeat = client
25421            .heartbeat_activity_task(
25422                "activity-cancel",
25423                "attempt-cancel",
25424                "rust-worker",
25425                typed_fidelity_probe(),
25426            )
25427            .await
25428            .expect("cancellation heartbeat");
25429        assert!(heartbeat.cancel_requested);
25430        assert!(heartbeat.should_stop());
25431        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
25432        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
25433        let heartbeat_body =
25434            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
25435        assert_eq!(heartbeat_body["details"]["codec"], DEFAULT_CODEC);
25436        assert_eq!(
25437            decode_wire_avro_value(&heartbeat_body["details"], DEFAULT_CODEC)
25438                .expect("typed heartbeat details"),
25439            typed_fidelity_probe()
25440        );
25441
25442        let error = client
25443            .complete_activity_task(
25444                "activity-cancel",
25445                "attempt-cancel",
25446                "rust-worker",
25447                json!({"late":true}),
25448                DEFAULT_CODEC,
25449            )
25450            .await
25451            .expect_err("late completion must be refused");
25452        assert!(activity_task_rejection_is_final(&error));
25453        let Error::ActivityTaskRejected(rejection) = error else {
25454            panic!("expected typed activity rejection");
25455        };
25456        assert_eq!(rejection.status, 409);
25457        assert_eq!(rejection.reason, "run_cancelled");
25458        assert!(rejection.cancel_requested);
25459        assert_eq!(rejection.can_continue, Some(false));
25460    }
25461
25462    #[tokio::test]
25463    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
25464        let server = MockWorkerServer::cancelled_activity();
25465        let client = Client::builder(server.base_url())
25466            .timeout(Duration::from_secs(2))
25467            .build()
25468            .expect("client");
25469        let cancellation_observed = Arc::new(AtomicBool::new(false));
25470        let observed = Arc::clone(&cancellation_observed);
25471        let mut worker = Worker::new(client.clone(), "rust-workers")
25472            .worker_id("rust-cancel-worker")
25473            .poll_timeout(Duration::from_millis(10));
25474        worker.register_activity("cancel-aware", move |ctx, _args| {
25475            let observed = Arc::clone(&observed);
25476            async move {
25477                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
25478                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
25479                Ok(json!({"late":"completion"}))
25480            }
25481        });
25482
25483        assert_eq!(
25484            worker.run_once().await.expect("cancelled attempt handled"),
25485            1
25486        );
25487        assert!(cancellation_observed.load(Ordering::SeqCst));
25488        assert_eq!(
25489            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
25490            1
25491        );
25492
25493        let mut restarted = Worker::new(client, "rust-workers")
25494            .worker_id("rust-cancel-worker-restarted")
25495            .poll_timeout(Duration::from_millis(10));
25496        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
25497        assert_eq!(
25498            restarted
25499                .run_once()
25500                .await
25501                .expect("replacement worker continues polling"),
25502            0
25503        );
25504    }
25505
25506    #[tokio::test]
25507    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
25508        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"}"#;
25509        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
25510        let client = Client::builder(server.base_url())
25511            .timeout(Duration::from_secs(2))
25512            .build()
25513            .expect("client");
25514
25515        let direct_error = client
25516            .complete_workflow_task(
25517                "workflow-timeout-task",
25518                "timeout-worker",
25519                3,
25520                vec![json!({
25521                    "type": "complete_workflow",
25522                    "result": fixture_envelope(Value::Null)
25523                })],
25524            )
25525            .await
25526            .expect_err("the low-level client preserves the completion rejection");
25527        let Error::Http { status, body } = direct_error else {
25528            panic!("expected the original HTTP completion rejection");
25529        };
25530        assert_eq!(status, reqwest::StatusCode::CONFLICT);
25531        assert_eq!(
25532            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
25533            "run_timed_out"
25534        );
25535
25536        let mut worker = Worker::new(client, "rust-workers")
25537            .worker_id("timeout-worker")
25538            .poll_timeout(Duration::from_millis(10));
25539        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
25540            Ok(json!({"late": "result"}))
25541        });
25542
25543        assert_eq!(
25544            worker
25545                .run_once()
25546                .await
25547                .expect("authoritative selected-run timeout settles the tick"),
25548            1
25549        );
25550        assert_eq!(
25551            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
25552            2,
25553            "both the direct client proof and managed worker must see the rejection"
25554        );
25555    }
25556
25557    #[tokio::test]
25558    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
25559        for (name, status, response) in [
25560            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
25561            (
25562                "command was recorded",
25563                "409 Conflict",
25564                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25565            ),
25566            (
25567                "lease conflict",
25568                "409 Conflict",
25569                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
25570            ),
25571            (
25572                "nonterminal run",
25573                "409 Conflict",
25574                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
25575            ),
25576            (
25577                "different selected run",
25578                "409 Conflict",
25579                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"}"#,
25580            ),
25581            (
25582                "different task attempt",
25583                "409 Conflict",
25584                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25585            ),
25586            (
25587                "authentication failure",
25588                "401 Unauthorized",
25589                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25590            ),
25591            (
25592                "authorization failure",
25593                "403 Forbidden",
25594                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25595            ),
25596            (
25597                "protocol failure",
25598                "400 Bad Request",
25599                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
25600            ),
25601            (
25602                "malformed command",
25603                "422 Unprocessable Entity",
25604                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25605            ),
25606            (
25607                "transient server failure",
25608                "503 Service Unavailable",
25609                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25610            ),
25611        ] {
25612            let server = MockWorkerServer::workflow_completion(status, response);
25613            let client = Client::builder(server.base_url())
25614                .timeout(Duration::from_secs(2))
25615                .build()
25616                .expect("client");
25617            let mut worker = Worker::new(client, "rust-workers")
25618                .worker_id("timeout-worker")
25619                .poll_timeout(Duration::from_millis(10));
25620            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
25621                Ok(json!({"late": "result"}))
25622            });
25623
25624            let error = worker
25625                .run_once()
25626                .await
25627                .expect_err(&format!("{name} must remain an error"));
25628            assert!(
25629                matches!(error, Error::Http { .. } | Error::Protocol(_)),
25630                "{name} returned an unexpected error variant: {error}"
25631            );
25632        }
25633    }
25634
25635    #[tokio::test]
25636    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
25637        let server = MockWorkerServer::start();
25638        let client = Client::builder(server.base_url())
25639            .worker_token(Some("worker-secret".to_string()))
25640            .namespace("orders")
25641            .timeout(Duration::from_secs(2))
25642            .build()
25643            .expect("client");
25644        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
25645
25646        let result = client
25647            .deregister_worker_registration("worker/α space")
25648            .await
25649            .expect("deregister worker registration");
25650
25651        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
25652        assert_eq!(
25653            server.worker_protocol_for(path).as_deref(),
25654            Some(WORKER_PROTOCOL_VERSION)
25655        );
25656        assert_eq!(server.control_protocol_for(path), None);
25657        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
25658        assert_eq!(
25659            server.authorization_for(path).as_deref(),
25660            Some("Bearer worker-secret")
25661        );
25662        assert_eq!(
25663            result,
25664            WorkerDeregistrationEnvelope {
25665                worker_id: "deregistered-worker".to_string(),
25666                outcome: "deregistered".to_string(),
25667                recovered_workflow_task_count: 2,
25668            }
25669        );
25670    }
25671
25672    #[tokio::test]
25673    async fn low_level_registration_rejects_update_validators_before_transport() {
25674        let server = MockWorkerServer::start();
25675        let client = Client::builder(server.base_url())
25676            .timeout(Duration::from_secs(2))
25677            .build()
25678            .expect("client");
25679
25680        for update_validators in [json!(["approve"]), json!("approve")] {
25681            let error = client
25682                .register_worker_with_command_contracts(
25683                    "validator-claiming-worker",
25684                    "rust-workers",
25685                    vec!["orders".to_string()],
25686                    vec![],
25687                    1,
25688                    1,
25689                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
25690                    json!({
25691                        "orders": {
25692                            "queries": ["current"],
25693                            "updates": ["approve"],
25694                            "update_validators": update_validators,
25695                        },
25696                    }),
25697                )
25698                .await
25699                .expect_err("unsupported validator claims must fail before registration");
25700
25701            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
25702                panic!("expected typed unsupported-validator failure");
25703            };
25704            assert_eq!(workflow_type, "orders");
25705        }
25706        assert_eq!(server.request_count("/api/worker/register"), 0);
25707    }
25708
25709    #[tokio::test]
25710    async fn low_level_registration_preserves_query_and_update_contracts() {
25711        let server = MockWorkerServer::start();
25712        let client = Client::builder(server.base_url())
25713            .timeout(Duration::from_secs(2))
25714            .build()
25715            .expect("client");
25716        let contracts = json!({
25717            "orders": {
25718                "queries": ["current"],
25719                "updates": ["approve"],
25720                "update_validators": [],
25721            },
25722            "payments": {
25723                "queries": ["status"],
25724                "updates": ["capture"],
25725            },
25726        });
25727
25728        client
25729            .register_worker_with_command_contracts(
25730                "command-worker",
25731                "rust-workers",
25732                vec!["orders".to_string(), "payments".to_string()],
25733                vec![],
25734                1,
25735                1,
25736                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
25737                contracts.clone(),
25738            )
25739            .await
25740            .expect("query and update contracts must remain supported");
25741
25742        assert_eq!(
25743            server.request_body("/api/worker/register")["workflow_command_contracts"],
25744            contracts
25745        );
25746        assert!(server
25747            .request_body("/api/worker/register")
25748            .get("workflow_definition_fingerprints")
25749            .is_none());
25750    }
25751
25752    #[tokio::test]
25753    async fn rust_worker_advertises_source_backed_definition_and_clears_it_on_reregistration() {
25754        let server = MockWorkerServer::start();
25755        let client = Client::builder(server.base_url())
25756            .timeout(Duration::from_secs(2))
25757            .build()
25758            .expect("client");
25759        let mut worker = Worker::new(client, "rust-workers");
25760        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
25761
25762        assert!(worker
25763            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
25764            .is_err());
25765        assert!(worker
25766            .set_workflow_definition_sources("orders", &[])
25767            .is_err());
25768        worker
25769            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
25770            .expect("embed workflow source");
25771        worker.register().await.expect("register worker");
25772        let first = server.request_bodies("/api/worker/register")[0]
25773            ["workflow_definition_fingerprints"]["orders"]
25774            .as_str()
25775            .expect("source-backed fingerprint")
25776            .to_string();
25777        assert!(first.starts_with("sha256:"));
25778
25779        worker
25780            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
25781            .expect("change embedded helper source");
25782        worker.register().await.expect("register changed source");
25783        let changed = server.request_bodies("/api/worker/register")[1]
25784            ["workflow_definition_fingerprints"]["orders"]
25785            .as_str()
25786            .expect("changed fingerprint")
25787            .to_string();
25788        assert_ne!(first, changed);
25789
25790        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
25791        worker
25792            .register()
25793            .await
25794            .expect("register replacement handler");
25795        assert_eq!(
25796            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
25797            json!({})
25798        );
25799    }
25800
25801    #[tokio::test]
25802    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
25803        let server = MockWorkerServer::start();
25804        let control_only = Client::builder(server.base_url())
25805            .control_token(Some("control-secret".to_string()))
25806            .build()
25807            .expect("control client");
25808
25809        let error = control_only
25810            .register_worker("worker", "queue", vec![], vec![], 1, 1)
25811            .await
25812            .expect_err("control token must not authorize a worker request");
25813        assert!(matches!(
25814            error,
25815            Error::MissingRoleCredentials { role: "worker", .. }
25816        ));
25817        assert_eq!(server.request_count("/api/worker/register"), 0);
25818
25819        let worker_only = Client::builder(server.base_url())
25820            .worker_token(Some("worker-secret".to_string()))
25821            .build()
25822            .expect("worker client");
25823        let error = worker_only
25824            .health()
25825            .await
25826            .expect_err("worker token must not authorize a control request");
25827        assert!(matches!(
25828            error,
25829            Error::MissingRoleCredentials {
25830                role: "control",
25831                ..
25832            }
25833        ));
25834        assert_eq!(server.request_count("/api/health"), 0);
25835    }
25836
25837    #[tokio::test]
25838    async fn shared_token_supports_worker_and_control_planes() {
25839        let server = MockWorkerServer::start();
25840        let client = Client::builder(server.base_url())
25841            .token(Some("shared-secret".to_string()))
25842            .build()
25843            .expect("client");
25844
25845        client.health().await.expect("control request");
25846        client
25847            .register_worker("worker", "queue", vec![], vec![], 1, 1)
25848            .await
25849            .expect("worker request");
25850
25851        assert_eq!(
25852            server.authorization_for("/api/health").as_deref(),
25853            Some("Bearer shared-secret")
25854        );
25855        assert_eq!(
25856            server.control_protocol_for("/api/health").as_deref(),
25857            Some(CONTROL_PLANE_VERSION)
25858        );
25859        assert_eq!(
25860            server.authorization_for("/api/worker/register").as_deref(),
25861            Some("Bearer shared-secret")
25862        );
25863        assert_eq!(
25864            server
25865                .worker_protocol_for("/api/worker/register")
25866                .as_deref(),
25867            Some(WORKER_PROTOCOL_VERSION)
25868        );
25869    }
25870
25871    #[tokio::test]
25872    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
25873        let server = MockWorkerServer::start();
25874        let client = Client::builder(server.base_url())
25875            .timeout(Duration::from_secs(2))
25876            .build()
25877            .expect("client");
25878
25879        client
25880            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
25881            .await
25882            .expect("register");
25883        client
25884            .heartbeat_worker("capture-worker", 1, 1)
25885            .await
25886            .expect("heartbeat");
25887        client
25888            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
25889            .await
25890            .expect("workflow poll");
25891        client
25892            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
25893            .await
25894            .expect("activity poll");
25895
25896        for path in [
25897            "/api/worker/register",
25898            "/api/worker/heartbeat",
25899            "/api/worker/workflow-tasks/poll",
25900            "/api/worker/activity-tasks/poll",
25901        ] {
25902            assert_eq!(
25903                server.worker_protocol_for(path).as_deref(),
25904                Some(WORKER_PROTOCOL_VERSION),
25905                "unexpected protocol for {path}"
25906            );
25907        }
25908
25909        assert_eq!(
25910            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
25911            1
25912        );
25913        assert_eq!(
25914            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
25915            500
25916        );
25917        assert_eq!(
25918            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
25919            1
25920        );
25921        assert!(
25922            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
25923                .as_str()
25924                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
25925        );
25926        assert!(
25927            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
25928                .as_str()
25929                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
25930        );
25931    }
25932
25933    #[tokio::test]
25934    async fn query_task_endpoints_send_the_query_feature_protocol() {
25935        let server = MockWorkerServer::start();
25936        let client = Client::builder(server.base_url())
25937            .timeout(Duration::from_secs(2))
25938            .build()
25939            .expect("client");
25940
25941        client
25942            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
25943            .await
25944            .expect("query poll");
25945        client
25946            .complete_query_task(
25947                "query-capture",
25948                "capture-worker",
25949                1,
25950                json!(8),
25951                DEFAULT_CODEC,
25952            )
25953            .await
25954            .expect("query complete");
25955        client
25956            .fail_query_task(
25957                "query-capture",
25958                "capture-worker",
25959                1,
25960                "failed",
25961                "query_rejected",
25962                "QueryFailed",
25963            )
25964            .await
25965            .expect("query fail");
25966
25967        for path in [
25968            "/api/worker/query-tasks/poll",
25969            "/api/worker/query-tasks/query-capture/complete",
25970            "/api/worker/query-tasks/query-capture/fail",
25971        ] {
25972            assert_eq!(
25973                server.worker_protocol_for(path).as_deref(),
25974                Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
25975                "unexpected protocol for {path}"
25976            );
25977        }
25978
25979        assert_eq!(
25980            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
25981            1
25982        );
25983        assert!(
25984            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
25985                .as_str()
25986                .is_some_and(|id| id.starts_with("rust-query-poll-"))
25987        );
25988    }
25989
25990    #[tokio::test]
25991    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
25992        let server = MockWorkerServer::transient_worker_failures();
25993        let client = Client::builder(server.base_url())
25994            .timeout(Duration::from_secs(2))
25995            .build()
25996            .expect("client");
25997
25998        client
25999            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
26000            .await
26001            .expect("workflow poll retry");
26002        client
26003            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
26004            .await
26005            .expect("activity poll retry");
26006        client
26007            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26008            .await
26009            .expect("query poll retry");
26010
26011        for path in [
26012            "/api/worker/workflow-tasks/poll",
26013            "/api/worker/activity-tasks/poll",
26014            "/api/worker/query-tasks/poll",
26015        ] {
26016            let bodies = server.request_bodies(path);
26017            assert_eq!(bodies.len(), 2, "{path} must be retried once");
26018            assert_eq!(
26019                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
26020                "{path} must preserve the request binding across retry"
26021            );
26022        }
26023    }
26024
26025    #[tokio::test]
26026    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
26027        let server = MockWorkerServer::consecutive_poll_failures(2);
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, "capture")
26033            .worker_id("capture-worker")
26034            .poll_timeout(Duration::from_millis(10))
26035            .retry_policy(WorkerRetryPolicy {
26036                max_retries: 2,
26037                initial_backoff: Duration::from_millis(1),
26038                max_backoff: Duration::from_millis(1),
26039            });
26040        worker.register_workflow(
26041            "capture.workflow",
26042            |_ctx, _input| async move { Ok(Value::Null) },
26043        );
26044        worker.register_activity(
26045            "capture.activity",
26046            |_ctx, _input| async move { Ok(Value::Null) },
26047        );
26048        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
26049            Ok(Value::Null)
26050        });
26051
26052        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
26053
26054        for path in [
26055            "/api/worker/workflow-tasks/poll",
26056            "/api/worker/activity-tasks/poll",
26057            "/api/worker/query-tasks/poll",
26058        ] {
26059            let bodies = server.request_bodies(path);
26060            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
26061            assert!(
26062                bodies
26063                    .iter()
26064                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
26065                "{path} must preserve one request binding across every retry"
26066            );
26067        }
26068    }
26069
26070    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
26071        let reason = if unavailable {
26072            "storage_admission_unavailable"
26073        } else {
26074            "storage_pressure"
26075        };
26076        let mut body = json!({
26077            "reason": reason,
26078            "storage_state": if unavailable { "fenced" } else { "draining" },
26079            "retryable": true,
26080            "retry_after_seconds": 1,
26081        });
26082        if !mid_poll {
26083            body["request_admitted"] = json!(false);
26084        }
26085        if let Some(id) = poll_id {
26086            body["task"] = Value::Null;
26087            body["poll_status"] = json!(reason);
26088            body["poll_request_id"] = json!(id);
26089            body["retry_same_poll_request_id"] = json!(true);
26090            body["claim_admitted"] = json!(false);
26091        }
26092        body
26093    }
26094
26095    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
26096        let operation = match path {
26097            "/api/worker/register" => "register_worker",
26098            "/api/worker/heartbeat" => "heartbeat_worker",
26099            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
26100            "/api/worker/activity-tasks/poll" => "poll_activity_task",
26101            "/api/worker/query-tasks/poll" => "poll_query_task",
26102            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
26103            _ => return None,
26104        };
26105        let request: Value = serde_json::from_str(request).ok()?;
26106        let mut response = json!({
26107            "reason": "backend_unavailable",
26108            "operation": operation,
26109            "outcome": "unknown",
26110            "retryable": true,
26111            "retry_after_seconds": 1,
26112            "worker_id": request["worker_id"],
26113            "task_queue": request.get("task_queue"),
26114        });
26115        if path.ends_with("/poll") {
26116            response["task"] = Value::Null;
26117            response["poll_status"] = json!("backend_unavailable");
26118            response["poll_request_id"] = request["poll_request_id"].clone();
26119            response["retry_same_poll_request_id"] = json!(true);
26120        }
26121        Some(response)
26122    }
26123
26124    fn backend_retry_override(
26125        path: &str,
26126        request: &str,
26127        number: usize,
26128    ) -> Option<(&'static str, String)> {
26129        if number > 8 {
26130            return None;
26131        }
26132        Some((
26133            "503 Service Unavailable",
26134            backend_refusal(path, request)?.to_string(),
26135        ))
26136    }
26137
26138    fn backend_unavailable_override(
26139        path: &str,
26140        request: &str,
26141        _number: usize,
26142    ) -> Option<(&'static str, String)> {
26143        Some((
26144            "503 Service Unavailable",
26145            backend_refusal(path, request)?.to_string(),
26146        ))
26147    }
26148
26149    fn storage_worker(server: &MockWorkerServer) -> Worker {
26150        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
26151            .worker_id("storage-worker")
26152            .retry_policy(WorkerRetryPolicy {
26153                max_retries: 1,
26154                initial_backoff: Duration::from_millis(1),
26155                max_backoff: Duration::from_millis(1),
26156            })
26157    }
26158
26159    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
26160        let requests = server.requests.lock().expect("requests");
26161        let bodies: Vec<_> = requests
26162            .iter()
26163            .filter(|request| request.path == path)
26164            .map(|request| &request.body)
26165            .collect();
26166        assert_eq!(bodies.len(), count, "{path}");
26167        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
26168    }
26169
26170    #[test]
26171    fn backend_recovery_requires_the_explicit_worker_contract() {
26172        for (path, operation) in [
26173            ("/worker/register", "register_worker"),
26174            ("/worker/heartbeat", "heartbeat_worker"),
26175            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
26176            ("/worker/activity-tasks/poll", "poll_activity_task"),
26177            ("/worker/query-tasks/poll", "poll_query_task"),
26178            (
26179                "/worker/update-validation-tasks/poll",
26180                "poll_update_validation_task",
26181            ),
26182        ] {
26183            let poll_id = path.ends_with("/poll").then_some("same-poll");
26184            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
26185            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
26186                .expect("worker operation");
26187            assert_eq!(body["operation"], operation);
26188            let error = Error::Http {
26189                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26190                body: body.to_string(),
26191            };
26192            assert_eq!(
26193                worker_backend_unavailable_retry_after(&error, path, poll_id),
26194                Some(Duration::from_secs(1))
26195            );
26196            assert!(!worker_operation_is_retryable(&error));
26197            for (field, value) in [
26198                ("operation", json!("wrong_operation")),
26199                ("outcome", json!("completed")),
26200                ("retryable", json!(false)),
26201                ("retry_after_seconds", json!(0)),
26202                ("worker_id", json!("")),
26203            ] {
26204                let mut invalid = body.clone();
26205                invalid[field] = value;
26206                let error = Error::Http {
26207                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26208                    body: invalid.to_string(),
26209                };
26210                assert!(
26211                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
26212                    "{path}: {field}"
26213                );
26214                assert!(!worker_operation_is_retryable(&error));
26215            }
26216            if let Some(poll_id) = poll_id {
26217                for (field, value) in [
26218                    ("poll_request_id", json!("wrong-poll")),
26219                    ("poll_status", json!("empty")),
26220                    ("task", json!({"task_id":"claimed"})),
26221                    ("retry_same_poll_request_id", json!(false)),
26222                ] {
26223                    let mut invalid = body.clone();
26224                    invalid[field] = value;
26225                    let error = Error::Http {
26226                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26227                        body: invalid.to_string(),
26228                    };
26229                    assert!(
26230                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
26231                            .is_none(),
26232                        "{path}: {field}"
26233                    );
26234                }
26235            }
26236            let error = Error::Http {
26237                status: reqwest::StatusCode::UNAUTHORIZED,
26238                body: body.to_string(),
26239            };
26240            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
26241            assert!(!worker_operation_is_retryable(&error));
26242        }
26243    }
26244
26245    #[tokio::test]
26246    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
26247        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26248            request_override: Some(backend_retry_override),
26249            ..MockWorkerBehavior::default()
26250        });
26251        let mut worker =
26252            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26253        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
26254        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
26255        worker.register_query("backend.workflow", "state", |_, _| async {
26256            Ok(Value::Null)
26257        });
26258        worker.register().await.expect("registration recovery");
26259        worker
26260            .client
26261            .heartbeat_worker("storage-worker", 1, 1)
26262            .await
26263            .expect("heartbeat recovery");
26264        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
26265        for path in [
26266            "/api/worker/register",
26267            "/api/worker/heartbeat",
26268            "/api/worker/workflow-tasks/poll",
26269            "/api/worker/activity-tasks/poll",
26270            "/api/worker/query-tasks/poll",
26271        ] {
26272            assert_identical_requests(&server, path, 9);
26273        }
26274    }
26275
26276    #[tokio::test]
26277    async fn backend_recovery_wait_stops_with_worker() {
26278        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26279            request_override: Some(backend_unavailable_override),
26280            ..MockWorkerBehavior::default()
26281        });
26282        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
26283            max_retries: 1,
26284            initial_backoff: Duration::from_secs(2),
26285            max_backoff: Duration::from_secs(2),
26286        });
26287        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
26288        let started = tokio::time::Instant::now();
26289        let _ = tokio::time::timeout(
26290            Duration::from_secs(1),
26291            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
26292        )
26293        .await
26294        .expect("shutdown interrupts backend wait");
26295        assert!(started.elapsed() < Duration::from_secs(1));
26296        assert!(server.request_count("/api/worker/register") >= 1);
26297    }
26298
26299    #[test]
26300    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
26301        for unavailable in [false, true] {
26302            for mid_poll in [false, true] {
26303                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
26304                let error = Error::Http {
26305                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26306                    body: body.to_string(),
26307                };
26308                assert_eq!(
26309                    worker_storage_admission_retry_after(&error, Some("same-poll")),
26310                    Some(Duration::from_secs(1))
26311                );
26312                assert!(
26313                    !worker_operation_is_retryable(&error),
26314                    "storage is not a bounded generic retry"
26315                );
26316                for (field, value) in [
26317                    ("poll_request_id", json!("wrong-poll")),
26318                    ("task", json!({"task_id":"claimed"})),
26319                    ("retryable", json!(false)),
26320                    ("retry_after_seconds", json!(0)),
26321                    ("retry_after_seconds", json!(true)),
26322                    ("retry_after_seconds", json!(1.0)),
26323                    ("storage_state", json!("normal")),
26324                    ("poll_status", json!("empty")),
26325                    ("claim_admitted", json!(true)),
26326                    ("retry_same_poll_request_id", json!(false)),
26327                    ("request_admitted", json!(true)),
26328                ] {
26329                    let mut invalid = body.clone();
26330                    invalid[field] = value;
26331                    let error = Error::Http {
26332                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26333                        body: invalid.to_string(),
26334                    };
26335                    assert!(
26336                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
26337                        "{field}"
26338                    );
26339                }
26340            }
26341        }
26342        let body = storage_refusal(None, false, false);
26343        let error = Error::Http {
26344            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26345            body: body.to_string(),
26346        };
26347        assert!(worker_storage_admission_retry_after(&error, None).is_some());
26348        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
26349        let error = Error::Http {
26350            status: reqwest::StatusCode::FORBIDDEN,
26351            body: body.to_string(),
26352        };
26353        assert!(worker_storage_admission_retry_after(&error, None).is_none());
26354        let body = storage_refusal(None, false, true);
26355        let error = Error::Http {
26356            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26357            body: body.to_string(),
26358        };
26359        assert!(worker_storage_admission_retry_after(&error, None).is_none());
26360    }
26361
26362    #[tokio::test]
26363    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
26364        for unavailable in [false, true] {
26365            for mid_poll in [false, true] {
26366                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26367                    poll_failures_per_path: 1,
26368                    storage_refusals: 7,
26369                    storage_path: Some("/poll"),
26370                    storage_unavailable: unavailable,
26371                    storage_mid_poll: mid_poll,
26372                    ..MockWorkerBehavior::default()
26373                });
26374                let mut worker = storage_worker(&server);
26375                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
26376                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
26377                for path in [
26378                    "/api/worker/workflow-tasks/poll",
26379                    "/api/worker/activity-tasks/poll",
26380                    "/api/worker/query-tasks/poll",
26381                ] {
26382                    assert_identical_requests(&server, path, 9);
26383                }
26384            }
26385        }
26386    }
26387
26388    #[tokio::test]
26389    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
26390        struct CountedBody(Arc<AtomicUsize>);
26391        impl Serialize for CountedBody {
26392            fn serialize<S: Serializer>(
26393                &self,
26394                serializer: S,
26395            ) -> std::result::Result<S::Ok, S::Error> {
26396                let count = self.0.fetch_add(1, Ordering::SeqCst);
26397                json!({"serialization":count,"lease_owner":"worker","attempt":7})
26398                    .serialize(serializer)
26399            }
26400        }
26401        for path in [
26402            "/api/worker/register",
26403            "/api/worker/heartbeat",
26404            "/api/worker/workflow-tasks/storage-task/complete",
26405            "/api/worker/workflow-tasks/storage-task/fail",
26406            "/api/worker/activity-tasks/storage-task/complete",
26407            "/api/worker/activity-tasks/storage-task/fail",
26408            "/api/worker/activity-tasks/storage-task/heartbeat",
26409            "/api/worker/query-tasks/storage-task/complete",
26410            "/api/worker/query-tasks/storage-task/fail",
26411        ] {
26412            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26413                storage_refusals: 7,
26414                storage_path: Some(path),
26415                ..MockWorkerBehavior::default()
26416            });
26417            let worker =
26418                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26419            let calls = Arc::new(AtomicUsize::new(0));
26420            let _: Value = worker
26421                .client
26422                .request_json(
26423                    reqwest::Method::POST,
26424                    &path[4..],
26425                    RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
26426                    Some(&CountedBody(Arc::clone(&calls))),
26427                )
26428                .await
26429                .expect("prepared request recovery");
26430            assert_eq!(calls.load(Ordering::SeqCst), 1);
26431            assert_identical_requests(&server, path, 8);
26432        }
26433        for worker_scope in [false, true] {
26434            let path = if worker_scope {
26435                "/api/health"
26436            } else {
26437                "/api/worker/register"
26438            };
26439            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26440                storage_refusals: usize::MAX,
26441                storage_path: Some(path),
26442                ..MockWorkerBehavior::default()
26443            });
26444            let worker = storage_worker(&server);
26445            let client = worker.client.clone();
26446            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
26447            let error = if worker_scope {
26448                worker
26449                    .client
26450                    .health()
26451                    .await
26452                    .expect_err("control plane is not retried")
26453            } else {
26454                client
26455                    .request_json::<Value, Value>(
26456                        reqwest::Method::POST,
26457                        "/worker/register",
26458                        RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
26459                        Some(&json!({})),
26460                    )
26461                    .await
26462                    .expect_err("direct client is not retried")
26463            };
26464            assert!(worker_storage_admission_body(&error).is_some());
26465            assert_eq!(server.request_count(path), 1);
26466        }
26467    }
26468
26469    #[tokio::test]
26470    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
26471        for fail in [false, true] {
26472            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26473                storage_activity: true,
26474                storage_refusals: 7,
26475                storage_path: Some("/storage-activity/"),
26476                ..MockWorkerBehavior::default()
26477            });
26478            let mut worker = storage_worker(&server);
26479            let calls = Arc::new(AtomicUsize::new(0));
26480            let observed = Arc::clone(&calls);
26481            worker.register_activity("storage.activity", move |ctx, _| {
26482                let calls = Arc::clone(&observed);
26483                async move {
26484                    calls.fetch_add(1, Ordering::SeqCst);
26485                    ctx.heartbeat(json!({"step":2})).await?;
26486                    if fail {
26487                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
26488                    } else {
26489                        Ok(json!({"receipt":true}))
26490                    }
26491                }
26492            });
26493            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
26494            assert_eq!(calls.load(Ordering::SeqCst), 1);
26495            assert_identical_requests(
26496                &server,
26497                "/api/worker/activity-tasks/storage-activity/heartbeat",
26498                8,
26499            );
26500            let suffix = if fail { "fail" } else { "complete" };
26501            assert_identical_requests(
26502                &server,
26503                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
26504                8,
26505            );
26506            let other = if fail { "complete" } else { "fail" };
26507            assert_eq!(
26508                server.request_count(&format!(
26509                    "/api/worker/activity-tasks/storage-activity/{other}"
26510                )),
26511                0
26512            );
26513        }
26514    }
26515
26516    #[tokio::test]
26517    async fn storage_waits_are_interruptible_without_false_activity_failure() {
26518        for path in [
26519            "/api/worker/register",
26520            "/api/worker/heartbeat",
26521            "/api/worker/activity-tasks/poll",
26522            "/api/worker/activity-tasks/storage-activity/heartbeat",
26523            "/api/worker/activity-tasks/storage-activity/complete",
26524        ] {
26525            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26526                storage_activity: true,
26527                storage_refusals: usize::MAX,
26528                storage_path: Some(path),
26529                ..MockWorkerBehavior::default()
26530            });
26531            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
26532            worker.register_activity("storage.activity", |ctx, _| async move {
26533                ctx.heartbeat(json!({"step":2})).await?;
26534                Ok(json!({"receipt":true}))
26535            });
26536            let shutdown = async {
26537                while server.request_count(path) == 0 {
26538                    tokio::time::sleep(Duration::from_millis(1)).await;
26539                }
26540            };
26541            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
26542                .await
26543                .expect("shutdown interrupts admission");
26544            assert!(
26545                result.is_err(),
26546                "a refused operation must not appear acknowledged: {path}, {result:?}"
26547            );
26548            assert_eq!(server.request_count(path), 1);
26549            assert_eq!(
26550                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
26551                0
26552            );
26553            assert_eq!(
26554                server.request_count("/api/worker/registrations/mock-worker"),
26555                usize::from(!path.ends_with("/register"))
26556            );
26557        }
26558    }
26559
26560    #[tokio::test]
26561    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
26562        for fail in [false, true] {
26563            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26564                storage_query: true,
26565                storage_refusals: 7,
26566                storage_path: Some("/storage-query/"),
26567                ..MockWorkerBehavior::default()
26568            });
26569            let mut worker = storage_worker(&server);
26570            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
26571            let calls = Arc::new(AtomicUsize::new(0));
26572            let observed = Arc::clone(&calls);
26573            worker.register_query("storage.workflow", "state", move |_, _| {
26574                let calls = Arc::clone(&observed);
26575                async move {
26576                    calls.fetch_add(1, Ordering::SeqCst);
26577                    if fail {
26578                        Err(Error::WorkerLoop("intentional query failure".to_string()))
26579                    } else {
26580                        Ok(json!({"state":"waiting"}))
26581                    }
26582                }
26583            });
26584            assert_eq!(worker.run_once().await.expect("query settled"), 1);
26585            assert_eq!(calls.load(Ordering::SeqCst), 1);
26586            let suffix = if fail { "fail" } else { "complete" };
26587            assert_identical_requests(
26588                &server,
26589                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
26590                8,
26591            );
26592            let other = if fail { "complete" } else { "fail" };
26593            assert_eq!(
26594                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
26595                0
26596            );
26597        }
26598    }
26599
26600    #[tokio::test]
26601    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
26602        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26603            storage_refusals: 7,
26604            storage_path: Some("/poll"),
26605            unauthorized_polls: true,
26606            ..MockWorkerBehavior::default()
26607        });
26608        let error = storage_worker(&server)
26609            .run_once()
26610            .await
26611            .expect_err("auth remains terminal");
26612        assert!(matches!(
26613            error,
26614            Error::Http {
26615                status: reqwest::StatusCode::UNAUTHORIZED,
26616                ..
26617            }
26618        ));
26619        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
26620
26621        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26622            storage_refusals: 7,
26623            storage_path: Some("/activity-cancel/complete"),
26624            ..MockWorkerBehavior::default()
26625        });
26626        let worker =
26627            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26628        let error = worker
26629            .client
26630            .complete_activity_task(
26631                "activity-cancel",
26632                "attempt-cancel",
26633                "worker",
26634                json!({}),
26635                DEFAULT_CODEC,
26636            )
26637            .await
26638            .expect_err("cancellation remains terminal");
26639        assert!(activity_task_rejection_is_final(&error));
26640        assert_identical_requests(
26641            &server,
26642            "/api/worker/activity-tasks/activity-cancel/complete",
26643            8,
26644        );
26645
26646        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26647            storage_refusals: usize::MAX,
26648            storage_path: Some("/poll"),
26649            storage_wrong_poll_id: true,
26650            ..MockWorkerBehavior::default()
26651        });
26652        assert!(storage_worker(&server).run_once().await.is_err());
26653        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
26654    }
26655
26656    #[tokio::test]
26657    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
26658        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26659            storage_refusals: usize::MAX,
26660            storage_path: Some("/poll"),
26661            ..MockWorkerBehavior::default()
26662        });
26663        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
26664        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
26665        let run = tokio::spawn(async move { worker.run().await });
26666        tokio::time::timeout(Duration::from_secs(2), async {
26667            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
26668                tokio::time::sleep(Duration::from_millis(1)).await;
26669            }
26670        })
26671        .await
26672        .expect("poll started");
26673        run.abort();
26674        assert!(run.await.expect_err("cancelled run").is_cancelled());
26675        tokio::time::sleep(Duration::from_millis(250)).await;
26676        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
26677    }
26678
26679    #[tokio::test]
26680    async fn query_protocol_rejection_from_older_server_is_typed() {
26681        let server = MockWorkerServer::reject_query_protocol();
26682        let client = Client::builder(server.base_url())
26683            .timeout(Duration::from_secs(2))
26684            .build()
26685            .expect("client");
26686
26687        let error = client
26688            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26689            .await
26690            .expect_err("server below query protocol floor must reject");
26691        let Error::Protocol(failure) = error else {
26692            panic!("expected typed protocol failure");
26693        };
26694
26695        assert_eq!(failure.status, 400);
26696        assert_eq!(failure.reason, "unsupported_protocol_version");
26697        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
26698        assert_eq!(
26699            failure.requested_version.as_deref(),
26700            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
26701        );
26702        assert_eq!(
26703            server
26704                .worker_protocol_for("/api/worker/query-tasks/poll")
26705                .as_deref(),
26706            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
26707        );
26708    }
26709
26710    #[tokio::test]
26711    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
26712        let server = MockWorkerServer::reject_query_protocol();
26713        let client = Client::builder(server.base_url())
26714            .timeout(Duration::from_secs(2))
26715            .build()
26716            .expect("client");
26717        let mut worker = Worker::new(client, "rust-workers")
26718            .worker_id("baseline-worker")
26719            .poll_timeout(Duration::from_millis(10));
26720
26721        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
26722            Ok(Value::Null)
26723        });
26724
26725        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
26726        assert_eq!(
26727            server
26728                .worker_protocol_for("/api/worker/workflow-tasks/poll")
26729                .as_deref(),
26730            Some(WORKER_PROTOCOL_VERSION)
26731        );
26732        assert_eq!(
26733            server.worker_protocol_for("/api/worker/query-tasks/poll"),
26734            None,
26735            "a worker without query handlers must not use the query-task endpoint"
26736        );
26737    }
26738
26739    #[tokio::test]
26740    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
26741        let server = MockWorkerServer::reject_query_completion();
26742        let client = Client::builder(server.base_url())
26743            .timeout(Duration::from_secs(2))
26744            .build()
26745            .expect("client");
26746
26747        let error = client
26748            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
26749            .await
26750            .expect_err("expired completion must be rejected");
26751        let Error::QueryFailed(failure) = error else {
26752            panic!("expected typed query failure");
26753        };
26754        assert_eq!(failure.status, 409);
26755        assert_eq!(failure.reason, "query_task_timed_out");
26756
26757        let mut worker = Worker::new(client, "rust-workers")
26758            .worker_id("late-worker")
26759            .poll_timeout(Duration::from_millis(10));
26760        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26761        worker.register_query(
26762            "counter",
26763            "current",
26764            |_ctx, _args| async move { Ok(json!(8)) },
26765        );
26766
26767        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
26768        assert_eq!(
26769            worker
26770                .run_once()
26771                .await
26772                .expect("worker continues after late completion"),
26773            0
26774        );
26775        assert_eq!(
26776            server.request_count("/api/worker/query-tasks/query-late/complete"),
26777            2
26778        );
26779        assert_eq!(
26780            server.request_count("/api/worker/query-tasks/query-late/fail"),
26781            0,
26782            "a server completion rejection must not be reported as an encoding failure"
26783        );
26784    }
26785
26786    #[tokio::test]
26787    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
26788        let server = MockWorkerServer::start();
26789        let client = Client::builder(server.base_url())
26790            .timeout(Duration::from_secs(2))
26791            .build()
26792            .expect("client");
26793        let mut worker = Worker::new(client, "rust-workers")
26794            .worker_id("joined-worker")
26795            .poll_timeout(Duration::from_millis(10));
26796        worker.register_workflow(
26797            "joined.workflow",
26798            |_ctx, _input| async move { Ok(Value::Null) },
26799        );
26800        worker.register_activity(
26801            "joined.activity",
26802            |_ctx, _input| async move { Ok(Value::Null) },
26803        );
26804        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
26805            Ok(Value::Null)
26806        });
26807
26808        worker
26809            .run_until(tokio::time::sleep(Duration::from_millis(20)))
26810            .await
26811            .expect("normal shutdown");
26812
26813        let deregistration_path = "/api/worker/registrations/mock-worker";
26814        assert_eq!(server.request_count(deregistration_path), 1);
26815        for poll_path in [
26816            "/api/worker/workflow-tasks/poll",
26817            "/api/worker/activity-tasks/poll",
26818            "/api/worker/query-tasks/poll",
26819        ] {
26820            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
26821        }
26822        assert_eq!(
26823            server.captured_paths().last().map(String::as_str),
26824            Some(deregistration_path),
26825            "deregistration must start only after every poller has joined"
26826        );
26827    }
26828
26829    #[tokio::test]
26830    async fn registration_failure_does_not_deregister() {
26831        let server = MockWorkerServer::rejected_registration();
26832        let client = Client::builder(server.base_url())
26833            .timeout(Duration::from_secs(2))
26834            .build()
26835            .expect("client");
26836        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
26837
26838        let error = worker
26839            .run_until(async {})
26840            .await
26841            .expect_err("registration must fail");
26842        assert!(matches!(
26843            error,
26844            Error::Http {
26845                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26846                ..
26847            }
26848        ));
26849        assert!(server
26850            .captured_paths()
26851            .iter()
26852            .all(|path| !path.starts_with("/api/worker/registrations/")));
26853    }
26854
26855    #[tokio::test]
26856    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
26857        let server = MockWorkerServer::rejected_registration_protocol();
26858        let client = Client::builder(server.base_url())
26859            .timeout(Duration::from_secs(2))
26860            .build()
26861            .expect("client");
26862        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
26863
26864        let error = worker
26865            .run_until(async {})
26866            .await
26867            .expect_err("a protocol 1.16 server must reject this worker");
26868        let Error::Protocol(failure) = error else {
26869            panic!("expected typed protocol rejection");
26870        };
26871        assert_eq!(failure.reason, "unsupported_protocol_version");
26872        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
26873        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
26874        assert_eq!(
26875            server
26876                .worker_protocol_for("/api/worker/register")
26877                .as_deref(),
26878            Some(WORKER_PROTOCOL_VERSION)
26879        );
26880    }
26881
26882    #[tokio::test]
26883    async fn declined_registration_does_not_deregister() {
26884        let server = MockWorkerServer::declined_registration();
26885        let client = Client::builder(server.base_url())
26886            .timeout(Duration::from_secs(2))
26887            .build()
26888            .expect("client");
26889        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
26890
26891        let error = worker
26892            .run_until(async {})
26893            .await
26894            .expect_err("declined registration must fail");
26895        assert!(matches!(error, Error::WorkerLoop(_)));
26896        assert!(error.to_string().contains("was not accepted"));
26897        assert!(server
26898            .captured_paths()
26899            .iter()
26900            .all(|path| !path.starts_with("/api/worker/registrations/")));
26901    }
26902
26903    #[tokio::test]
26904    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
26905        let server = MockWorkerServer::rejected_deregistration();
26906        let client = Client::builder(server.base_url())
26907            .timeout(Duration::from_secs(2))
26908            .build()
26909            .expect("client");
26910        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
26911
26912        let error = worker
26913            .run_until(async {})
26914            .await
26915            .expect_err("deregistration must fail");
26916        assert!(matches!(
26917            error,
26918            Error::Http {
26919                status: reqwest::StatusCode::FORBIDDEN,
26920                ..
26921            }
26922        ));
26923        assert_eq!(
26924            server.request_count("/api/worker/registrations/mock-worker"),
26925            1
26926        );
26927    }
26928
26929    #[tokio::test]
26930    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
26931        let server = MockWorkerServer::rejected_deregistration_protocol();
26932        let client = Client::builder(server.base_url())
26933            .timeout(Duration::from_secs(2))
26934            .build()
26935            .expect("client");
26936        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
26937
26938        let error = worker
26939            .run_until(async {})
26940            .await
26941            .expect_err("protocol rejection must fail shutdown");
26942        let Error::Protocol(failure) = error else {
26943            panic!("expected typed protocol failure");
26944        };
26945        assert_eq!(failure.reason, "unsupported_protocol_version");
26946        assert_eq!(
26947            failure.requested_version.as_deref(),
26948            Some(WORKER_PROTOCOL_VERSION)
26949        );
26950        assert_eq!(
26951            server.request_count("/api/worker/registrations/mock-worker"),
26952            1
26953        );
26954    }
26955
26956    #[tokio::test]
26957    async fn primary_poller_error_retains_deregistration_failure_context() {
26958        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
26959        let client = Client::builder(server.base_url())
26960            .timeout(Duration::from_secs(2))
26961            .build()
26962            .expect("client");
26963        let mut worker = Worker::new(client, "rust-workers")
26964            .worker_id("combined-failure")
26965            .poll_timeout(Duration::from_millis(10));
26966        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
26967            Ok(Value::Null)
26968        });
26969
26970        let error = worker
26971            .run()
26972            .await
26973            .expect_err("worker and cleanup must fail");
26974        let summary = error.to_string();
26975        assert!(summary.contains("authentication_failed"));
26976        assert!(summary.contains("worker cannot deregister"));
26977        let Error::WorkerShutdown {
26978            primary,
26979            deregistration,
26980        } = error
26981        else {
26982            panic!("expected combined worker shutdown error");
26983        };
26984        assert!(matches!(
26985            *primary,
26986            Error::Http {
26987                status: reqwest::StatusCode::UNAUTHORIZED,
26988                ..
26989            }
26990        ));
26991        assert!(matches!(
26992            *deregistration,
26993            Error::Http {
26994                status: reqwest::StatusCode::FORBIDDEN,
26995                ..
26996            }
26997        ));
26998        assert_eq!(
26999            server.request_count("/api/worker/registrations/mock-worker"),
27000            1
27001        );
27002    }
27003
27004    #[tokio::test]
27005    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
27006        let server = MockWorkerServer::start();
27007        let client = Client::builder(server.base_url())
27008            .timeout(Duration::from_secs(2))
27009            .build()
27010            .expect("client");
27011        let mut worker = Worker::new(client, "rust-workers")
27012            .worker_id("activity-only-worker")
27013            .poll_timeout(Duration::from_millis(10));
27014
27015        worker.register_activity(
27016            "activity.only",
27017            |_ctx, _args| async move { Ok(Value::Null) },
27018        );
27019
27020        worker.run_until(async {}).await.expect("run worker");
27021    }
27022
27023    #[tokio::test]
27024    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
27025        let server = MockWorkerServer::start();
27026        let client = Client::builder(server.base_url())
27027            .timeout(Duration::from_secs(2))
27028            .build()
27029            .expect("client");
27030        let mut worker = Worker::new(client, "rust-workers")
27031            .worker_id("workflow-only-worker")
27032            .poll_timeout(Duration::from_millis(10));
27033
27034        worker.register_workflow(
27035            "workflow.only",
27036            |_ctx, _input| async move { Ok(Value::Null) },
27037        );
27038
27039        worker.run_until(async {}).await.expect("run worker");
27040    }
27041
27042    #[tokio::test]
27043    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
27044        let server = MockWorkerServer::start();
27045        let client = Client::builder(server.base_url())
27046            .timeout(Duration::from_secs(2))
27047            .build()
27048            .expect("client");
27049        let observations = Arc::new(Mutex::new(Vec::new()));
27050        let observed = Arc::clone(&observations);
27051        let mut worker = Worker::new(client, "rust-workers")
27052            .worker_id("observed-heartbeat-worker")
27053            .poll_timeout(Duration::from_millis(10))
27054            .on_worker_heartbeat(move |observation| {
27055                observed
27056                    .lock()
27057                    .expect("heartbeat observations")
27058                    .push(observation.clone());
27059            });
27060
27061        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
27062            Ok(Value::Null)
27063        });
27064        let acknowledged = Arc::clone(&observations);
27065        worker
27066            .run_until(async move {
27067                tokio::time::timeout(Duration::from_secs(2), async move {
27068                    loop {
27069                        if !acknowledged
27070                            .lock()
27071                            .expect("heartbeat observations")
27072                            .is_empty()
27073                        {
27074                            break;
27075                        }
27076                        tokio::time::sleep(Duration::from_millis(1)).await;
27077                    }
27078                })
27079                .await
27080                .expect("heartbeat acknowledgement within timeout");
27081            })
27082            .await
27083            .expect("run worker");
27084
27085        let observations = observations.lock().expect("heartbeat observations");
27086        let first = observations.first().expect("heartbeat acknowledgement");
27087        assert_eq!(first.worker_id, "observed-heartbeat-worker");
27088        assert_eq!(first.task_queue, "rust-workers");
27089        assert!(first.acknowledged_at_unix_millis > 0);
27090        assert_eq!(first.acknowledgement, json!({}));
27091    }
27092
27093    #[tokio::test]
27094    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
27095        let server = MockWorkerServer::delayed_heartbeat_worker();
27096        let client = Client::builder(server.base_url())
27097            .timeout(Duration::from_secs(3))
27098            .build()
27099            .expect("client");
27100        let observations = Arc::new(Mutex::new(Vec::new()));
27101        let observed = Arc::clone(&observations);
27102        let mut worker = Worker::new(client, "rust-snapshot-workers")
27103            .worker_id("rust-snapshot-worker")
27104            .poll_timeout(Duration::from_millis(10))
27105            .on_worker_heartbeat(move |observation| {
27106                observed
27107                    .lock()
27108                    .expect("heartbeat observations")
27109                    .push(observation.clone());
27110            });
27111
27112        worker.register_workflow("snapshot", |ctx, _input| async move {
27113            ctx.wait_signal("finish").await?;
27114            Ok(json!({"status": "finished"}))
27115        });
27116        worker.register_query("snapshot", "current", |ctx, _args| async move {
27117            Ok(json!(ctx
27118                .signals("increment")
27119                .iter()
27120                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
27121                .sum::<i64>()))
27122        });
27123        worker.register_activity("cancel-aware", |_ctx, _args| async move {
27124            Ok(json!({"late": "completion"}))
27125        });
27126
27127        worker
27128            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
27129            .await
27130            .expect("delayed heartbeat must allow a clean worker shutdown");
27131
27132        let observations = observations.lock().expect("heartbeat observations");
27133        assert!(
27134            observations.len() >= 3,
27135            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
27136        );
27137        assert!(
27138            observations.windows(2).all(|pair| {
27139                pair[1].acknowledged_at_unix_millis
27140                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
27141                    >= 850
27142            }),
27143            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
27144        );
27145        drop(observations);
27146
27147        let heartbeat_times = server.request_times("/api/worker/heartbeat");
27148        let delayed_request_at = *heartbeat_times
27149            .get(1)
27150            .expect("intentionally delayed heartbeat request");
27151        let delay_window_start = delayed_request_at + Duration::from_millis(100);
27152        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
27153        for path in [
27154            "/api/worker/workflow-tasks/poll",
27155            "/api/worker/activity-tasks/poll",
27156            "/api/worker/query-tasks/poll",
27157        ] {
27158            assert!(
27159                server
27160                    .request_times(path)
27161                    .iter()
27162                    .any(|received_at| *received_at >= delay_window_start
27163                        && *received_at <= delay_window_end),
27164                "{path} must keep polling while a heartbeat acknowledgement is delayed"
27165            );
27166        }
27167        assert!(
27168            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
27169            "workflow work must be settled"
27170        );
27171        assert!(
27172            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
27173            "activity work must be settled"
27174        );
27175        assert!(
27176            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
27177            "query work must be settled"
27178        );
27179    }
27180
27181    #[tokio::test]
27182    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
27183        let server = MockWorkerServer::heartbeat_retry_worker();
27184        let client = Client::builder(server.base_url())
27185            .timeout(Duration::from_secs(2))
27186            .build()
27187            .expect("client");
27188        let observations = Arc::new(Mutex::new(Vec::new()));
27189        let observed = Arc::clone(&observations);
27190        let worker = Worker::new(client, "rust-workers")
27191            .worker_id("heartbeat-retry-worker")
27192            .retry_policy(WorkerRetryPolicy {
27193                max_retries: 1,
27194                initial_backoff: Duration::from_millis(300),
27195                max_backoff: Duration::from_millis(300),
27196            })
27197            .on_worker_heartbeat(move |observation| {
27198                observed
27199                    .lock()
27200                    .expect("heartbeat observations")
27201                    .push(observation.clone());
27202            });
27203
27204        worker
27205            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
27206            .await
27207            .expect("retryable heartbeat failure must remain bounded and recover");
27208
27209        let observations = observations.lock().expect("heartbeat observations");
27210        assert!(observations.len() >= 3, "heartbeat retry must recover");
27211        assert!(
27212            observations.windows(2).all(|pair| {
27213                pair[1]
27214                    .acknowledged_at_unix_millis
27215                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
27216                    >= 850
27217            }),
27218            "a successful retry must start a fresh advertised cadence: {observations:?}"
27219        );
27220        assert_eq!(
27221            server.request_count("/api/worker/heartbeat"),
27222            observations.len() + 1,
27223            "one retryable failure must add exactly one bounded request"
27224        );
27225    }
27226
27227    #[tokio::test]
27228    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
27229        let server = MockWorkerServer::waiting_query_worker();
27230        let client = Client::builder(server.base_url())
27231            .timeout(Duration::from_secs(2))
27232            .build()
27233            .expect("client");
27234        let observations = Arc::new(Mutex::new(Vec::new()));
27235        let observed = Arc::clone(&observations);
27236        let mut worker = Worker::new(client, "rust-snapshot-workers")
27237            .worker_id("rust-snapshot-worker")
27238            .poll_timeout(Duration::from_millis(10))
27239            .on_worker_heartbeat(move |observation| {
27240                observed
27241                    .lock()
27242                    .expect("heartbeat observations")
27243                    .push(observation.clone());
27244            });
27245
27246        worker.register_workflow("snapshot", |ctx, _input| async move {
27247            ctx.wait_signal("finish").await?;
27248            Ok(json!({"status": "finished"}))
27249        });
27250        worker.register_query("snapshot", "current", |ctx, _args| async move {
27251            let current = ctx
27252                .signals("increment")
27253                .iter()
27254                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
27255                .sum::<i64>();
27256            Ok(json!(current))
27257        });
27258        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
27259
27260        worker
27261            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
27262            .await
27263            .expect("pending workflow and query poller must remain live until shutdown");
27264
27265        assert!(
27266            observations.lock().expect("heartbeat observations").len() >= 4,
27267            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
27268        );
27269        assert!(
27270            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
27271            "workflow polling must continue after empty replay acknowledgements"
27272        );
27273        assert!(
27274            server.request_count("/api/worker/query-tasks/poll") >= 2,
27275            "query polling must continue after serving the current query"
27276        );
27277        assert_eq!(
27278            server.request_body("/api/worker/register")["capabilities"],
27279            json!([
27280                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
27281                DURABLE_SELECTION_CAPABILITY,
27282                MEMO_UPSERTS_CAPABILITY,
27283                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
27284                QUERY_TASKS_CAPABILITY,
27285                WORKFLOW_UPDATES_CAPABILITY,
27286                MESSAGE_STREAMS_CAPABILITY
27287            ])
27288        );
27289        assert_eq!(
27290            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
27291            json!({
27292                "queries": ["current"],
27293                "query_contracts": [],
27294                "signals": [],
27295                "signal_contracts": [],
27296                "updates": ["replace"],
27297                "update_contracts": [],
27298                "update_validators": [],
27299            })
27300        );
27301
27302        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
27303        assert_eq!(
27304            opened["commands"],
27305            json!([{
27306                "type": "open_signal_wait",
27307                "signal_name": "finish",
27308            }])
27309        );
27310
27311        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
27312            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
27313            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
27314            let failure = server.request_body(&fail_path);
27315            assert_eq!(
27316                failure["failure"]["type"],
27317                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
27318            );
27319            assert_eq!(server.request_count(&completion_path), 0);
27320        }
27321
27322        let query_completion =
27323            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
27324        assert_eq!(query_completion["result"], json!(8));
27325
27326        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
27327        assert_eq!(
27328            server.request_count(terminal_path),
27329            1,
27330            "the matching signal must settle the workflow exactly once"
27331        );
27332        let terminal = server.request_body(terminal_path);
27333        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
27334        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
27335        assert_eq!(
27336            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
27337                .expect("terminal workflow result"),
27338            json!({"status": "finished"})
27339        );
27340    }
27341
27342    #[tokio::test]
27343    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
27344        let server = MockWorkerServer::transient_worker_failures();
27345        let client = Client::builder(server.base_url())
27346            .timeout(Duration::from_secs(2))
27347            .build()
27348            .expect("client");
27349        let mut worker = Worker::new(client, "rust-workers")
27350            .worker_id("retry-worker")
27351            .poll_timeout(Duration::from_millis(10))
27352            .retry_policy(WorkerRetryPolicy {
27353                max_retries: 2,
27354                initial_backoff: Duration::from_millis(1),
27355                max_backoff: Duration::from_millis(1),
27356            });
27357        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27358        worker.register_activity(
27359            "counter.activity",
27360            |_ctx, _input| async move { Ok(Value::Null) },
27361        );
27362        worker.register_query(
27363            "counter",
27364            "current",
27365            |_ctx, _args| async move { Ok(json!(8)) },
27366        );
27367
27368        worker
27369            .run_until(tokio::time::sleep(Duration::from_millis(75)))
27370            .await
27371            .expect("transient failures must not stop the worker");
27372
27373        for path in [
27374            "/api/worker/heartbeat",
27375            "/api/worker/workflow-tasks/poll",
27376            "/api/worker/activity-tasks/poll",
27377            "/api/worker/query-tasks/poll",
27378        ] {
27379            assert!(
27380                server.request_count(path) >= 2,
27381                "{path} must continue after its transient failure"
27382            );
27383        }
27384    }
27385
27386    #[tokio::test]
27387    async fn worker_continues_after_long_poll_capacity_backpressure() {
27388        let server = MockWorkerServer::capacity_limited_activity_poll();
27389        let client = Client::builder(server.base_url())
27390            .timeout(Duration::from_secs(2))
27391            .build()
27392            .expect("client");
27393        let mut worker = Worker::new(client, "rust-workers")
27394            .worker_id("capacity-worker")
27395            .poll_timeout(Duration::from_millis(10))
27396            .retry_policy(WorkerRetryPolicy {
27397                max_retries: 0,
27398                initial_backoff: Duration::from_millis(1),
27399                max_backoff: Duration::from_millis(1),
27400            });
27401        worker.register_activity("capacity.activity", |_ctx, _input| async move {
27402            Ok(json!({"handled": true}))
27403        });
27404
27405        worker
27406            .run_until(tokio::time::sleep(Duration::from_millis(50)))
27407            .await
27408            .expect("capacity backpressure must not stop the worker");
27409
27410        assert!(
27411            server.request_count("/api/worker/activity-tasks/poll") >= 2,
27412            "the activity poller must continue after capacity backpressure"
27413        );
27414        assert_eq!(
27415            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
27416            1,
27417            "the worker must complete work returned after capacity recovers"
27418        );
27419    }
27420
27421    #[test]
27422    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
27423        let capacity = Error::Http {
27424            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27425            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
27426        };
27427        assert_eq!(
27428            worker_poll_capacity_retry_after(&capacity),
27429            Some(Duration::from_secs(3))
27430        );
27431
27432        let rejected_capacity = Error::Http {
27433            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27434            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
27435        };
27436        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
27437        assert!(!worker_operation_is_retryable(&rejected_capacity));
27438
27439        let ordinary_rate_limit = Error::Http {
27440            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27441            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
27442                .to_string(),
27443        };
27444        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
27445        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
27446    }
27447
27448    #[tokio::test]
27449    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
27450        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27451            poll_failures_per_path: 8,
27452            heartbeat_failures: 8,
27453            ..MockWorkerBehavior::default()
27454        });
27455        let client = Client::builder(server.base_url())
27456            .timeout(Duration::from_secs(2))
27457            .build()
27458            .expect("client");
27459        let acknowledgements = Arc::new(AtomicUsize::new(0));
27460        let observed = Arc::clone(&acknowledgements);
27461        let mut worker = Worker::new(client, "rust-workers")
27462            .recover_transient_outages(true)
27463            .poll_timeout(Duration::from_millis(10))
27464            .retry_policy(WorkerRetryPolicy {
27465                max_retries: 2,
27466                initial_backoff: Duration::from_millis(2),
27467                max_backoff: Duration::from_millis(5),
27468            })
27469            .on_worker_heartbeat(move |_| {
27470                observed.fetch_add(1, Ordering::SeqCst);
27471            });
27472        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27473        worker.register_activity(
27474            "counter.activity",
27475            |_ctx, _input| async move { Ok(Value::Null) },
27476        );
27477        worker.register_query("counter", "current", |_ctx, _args| async move {
27478            Ok(Value::Null)
27479        });
27480
27481        worker
27482            .run_until(tokio::time::sleep(Duration::from_millis(500)))
27483            .await
27484            .expect("a recoverable outage must not stop the service worker");
27485
27486        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
27487        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
27488        for path in [
27489            "/api/worker/workflow-tasks/poll",
27490            "/api/worker/activity-tasks/poll",
27491            "/api/worker/query-tasks/poll",
27492        ] {
27493            let bodies = server.request_bodies(path);
27494            assert!(bodies.len() >= 10, "{path} must resume after recovery");
27495            let first = &bodies[0]["poll_request_id"];
27496            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
27497            for body in &bodies[..9] {
27498                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
27499            }
27500            assert_ne!(&bodies[9]["poll_request_id"], first);
27501            let times = server.request_times(path);
27502            for pair in times[..9].windows(2) {
27503                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
27504            }
27505        }
27506    }
27507
27508    #[tokio::test]
27509    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
27510        for heartbeat_outage in [false, true] {
27511            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27512                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
27513                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
27514                ..MockWorkerBehavior::default()
27515            });
27516            let client = Client::builder(server.base_url()).build().expect("client");
27517            let mut worker = Worker::new(client, "rust-workers")
27518                .recover_transient_outages(true)
27519                .retry_policy(WorkerRetryPolicy {
27520                    max_retries: 1,
27521                    initial_backoff: Duration::from_secs(5),
27522                    max_backoff: Duration::from_secs(5),
27523                });
27524            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27525            let started = Instant::now();
27526            worker
27527                .run_until(tokio::time::sleep(Duration::from_millis(200)))
27528                .await
27529                .expect("shutdown during an outage is a normal stop");
27530            assert!(started.elapsed() < Duration::from_secs(1));
27531            let path = if heartbeat_outage {
27532                "/api/worker/heartbeat"
27533            } else {
27534                "/api/worker/workflow-tasks/poll"
27535            };
27536            assert_eq!(server.request_count(path), 1);
27537            assert_eq!(
27538                server.request_count("/api/worker/registrations/mock-worker"),
27539                1
27540            );
27541        }
27542    }
27543
27544    #[tokio::test]
27545    async fn worker_outage_recovery_keeps_run_once_bounded() {
27546        let server = MockWorkerServer::unavailable_polls();
27547        let client = Client::builder(server.base_url()).build().expect("client");
27548        let mut worker = Worker::new(client, "rust-workers")
27549            .recover_transient_outages(true)
27550            .retry_policy(WorkerRetryPolicy {
27551                max_retries: 2,
27552                initial_backoff: Duration::from_millis(1),
27553                max_backoff: Duration::from_millis(1),
27554            });
27555        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27556        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
27557        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
27558    }
27559
27560    #[tokio::test]
27561    async fn worker_outage_recovery_respects_disabled_retries() {
27562        let server = MockWorkerServer::unavailable_polls();
27563        let client = Client::builder(server.base_url()).build().expect("client");
27564        let mut worker = Worker::new(client, "rust-workers")
27565            .recover_transient_outages(true)
27566            .retry_policy(WorkerRetryPolicy {
27567                max_retries: 0,
27568                ..WorkerRetryPolicy::default()
27569            });
27570        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27571        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
27572        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27573    }
27574
27575    #[tokio::test]
27576    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
27577        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27578            heartbeat_failures: usize::MAX,
27579            unauthorized_polls: true,
27580            ..MockWorkerBehavior::default()
27581        });
27582        let client = Client::builder(server.base_url()).build().expect("client");
27583        let mut worker = Worker::new(client, "rust-workers")
27584            .recover_transient_outages(true)
27585            .retry_policy(WorkerRetryPolicy {
27586                max_retries: 1,
27587                initial_backoff: Duration::from_secs(5),
27588                max_backoff: Duration::from_secs(5),
27589            });
27590        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27591        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
27592            .await
27593            .expect("fatal poll errors must interrupt heartbeat recovery")
27594            .expect_err("authentication failure is terminal");
27595        assert!(
27596            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
27597        );
27598        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27599    }
27600
27601    #[tokio::test]
27602    async fn worker_bounds_transport_retries() {
27603        let server = MockWorkerServer::unavailable_polls();
27604        let client = Client::builder(server.base_url())
27605            .timeout(Duration::from_secs(2))
27606            .build()
27607            .expect("client");
27608        let mut worker = Worker::new(client, "rust-workers")
27609            .worker_id("bounded-retry-worker")
27610            .poll_timeout(Duration::from_millis(10))
27611            .retry_policy(WorkerRetryPolicy {
27612                max_retries: 2,
27613                initial_backoff: Duration::from_millis(1),
27614                max_backoff: Duration::from_millis(1),
27615            });
27616        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27617
27618        let error = worker.run().await.expect_err("retry bound must terminate");
27619        assert!(matches!(error, Error::Transport(_)));
27620        assert_eq!(
27621            server.request_count("/api/worker/workflow-tasks/poll"),
27622            3,
27623            "one initial request plus exactly two retries"
27624        );
27625    }
27626
27627    #[tokio::test]
27628    async fn worker_retry_policy_can_disable_poll_retries() {
27629        let server = MockWorkerServer::unavailable_polls();
27630        let client = Client::builder(server.base_url())
27631            .timeout(Duration::from_secs(2))
27632            .build()
27633            .expect("client");
27634        let mut worker = Worker::new(client, "rust-workers")
27635            .worker_id("no-retry-worker")
27636            .poll_timeout(Duration::from_millis(10))
27637            .retry_policy(WorkerRetryPolicy {
27638                max_retries: 0,
27639                initial_backoff: Duration::from_millis(1),
27640                max_backoff: Duration::from_millis(1),
27641            });
27642        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27643
27644        let error = worker
27645            .run_once()
27646            .await
27647            .expect_err("disabled retries must return the first transport failure");
27648        assert!(matches!(error, Error::Transport(_)));
27649        assert_eq!(
27650            server.request_count("/api/worker/workflow-tasks/poll"),
27651            1,
27652            "max_retries=0 must send only the initial request"
27653        );
27654    }
27655
27656    #[tokio::test]
27657    async fn worker_does_not_retry_authentication_failures() {
27658        let server = MockWorkerServer::unauthorized_polls();
27659        let client = Client::builder(server.base_url())
27660            .timeout(Duration::from_secs(2))
27661            .build()
27662            .expect("client");
27663        let mut worker = Worker::new(client, "rust-workers")
27664            .worker_id("unauthorized-worker")
27665            .recover_transient_outages(true)
27666            .poll_timeout(Duration::from_millis(10));
27667        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27668
27669        let error = worker
27670            .run()
27671            .await
27672            .expect_err("authentication must terminate");
27673        let Error::Http { status, body } = error else {
27674            panic!("expected stable HTTP authentication error");
27675        };
27676        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
27677        assert!(body.contains("authentication_failed"));
27678        assert_eq!(
27679            server.request_count("/api/worker/workflow-tasks/poll"),
27680            1,
27681            "authentication failures must not be retried"
27682        );
27683    }
27684
27685    #[derive(Clone, Debug)]
27686    struct CapturedRequest {
27687        headers: String,
27688        method: String,
27689        path: String,
27690        authorization: Option<String>,
27691        namespace: Option<String>,
27692        worker_protocol: Option<String>,
27693        control_protocol: Option<String>,
27694        body: String,
27695        received_at: Instant,
27696    }
27697
27698    struct MockWorkerServer {
27699        addr: SocketAddr,
27700        stop: Arc<AtomicBool>,
27701        requests: Arc<Mutex<Vec<CapturedRequest>>>,
27702        thread: Option<thread::JoinHandle<()>>,
27703    }
27704
27705    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
27706
27707    #[derive(Clone, Copy, Default)]
27708    struct MockWorkerBehavior {
27709        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
27710        request_override: Option<RequestOverride>,
27711        storage_refusals: usize,
27712        storage_path: Option<&'static str>,
27713        storage_unavailable: bool,
27714        storage_mid_poll: bool,
27715        storage_activity: bool,
27716        storage_query: bool,
27717        storage_wrong_poll_id: bool,
27718        reject_query_protocol: bool,
27719        reject_query_completion: bool,
27720        waiting_query_worker: bool,
27721        decline_registration: bool,
27722        complete_named_signal: bool,
27723        poll_failures_per_path: usize,
27724        long_poll_capacity_responses_per_path: usize,
27725        heartbeat_failures: usize,
27726        heartbeat_failure_request: Option<usize>,
27727        delayed_heartbeat_request: Option<usize>,
27728        heartbeat_response_delay: Duration,
27729        concurrent_requests: bool,
27730        unauthorized_polls: bool,
27731        reject_registration: bool,
27732        reject_registration_protocol: bool,
27733        reject_deregistration: bool,
27734        reject_deregistration_protocol: bool,
27735        cancelled_activity: bool,
27736        draining_polls: bool,
27737        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
27738        workflow_completion_status: Option<&'static str>,
27739        workflow_completion_body: Option<&'static str>,
27740    }
27741
27742    impl MockWorkerServer {
27743        fn start() -> Self {
27744            Self::start_with_behavior(MockWorkerBehavior::default())
27745        }
27746
27747        fn reject_query_protocol() -> Self {
27748            Self::start_with_behavior(MockWorkerBehavior {
27749                reject_query_protocol: true,
27750                ..MockWorkerBehavior::default()
27751            })
27752        }
27753
27754        fn reject_query_completion() -> Self {
27755            Self::start_with_behavior(MockWorkerBehavior {
27756                reject_query_completion: true,
27757                ..MockWorkerBehavior::default()
27758            })
27759        }
27760
27761        fn waiting_query_worker() -> Self {
27762            Self::start_with_behavior(MockWorkerBehavior {
27763                waiting_query_worker: true,
27764                complete_named_signal: true,
27765                ..MockWorkerBehavior::default()
27766            })
27767        }
27768
27769        fn transient_worker_failures() -> Self {
27770            Self::start_with_behavior(MockWorkerBehavior {
27771                poll_failures_per_path: 1,
27772                heartbeat_failures: 1,
27773                ..MockWorkerBehavior::default()
27774            })
27775        }
27776
27777        fn consecutive_poll_failures(count: usize) -> Self {
27778            Self::start_with_behavior(MockWorkerBehavior {
27779                poll_failures_per_path: count,
27780                ..MockWorkerBehavior::default()
27781            })
27782        }
27783
27784        fn capacity_limited_activity_poll() -> Self {
27785            Self::start_with_behavior(MockWorkerBehavior {
27786                long_poll_capacity_responses_per_path: 1,
27787                ..MockWorkerBehavior::default()
27788            })
27789        }
27790
27791        fn delayed_heartbeat_worker() -> Self {
27792            Self::start_with_behavior(MockWorkerBehavior {
27793                waiting_query_worker: true,
27794                delayed_heartbeat_request: Some(2),
27795                heartbeat_response_delay: Duration::from_millis(1_500),
27796                concurrent_requests: true,
27797                cancelled_activity: true,
27798                ..MockWorkerBehavior::default()
27799            })
27800        }
27801
27802        fn heartbeat_retry_worker() -> Self {
27803            Self::start_with_behavior(MockWorkerBehavior {
27804                waiting_query_worker: true,
27805                heartbeat_failure_request: Some(2),
27806                concurrent_requests: true,
27807                ..MockWorkerBehavior::default()
27808            })
27809        }
27810
27811        fn unavailable_polls() -> Self {
27812            Self::start_with_behavior(MockWorkerBehavior {
27813                poll_failures_per_path: usize::MAX,
27814                ..MockWorkerBehavior::default()
27815            })
27816        }
27817
27818        fn unauthorized_polls() -> Self {
27819            Self::start_with_behavior(MockWorkerBehavior {
27820                unauthorized_polls: true,
27821                ..MockWorkerBehavior::default()
27822            })
27823        }
27824
27825        fn rejected_registration() -> Self {
27826            Self::start_with_behavior(MockWorkerBehavior {
27827                reject_registration: true,
27828                ..MockWorkerBehavior::default()
27829            })
27830        }
27831
27832        fn rejected_registration_protocol() -> Self {
27833            Self::start_with_behavior(MockWorkerBehavior {
27834                reject_registration_protocol: true,
27835                ..MockWorkerBehavior::default()
27836            })
27837        }
27838
27839        fn declined_registration() -> Self {
27840            Self::start_with_behavior(MockWorkerBehavior {
27841                decline_registration: true,
27842                ..MockWorkerBehavior::default()
27843            })
27844        }
27845
27846        fn rejected_deregistration() -> Self {
27847            Self::start_with_behavior(MockWorkerBehavior {
27848                reject_deregistration: true,
27849                ..MockWorkerBehavior::default()
27850            })
27851        }
27852
27853        fn rejected_deregistration_protocol() -> Self {
27854            Self::start_with_behavior(MockWorkerBehavior {
27855                reject_deregistration_protocol: true,
27856                ..MockWorkerBehavior::default()
27857            })
27858        }
27859
27860        fn unauthorized_polls_and_rejected_deregistration() -> Self {
27861            Self::start_with_behavior(MockWorkerBehavior {
27862                unauthorized_polls: true,
27863                reject_deregistration: true,
27864                ..MockWorkerBehavior::default()
27865            })
27866        }
27867
27868        fn cancelled_activity() -> Self {
27869            Self::start_with_behavior(MockWorkerBehavior {
27870                cancelled_activity: true,
27871                ..MockWorkerBehavior::default()
27872            })
27873        }
27874
27875        fn draining_polls() -> Self {
27876            Self::start_with_behavior(MockWorkerBehavior {
27877                draining_polls: true,
27878                ..MockWorkerBehavior::default()
27879            })
27880        }
27881
27882        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
27883            Self::start_with_behavior(MockWorkerBehavior {
27884                invalid_task_payload_codec: Some(codec),
27885                ..MockWorkerBehavior::default()
27886            })
27887        }
27888
27889        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
27890            Self::start_with_behavior(MockWorkerBehavior {
27891                workflow_completion_status: Some(status),
27892                workflow_completion_body: Some(body),
27893                ..MockWorkerBehavior::default()
27894            })
27895        }
27896
27897        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
27898            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
27899            listener
27900                .set_nonblocking(true)
27901                .expect("configure mock listener");
27902            let addr = listener.local_addr().expect("mock server address");
27903            let stop = Arc::new(AtomicBool::new(false));
27904            let server_stop = Arc::clone(&stop);
27905            let requests = Arc::new(Mutex::new(Vec::new()));
27906            let server_requests = Arc::clone(&requests);
27907            let thread = thread::spawn(move || {
27908                let mut request_threads = Vec::new();
27909                while !server_stop.load(Ordering::SeqCst) {
27910                    match listener.accept() {
27911                        Ok((mut stream, _)) => {
27912                            if behavior.concurrent_requests {
27913                                let requests = Arc::clone(&server_requests);
27914                                request_threads.push(thread::spawn(move || {
27915                                    handle_mock_worker_request(&mut stream, &requests, behavior)
27916                                }));
27917                            } else {
27918                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
27919                            }
27920                        }
27921                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
27922                            let mut index = 0;
27923                            while index < request_threads.len() {
27924                                if request_threads[index].is_finished() {
27925                                    request_threads
27926                                        .swap_remove(index)
27927                                        .join()
27928                                        .expect("join mock request");
27929                                } else {
27930                                    index += 1;
27931                                }
27932                            }
27933                            thread::sleep(Duration::from_millis(5));
27934                        }
27935                        Err(_) => break,
27936                    }
27937                }
27938                for request_thread in request_threads {
27939                    request_thread.join().expect("join mock request");
27940                }
27941            });
27942
27943            Self {
27944                addr,
27945                stop,
27946                requests,
27947                thread: Some(thread),
27948            }
27949        }
27950
27951        fn base_url(&self) -> String {
27952            format!("http://{}", self.addr)
27953        }
27954
27955        fn worker_protocol_for(&self, path: &str) -> Option<String> {
27956            self.requests
27957                .lock()
27958                .expect("captured requests")
27959                .iter()
27960                .find(|request| request.path == path)
27961                .and_then(|request| request.worker_protocol.clone())
27962        }
27963
27964        fn control_protocol_for(&self, path: &str) -> Option<String> {
27965            self.requests
27966                .lock()
27967                .expect("captured requests")
27968                .iter()
27969                .find(|request| request.path == path)
27970                .and_then(|request| request.control_protocol.clone())
27971        }
27972
27973        fn method_for(&self, path: &str) -> Option<String> {
27974            self.requests
27975                .lock()
27976                .expect("captured requests")
27977                .iter()
27978                .find(|request| request.path == path)
27979                .map(|request| request.method.clone())
27980        }
27981
27982        fn authorization_for(&self, path: &str) -> Option<String> {
27983            self.requests
27984                .lock()
27985                .expect("captured requests")
27986                .iter()
27987                .find(|request| request.path == path)
27988                .and_then(|request| request.authorization.clone())
27989        }
27990
27991        fn namespace_for(&self, path: &str) -> Option<String> {
27992            self.requests
27993                .lock()
27994                .expect("captured requests")
27995                .iter()
27996                .find(|request| request.path == path)
27997                .and_then(|request| request.namespace.clone())
27998        }
27999
28000        fn request_count(&self, path: &str) -> usize {
28001            self.requests
28002                .lock()
28003                .expect("captured requests")
28004                .iter()
28005                .filter(|request| request.path == path)
28006                .count()
28007        }
28008
28009        fn captured_paths(&self) -> Vec<String> {
28010            self.requests
28011                .lock()
28012                .expect("captured requests")
28013                .iter()
28014                .map(|request| request.path.clone())
28015                .collect()
28016        }
28017
28018        fn request_times(&self, path: &str) -> Vec<Instant> {
28019            self.requests
28020                .lock()
28021                .expect("captured requests")
28022                .iter()
28023                .filter(|request| request.path == path)
28024                .map(|request| request.received_at)
28025                .collect()
28026        }
28027
28028        fn request_body(&self, path: &str) -> Value {
28029            let requests = self.requests.lock().expect("captured requests");
28030            let body = &requests
28031                .iter()
28032                .find(|request| request.path == path)
28033                .unwrap_or_else(|| panic!("missing request for {path}"))
28034                .body;
28035            serde_json::from_str(body).unwrap_or_else(|error| {
28036                panic!("invalid JSON request body for {path}: {error}: {body:?}")
28037            })
28038        }
28039
28040        fn request_bodies(&self, path: &str) -> Vec<Value> {
28041            self.requests
28042                .lock()
28043                .expect("captured requests")
28044                .iter()
28045                .filter(|request| request.path == path)
28046                .map(|request| {
28047                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
28048                        panic!(
28049                            "invalid JSON request body for {path}: {error}: {:?}",
28050                            request.body
28051                        )
28052                    })
28053                })
28054                .collect()
28055        }
28056    }
28057
28058    impl Drop for MockWorkerServer {
28059        fn drop(&mut self) {
28060            self.stop.store(true, Ordering::SeqCst);
28061            let _ = TcpStream::connect(self.addr);
28062
28063            if let Some(thread) = self.thread.take() {
28064                thread.join().expect("join mock server");
28065            }
28066        }
28067    }
28068
28069    fn handle_mock_worker_request(
28070        stream: &mut TcpStream,
28071        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
28072        behavior: MockWorkerBehavior,
28073    ) {
28074        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
28075        let mut buffer = [0_u8; 8192];
28076        let mut request = Vec::new();
28077
28078        loop {
28079            match stream.read(&mut buffer) {
28080                Ok(0) => break,
28081                Ok(read) => {
28082                    request.extend_from_slice(&buffer[..read]);
28083                    if mock_request_is_complete(&request) {
28084                        break;
28085                    }
28086                }
28087                Err(error)
28088                    if matches!(
28089                        error.kind(),
28090                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
28091                    ) =>
28092                {
28093                    break;
28094                }
28095                Err(_) => return,
28096            }
28097        }
28098
28099        let request = String::from_utf8_lossy(&request);
28100        let body = request
28101            .split_once("\r\n\r\n")
28102            .map(|(_, body)| body)
28103            .unwrap_or_default();
28104        let path = request
28105            .lines()
28106            .next()
28107            .and_then(|line| line.split_whitespace().nth(1))
28108            .unwrap_or_default();
28109        let method = request
28110            .lines()
28111            .next()
28112            .and_then(|line| line.split_whitespace().next())
28113            .unwrap_or_default();
28114        let authorization = request.lines().find_map(|line| {
28115            let (name, value) = line.split_once(':')?;
28116            name.eq_ignore_ascii_case("Authorization")
28117                .then(|| value.trim().to_string())
28118        });
28119        let namespace = request.lines().find_map(|line| {
28120            let (name, value) = line.split_once(':')?;
28121            name.eq_ignore_ascii_case("X-Namespace")
28122                .then(|| value.trim().to_string())
28123        });
28124        let worker_protocol = request.lines().find_map(|line| {
28125            let (name, value) = line.split_once(':')?;
28126            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
28127                .then(|| value.trim().to_string())
28128        });
28129        let control_protocol = request.lines().find_map(|line| {
28130            let (name, value) = line.split_once(':')?;
28131            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
28132                .then(|| value.trim().to_string())
28133        });
28134        let request_number = {
28135            let mut requests = requests.lock().expect("captured requests");
28136            requests.push(CapturedRequest {
28137                headers: request
28138                    .split_once("\r\n\r\n")
28139                    .map_or("", |(headers, _)| headers)
28140                    .to_owned(),
28141                method: method.to_string(),
28142                path: path.to_string(),
28143                authorization,
28144                namespace,
28145                worker_protocol: worker_protocol.clone(),
28146                control_protocol,
28147                body: body.to_string(),
28148                received_at: Instant::now(),
28149            });
28150            requests
28151                .iter()
28152                .filter(|request| request.path == path)
28153                .count()
28154        };
28155
28156        if let Some(response) = behavior
28157            .request_override
28158            .and_then(|handler| handler(path, body, request_number))
28159        {
28160            write_mock_response(stream, response.0, &response.1);
28161            return;
28162        }
28163        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
28164            write_mock_response(stream, response.0, &response.1);
28165            return;
28166        }
28167        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
28168            return;
28169        }
28170        let pressure_path = behavior
28171            .storage_path
28172            .is_some_and(|part| path.contains(part));
28173        let prior_failures = if path.ends_with("/poll") {
28174            behavior.poll_failures_per_path
28175        } else {
28176            0
28177        };
28178        if pressure_path
28179            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
28180        {
28181            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
28182            let poll_id = path
28183                .ends_with("/poll")
28184                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
28185            let mut refusal = storage_refusal(
28186                poll_id,
28187                behavior.storage_unavailable,
28188                behavior.storage_mid_poll,
28189            );
28190            if behavior.storage_wrong_poll_id {
28191                refusal["poll_request_id"] = json!("wrong-poll");
28192            }
28193            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
28194            return;
28195        }
28196        if path.contains("/storage-task/")
28197            || path.contains("/storage-activity/")
28198            || path.contains("/storage-query/")
28199        {
28200            write_mock_response(stream, "200 OK", "{}");
28201            return;
28202        }
28203        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
28204            write_mock_response(stream, "200 OK", &json!({"task":{
28205                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
28206                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
28207                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28208                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28209                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
28210            }}).to_string());
28211            return;
28212        }
28213        if behavior.storage_activity
28214            && path == "/api/worker/activity-tasks/poll"
28215            && request_number == 1
28216        {
28217            write_mock_response(stream, "200 OK", &json!({"task":{
28218                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
28219                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28220                "attempt_number":7, "lease_owner":"storage-worker"
28221            }}).to_string());
28222            return;
28223        }
28224
28225        if path == "/api/worker/register" {
28226            if behavior.reject_registration_protocol {
28227                write_mock_response(
28228                    stream,
28229                    "400 Bad Request",
28230                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
28231                );
28232                return;
28233            }
28234            if behavior.reject_registration {
28235                write_mock_response(
28236                    stream,
28237                    "503 Service Unavailable",
28238                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
28239                );
28240                return;
28241            }
28242        }
28243
28244        if path.starts_with("/api/worker/registrations/") {
28245            if behavior.reject_deregistration_protocol {
28246                write_mock_response(
28247                    stream,
28248                    "400 Bad Request",
28249                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.19"}"#,
28250                );
28251            } else if behavior.reject_deregistration {
28252                write_mock_response(
28253                    stream,
28254                    "403 Forbidden",
28255                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
28256                );
28257            } else {
28258                write_mock_response(
28259                    stream,
28260                    "200 OK",
28261                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
28262                );
28263            }
28264            return;
28265        }
28266
28267        let is_poll = matches!(
28268            path,
28269            "/api/worker/workflow-tasks/poll"
28270                | "/api/worker/activity-tasks/poll"
28271                | "/api/worker/query-tasks/poll"
28272        );
28273        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
28274            write_mock_response(
28275                stream,
28276                "429 Too Many Requests",
28277                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
28278            );
28279            return;
28280        }
28281        if is_poll && request_number <= behavior.poll_failures_per_path {
28282            return;
28283        }
28284        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
28285            return;
28286        }
28287        if path == "/api/worker/heartbeat"
28288            && behavior.heartbeat_failure_request == Some(request_number)
28289        {
28290            return;
28291        }
28292        if path == "/api/worker/heartbeat"
28293            && behavior.delayed_heartbeat_request == Some(request_number)
28294        {
28295            thread::sleep(behavior.heartbeat_response_delay);
28296        }
28297        if behavior.unauthorized_polls && is_poll {
28298            write_mock_response(
28299                stream,
28300                "401 Unauthorized",
28301                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
28302            );
28303            return;
28304        }
28305        if behavior.draining_polls && is_poll {
28306            write_mock_response(
28307                stream,
28308                "409 Conflict",
28309                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
28310            );
28311            return;
28312        }
28313
28314        if let Some(codec_case) = behavior.invalid_task_payload_codec {
28315            if is_poll && request_number == 1 {
28316                let mut task = match path {
28317                    "/api/worker/workflow-tasks/poll" => json!({
28318                        "task_id": "codec-workflow",
28319                        "workflow_type": "codec.workflow",
28320                        "payload_codec": DEFAULT_CODEC,
28321                        "workflow_task_attempt": 1,
28322                        "lease_owner": "codec-worker"
28323                    }),
28324                    "/api/worker/activity-tasks/poll" => json!({
28325                        "task_id": "codec-activity",
28326                        "activity_attempt_id": "codec-activity-attempt",
28327                        "activity_type": "codec.activity",
28328                        "payload_codec": DEFAULT_CODEC,
28329                        "attempt_number": 1,
28330                        "lease_owner": "codec-worker"
28331                    }),
28332                    "/api/worker/query-tasks/poll" => json!({
28333                        "query_task_id": "codec-query",
28334                        "query_task_attempt": 1,
28335                        "workflow_type": "codec.workflow",
28336                        "query_name": "known",
28337                        "payload_codec": DEFAULT_CODEC,
28338                        "lease_owner": "codec-worker"
28339                    }),
28340                    _ => unreachable!("is_poll limits task codec probe paths"),
28341                };
28342                codec_case.apply(&mut task);
28343                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
28344                return;
28345            }
28346
28347            if matches!(
28348                path,
28349                "/api/worker/workflow-tasks/codec-workflow/fail"
28350                    | "/api/worker/activity-tasks/codec-activity/fail"
28351                    | "/api/worker/query-tasks/codec-query/fail"
28352            ) {
28353                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
28354                return;
28355            }
28356        }
28357
28358        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
28359            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
28360            let body = format!(
28361                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
28362            );
28363            write_mock_response(stream, "400 Bad Request", &body);
28364            return;
28365        }
28366
28367        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
28368        {
28369            write_mock_response(
28370                stream,
28371                "409 Conflict",
28372                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
28373            );
28374            return;
28375        }
28376
28377        if behavior.workflow_completion_status.is_some()
28378            && path == "/api/worker/workflow-tasks/poll"
28379            && request_number == 1
28380        {
28381            write_mock_response(
28382                stream,
28383                "200 OK",
28384                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"}}"#,
28385            );
28386            return;
28387        }
28388
28389        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
28390            if let (Some(status), Some(body)) = (
28391                behavior.workflow_completion_status,
28392                behavior.workflow_completion_body,
28393            ) {
28394                write_mock_response(stream, status, body);
28395                return;
28396            }
28397        }
28398
28399        if behavior.waiting_query_worker {
28400            if behavior.complete_named_signal
28401                && path == "/api/worker/workflow-tasks/poll"
28402                && request_number == 1
28403            {
28404                let body = json!({
28405                    "task": {
28406                        "task_id": "snapshot-open",
28407                        "workflow_id": "snapshot-1",
28408                        "run_id": "snapshot-run-1",
28409                        "workflow_type": "snapshot",
28410                        "payload_codec": DEFAULT_CODEC,
28411                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28412                            .expect("Avro workflow arguments"),
28413                        "history_events": [],
28414                        "workflow_task_attempt": 1,
28415                        "lease_owner": "rust-snapshot-worker"
28416                    }
28417                })
28418                .to_string();
28419                write_mock_response(stream, "200 OK", &body);
28420                return;
28421            }
28422
28423            let signal_request = request_number - usize::from(behavior.complete_named_signal);
28424            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
28425            if path == "/api/worker/workflow-tasks/poll"
28426                && signal_request >= 1
28427                && signal_request <= signal_request_limit
28428            {
28429                let finish = behavior.complete_named_signal && signal_request == 3;
28430                let amounts = if signal_request == 1 {
28431                    vec![3]
28432                } else {
28433                    vec![3, 5]
28434                };
28435                let task_id = if signal_request == 1 {
28436                    "snapshot-wait-3"
28437                } else if finish {
28438                    "snapshot-finish"
28439                } else {
28440                    "snapshot-wait-5"
28441                };
28442                let mut history_events = std::iter::once(json!({
28443                    "event_type": "SignalWaitOpened",
28444                    "payload": {"sequence": 1, "signal_name": "finish"}
28445                }))
28446                .chain(amounts.iter().enumerate().map(|(index, amount)| {
28447                    json!({
28448                        "event_type": "SignalReceived",
28449                        "payload": {
28450                            "signal_id": format!("increment-{amount}"),
28451                            "signal_name": "increment",
28452                            "workflow_sequence": index + 2,
28453                            "payload_codec": DEFAULT_CODEC,
28454                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28455                                .expect("Avro signal envelope")
28456                        }
28457                    })
28458                }))
28459                .collect::<Vec<_>>();
28460                let (resume_id, resume_name, resume_arguments) = if finish {
28461                    history_events.push(json!({
28462                        "event_type": "SignalReceived",
28463                        "payload": {
28464                            "signal_id": "finish",
28465                            "signal_name": "finish",
28466                            "workflow_sequence": 4,
28467                            "payload_codec": DEFAULT_CODEC,
28468                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28469                                .expect("Avro finish signal envelope")
28470                        }
28471                    }));
28472                    (
28473                        "finish".to_string(),
28474                        "finish".to_string(),
28475                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
28476                            .expect("Avro finish resume signal"),
28477                    )
28478                } else {
28479                    let amount = amounts.last().expect("amount");
28480                    (
28481                        format!("increment-{amount}"),
28482                        "increment".to_string(),
28483                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28484                            .expect("Avro increment resume signal"),
28485                    )
28486                };
28487                let body = json!({
28488                    "task": {
28489                        "task_id": task_id,
28490                        "workflow_id": "snapshot-1",
28491                        "run_id": "snapshot-run-1",
28492                        "workflow_type": "snapshot",
28493                        "payload_codec": DEFAULT_CODEC,
28494                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28495                            .expect("Avro workflow arguments"),
28496                        "history_events": history_events,
28497                        "workflow_task_attempt": 1,
28498                        "workflow_signal_id": resume_id,
28499                        "signal_name": resume_name,
28500                        "signal_arguments": resume_arguments,
28501                        "lease_owner": "rust-snapshot-worker"
28502                    }
28503                })
28504                .to_string();
28505                write_mock_response(stream, "200 OK", &body);
28506                return;
28507            }
28508
28509            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
28510                let history_events = [3, 5]
28511                    .into_iter()
28512                    .enumerate()
28513                    .map(|(index, amount)| {
28514                        json!({
28515                            "event_type": "SignalReceived",
28516                            "payload": {
28517                                "signal_id": format!("increment-{amount}"),
28518                                "signal_name": "increment",
28519                                "workflow_sequence": index + 2,
28520                                "payload_codec": DEFAULT_CODEC,
28521                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28522                                    .expect("Avro query signal envelope")
28523                            }
28524                        })
28525                    })
28526                    .collect::<Vec<_>>();
28527                let body = json!({
28528                    "task": {
28529                        "query_task_id": "snapshot-current",
28530                        "query_task_attempt": 1,
28531                        "lease_owner": "rust-snapshot-worker",
28532                        "workflow_id": "snapshot-1",
28533                        "run_id": "snapshot-run-1",
28534                        "workflow_type": "snapshot",
28535                        "query_name": "current",
28536                        "payload_codec": DEFAULT_CODEC,
28537                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28538                            .expect("Avro workflow arguments"),
28539                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28540                            .expect("Avro query arguments"),
28541                        "history_events": history_events,
28542                        "run_status": "waiting"
28543                    }
28544                })
28545                .to_string();
28546                write_mock_response(stream, "200 OK", &body);
28547                return;
28548            }
28549
28550            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
28551                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
28552            {
28553                write_mock_response(
28554                    stream,
28555                    "200 OK",
28556                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
28557                );
28558                return;
28559            }
28560
28561            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
28562                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
28563                return;
28564            }
28565
28566            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
28567                write_mock_response(
28568                    stream,
28569                    "200 OK",
28570                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
28571                );
28572                return;
28573            }
28574
28575            if path == "/api/worker/query-tasks/snapshot-current/complete" {
28576                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
28577                return;
28578            }
28579        }
28580
28581        if matches!(
28582            path,
28583            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
28584        ) {
28585            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
28586                .expect("typed mock result");
28587            let body = json!({
28588                "result": typed_fidelity_probe().into_json().expect("result projection"),
28589                "result_envelope": result,
28590            })
28591            .to_string();
28592            write_mock_response(stream, "200 OK", &body);
28593            return;
28594        }
28595
28596        if path == "/api/workflows/typed-1" {
28597            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
28598                .expect("typed mock result");
28599            let body = json!({
28600                "workflow_id": "typed-1",
28601                "run_id": "run-typed-1",
28602                "workflow_type": "typed.echo",
28603                "status": "completed",
28604                "output": typed_fidelity_probe().into_json().expect("output projection"),
28605                "output_envelope": result,
28606            })
28607            .to_string();
28608            write_mock_response(stream, "200 OK", &body);
28609            return;
28610        }
28611
28612        let (status, body) = match path {
28613            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
28614            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
28615            "/api/workflows" => (
28616                "201 Created",
28617                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
28618            ),
28619            "/api/worker/register" if behavior.decline_registration => (
28620                "200 OK",
28621                r#"{"worker_id":"declined-worker","registered":false}"#,
28622            ),
28623            "/api/worker/register" if behavior.waiting_query_worker => (
28624                "200 OK",
28625                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
28626            ),
28627            "/api/worker/register" => (
28628                "200 OK",
28629                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
28630            ),
28631            "/api/worker/heartbeat" => ("200 OK", "{}"),
28632            "/api/worker/activity-tasks/poll"
28633                if behavior.cancelled_activity && request_number == 1 =>
28634            {
28635                (
28636                    "200 OK",
28637                    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"}}"#,
28638                )
28639            }
28640            "/api/worker/activity-tasks/poll"
28641                if behavior.long_poll_capacity_responses_per_path > 0
28642                    && request_number
28643                        == behavior
28644                            .long_poll_capacity_responses_per_path
28645                            .saturating_add(1) =>
28646            {
28647                (
28648                    "200 OK",
28649                    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"}}"#,
28650                )
28651            }
28652            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
28653                ("200 OK", r#"{"task":null}"#)
28654            }
28655            "/api/worker/query-tasks/poll"
28656                if behavior.reject_query_completion && request_number == 1 =>
28657            {
28658                (
28659                    "200 OK",
28660                    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"}}"#,
28661                )
28662            }
28663            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
28664            "/api/worker/query-tasks/query-capture/complete"
28665            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
28666            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
28667                "200 OK",
28668                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
28669            ),
28670            "/api/worker/activity-tasks/activity-cancel/complete" => (
28671                "409 Conflict",
28672                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
28673            ),
28674            "/api/worker/activity-tasks/activity-typed/complete"
28675            | "/api/worker/activity-tasks/activity-typed/fail"
28676            | "/api/worker/activity-tasks/capacity-activity/complete"
28677            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
28678            "/api/workflows/counter-1/query/current" => (
28679                "200 OK",
28680                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
28681            ),
28682            "/api/workflows/counter-1/query/missing" => (
28683                "404 Not Found",
28684                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
28685            ),
28686            "/api/workflows/wf-lifecycle/cancel" => (
28687                "200 OK",
28688                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
28689            ),
28690            "/api/workflows/wf-lifecycle/terminate" => (
28691                "200 OK",
28692                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
28693            ),
28694            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
28695                "200 OK",
28696                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
28697            ),
28698            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
28699                "200 OK",
28700                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
28701            ),
28702            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
28703                "202 Accepted",
28704                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
28705            ),
28706            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
28707                "200 OK",
28708                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}"#,
28709            ),
28710            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
28711                "409 Conflict",
28712                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
28713            ),
28714            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
28715            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
28716                "409 Conflict",
28717                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
28718            ),
28719            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
28720                "200 OK",
28721                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"}]}}"#,
28722            ),
28723            "/api/workflows/wf-cancelled" => (
28724                "200 OK",
28725                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
28726            ),
28727            "/api/workflows/wf-terminated" => (
28728                "200 OK",
28729                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
28730            ),
28731            "/api/workflows/wf-timed-out" => (
28732                "200 OK",
28733                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
28734            ),
28735            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
28736                "200 OK",
28737                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
28738            ),
28739            "/api/workflows/wf-selected" => (
28740                "200 OK",
28741                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
28742            ),
28743            "/api/workflows/wf-selected/runs/run-selected" => (
28744                "200 OK",
28745                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
28746            ),
28747            _ => ("404 Not Found", r#"{"message":"not found"}"#),
28748        };
28749        write_mock_response(stream, status, body);
28750    }
28751
28752    fn mock_request_is_complete(request: &[u8]) -> bool {
28753        let Some(header_end) = request
28754            .windows(4)
28755            .position(|window| window == b"\r\n\r\n")
28756            .map(|position| position + 4)
28757        else {
28758            return false;
28759        };
28760        let headers = String::from_utf8_lossy(&request[..header_end]);
28761        let content_length = headers.lines().find_map(|line| {
28762            let (name, value) = line.split_once(':')?;
28763            name.eq_ignore_ascii_case("content-length")
28764                .then(|| value.trim().parse::<usize>().ok())
28765                .flatten()
28766        });
28767
28768        request.len() >= header_end + content_length.unwrap_or(0)
28769    }
28770
28771    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
28772        let response = format!(
28773            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
28774            body.len()
28775        );
28776
28777        let _ = stream.write_all(response.as_bytes());
28778        let _ = stream.flush();
28779    }
28780
28781    fn activity_completion_backend_recovery(
28782        path: &str,
28783        _body: &str,
28784        request_number: usize,
28785    ) -> Option<(&'static str, String)> {
28786        match path {
28787            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
28788                "200 OK",
28789                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(),
28790            )),
28791            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
28792                "503 Service Unavailable",
28793                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(),
28794            )),
28795            "/api/worker/activity-tasks/recover-activity/complete" => Some((
28796                "200 OK",
28797                r#"{"outcome":"completed","recorded":true}"#.to_string(),
28798            )),
28799            _ => None,
28800        }
28801    }
28802
28803    fn workflow_completion_backend_recovery(
28804        path: &str,
28805        _body: &str,
28806        request_number: usize,
28807    ) -> Option<(&'static str, String)> {
28808        match path {
28809            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
28810                "200 OK",
28811                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
28812            )),
28813            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
28814                "503 Service Unavailable",
28815                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(),
28816            )),
28817            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
28818                "200 OK",
28819                r#"{"outcome":"completed","recorded":true}"#.to_string(),
28820            )),
28821            _ => None,
28822        }
28823    }
28824
28825    fn activity_completion_stale_after_backend_recovery(
28826        path: &str,
28827        body: &str,
28828        request_number: usize,
28829    ) -> Option<(&'static str, String)> {
28830        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
28831            return Some((
28832                "409 Conflict",
28833                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(),
28834            ));
28835        }
28836        activity_completion_backend_recovery(path, body, request_number)
28837    }
28838
28839    fn activity_completion_remains_unavailable(
28840        path: &str,
28841        body: &str,
28842        request_number: usize,
28843    ) -> Option<(&'static str, String)> {
28844        if path == "/api/worker/activity-tasks/recover-activity/complete" {
28845            return activity_completion_backend_recovery(path, body, 1);
28846        }
28847        activity_completion_backend_recovery(path, body, request_number)
28848    }
28849
28850    #[tokio::test]
28851    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
28852        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28853            request_override: Some(activity_completion_backend_recovery),
28854            ..MockWorkerBehavior::default()
28855        });
28856        let client = Client::builder(server.base_url())
28857            .timeout(Duration::from_secs(2))
28858            .build()
28859            .expect("client");
28860        let handler_calls = Arc::new(AtomicUsize::new(0));
28861        let mut worker = Worker::new(client, "recover-queue")
28862            .worker_id("recover-worker")
28863            .poll_timeout(Duration::from_millis(10));
28864        worker.register_activity("recover.activity", {
28865            let handler_calls = Arc::clone(&handler_calls);
28866            move |_ctx, _args| {
28867                let handler_calls = Arc::clone(&handler_calls);
28868                async move {
28869                    handler_calls.fetch_add(1, Ordering::SeqCst);
28870                    Ok(json!("done"))
28871                }
28872            }
28873        });
28874
28875        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
28876        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
28877        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
28878        assert_eq!(bodies.len(), 2);
28879        assert_eq!(bodies[0], bodies[1]);
28880    }
28881
28882    #[tokio::test]
28883    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
28884        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28885            request_override: Some(workflow_completion_backend_recovery),
28886            ..MockWorkerBehavior::default()
28887        });
28888        let client = Client::builder(server.base_url())
28889            .timeout(Duration::from_secs(2))
28890            .build()
28891            .expect("client");
28892        let handler_calls = Arc::new(AtomicUsize::new(0));
28893        let mut worker = Worker::new(client, "recover-queue")
28894            .worker_id("recover-worker")
28895            .poll_timeout(Duration::from_millis(10));
28896        worker.register_workflow("recover.workflow", {
28897            let handler_calls = Arc::clone(&handler_calls);
28898            move |_ctx, _args| {
28899                let handler_calls = Arc::clone(&handler_calls);
28900                async move {
28901                    handler_calls.fetch_add(1, Ordering::SeqCst);
28902                    Ok(json!("done"))
28903                }
28904            }
28905        });
28906
28907        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
28908        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
28909        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
28910        assert_eq!(bodies.len(), 2);
28911        assert_eq!(bodies[0], bodies[1]);
28912    }
28913
28914    #[tokio::test]
28915    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
28916        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28917            request_override: Some(activity_completion_stale_after_backend_recovery),
28918            ..MockWorkerBehavior::default()
28919        });
28920        let client = Client::builder(server.base_url())
28921            .timeout(Duration::from_secs(2))
28922            .build()
28923            .expect("client");
28924        let handler_calls = Arc::new(AtomicUsize::new(0));
28925        let mut worker = Worker::new(client, "recover-queue")
28926            .worker_id("recover-worker")
28927            .poll_timeout(Duration::from_millis(10));
28928        worker.register_activity("recover.activity", {
28929            let handler_calls = Arc::clone(&handler_calls);
28930            move |_ctx, _args| {
28931                let handler_calls = Arc::clone(&handler_calls);
28932                async move {
28933                    handler_calls.fetch_add(1, Ordering::SeqCst);
28934                    Ok(json!("done"))
28935                }
28936            }
28937        });
28938
28939        assert_eq!(
28940            worker
28941                .run_once()
28942                .await
28943                .expect("authoritative stale outcome"),
28944            1
28945        );
28946        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
28947        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
28948        assert_eq!(bodies.len(), 2);
28949        assert_eq!(bodies[0], bodies[1]);
28950    }
28951
28952    #[test]
28953    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
28954        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
28955        let response = json!({
28956            "reason":"backend_unavailable", "operation":"complete_activity_task",
28957            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
28958            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
28959            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
28960        });
28961        let path = "/worker/activity-tasks/recover-activity/complete";
28962        let error = |body: Value| Error::Http {
28963            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28964            body: body.to_string(),
28965        };
28966        assert_eq!(
28967            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
28968            Some(Duration::from_secs(1))
28969        );
28970
28971        for (field, invalid) in [
28972            ("operation", json!("poll_activity_task")),
28973            ("outcome", json!("rejected")),
28974            ("worker_id", json!("another-worker")),
28975            ("task_queue", json!("recover-queue")),
28976            ("retryable", json!(false)),
28977            ("retry_after_seconds", json!(0)),
28978            ("task_id", json!("another-task")),
28979            ("lease_owner", json!("another-worker")),
28980            ("activity_attempt_id", json!("another-attempt")),
28981        ] {
28982            let mut invalid_response = response.clone();
28983            invalid_response[field] = invalid;
28984            assert_eq!(
28985                worker_fenced_completion_retry_after(
28986                    &error(invalid_response),
28987                    path,
28988                    Some(&request)
28989                ),
28990                None,
28991                "must not retry mismatched {field}"
28992            );
28993        }
28994        assert_eq!(
28995            worker_fenced_completion_retry_after(&error(response), path, None),
28996            None
28997        );
28998    }
28999
29000    #[tokio::test]
29001    async fn shutdown_interrupts_fenced_completion_backend_wait() {
29002        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29003            request_override: Some(activity_completion_remains_unavailable),
29004            ..MockWorkerBehavior::default()
29005        });
29006        let client = Client::builder(server.base_url())
29007            .timeout(Duration::from_secs(2))
29008            .build()
29009            .expect("client");
29010        let stop = Arc::new(AtomicBool::new(false));
29011        let worker = Worker::new(client, "recover-queue")
29012            .worker_id("recover-worker")
29013            .with_storage_admission(Arc::clone(&stop));
29014        let completion = tokio::spawn(async move {
29015            worker
29016                .client
29017                .complete_activity_task(
29018                    "recover-activity",
29019                    "recover-attempt",
29020                    "recover-worker",
29021                    json!("done"),
29022                    DEFAULT_CODEC,
29023                )
29024                .await
29025        });
29026        let path = "/api/worker/activity-tasks/recover-activity/complete";
29027        tokio::time::timeout(Duration::from_secs(2), async {
29028            while server.request_count(path) == 0 {
29029                tokio::time::sleep(Duration::from_millis(10)).await;
29030            }
29031        })
29032        .await
29033        .expect("first completion request");
29034        stop.store(true, Ordering::SeqCst);
29035        let error = tokio::time::timeout(Duration::from_secs(1), completion)
29036            .await
29037            .expect("shutdown must interrupt retry wait")
29038            .expect("completion task")
29039            .expect_err("backend is still unavailable");
29040        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
29041        assert_eq!(server.request_count(path), 1);
29042    }
29043}