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
6286fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6287    names
6288        .iter()
6289        .map(|name| {
6290            json!({
6291                "name": name,
6292                "parameters": [{
6293                    "name": "args",
6294                    "position": 0,
6295                    "required": false,
6296                    "variadic": true,
6297                    "type": null,
6298                    "allows_null": true,
6299                    "default_available": false,
6300                    "default": null,
6301                }],
6302            })
6303        })
6304        .collect()
6305}
6306
6307#[derive(Debug)]
6308struct WorkflowTaskDecision {
6309    commands: Vec<Value>,
6310    message_stream_cursors: Vec<Value>,
6311    message_stream_waits: Vec<Value>,
6312    cancellation_delivery: Option<CancellationDelivery>,
6313    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6314    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6315}
6316
6317enum PreparedWorkflowTask {
6318    Decision(WorkflowTaskDecision),
6319    Execution {
6320        task: WorkflowTask,
6321        context: WorkflowContext,
6322        future: WorkflowFuture,
6323    },
6324}
6325
6326impl WorkflowTaskDecision {
6327    fn without_message_streams(commands: Vec<Value>) -> Self {
6328        Self {
6329            commands,
6330            message_stream_cursors: Vec::new(),
6331            message_stream_waits: Vec::new(),
6332            cancellation_delivery: None,
6333            cancellation_scope_opening: None,
6334            cancellation_scope_delivery: None,
6335        }
6336    }
6337}
6338
6339#[derive(Clone)]
6340enum RegisteredQuery {
6341    Snapshot(QueryHandler),
6342    Replayed {
6343        state_type: TypeId,
6344        handler: ReplayedQueryHandler,
6345    },
6346}
6347
6348#[derive(Clone, Debug)]
6349pub struct WorkerHeartbeatObservation {
6350    pub worker_id: String,
6351    pub task_queue: String,
6352    pub acknowledged_at_unix_millis: u64,
6353    pub acknowledgement: Value,
6354}
6355
6356/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6357///
6358/// Expected empty long polls and explicit Server capacity backpressure are
6359/// normal worker states. Capacity backpressure honors the advertised retry
6360/// delay without consuming this retry budget. Other transport failures,
6361/// retryable HTTP 408/429 responses, and server errors are retried with capped
6362/// exponential backoff. Authentication, protocol, codec, and handler failures
6363/// are never retried by the worker.
6364/// Explicit storage admission pauses also preserve the already-serialized worker
6365/// request without consuming this budget or rerunning its handler. The delay is
6366/// capped by `max_backoff`, and shutdown interrupts storage waits.
6367/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6368/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6369/// and `max_retries = 0` disables ordinary retries in either mode.
6370#[derive(Clone, Copy, Debug)]
6371pub struct WorkerRetryPolicy {
6372    /// Number of retries after the initial request fails.
6373    pub max_retries: usize,
6374    /// Delay before the first retry.
6375    pub initial_backoff: Duration,
6376    /// Maximum delay between retries.
6377    pub max_backoff: Duration,
6378}
6379
6380impl Default for WorkerRetryPolicy {
6381    fn default() -> Self {
6382        Self {
6383            max_retries: 5,
6384            initial_backoff: Duration::from_millis(100),
6385            max_backoff: Duration::from_secs(5),
6386        }
6387    }
6388}
6389
6390#[derive(Clone, Debug)]
6391struct WorkerStorageAdmission {
6392    policy: WorkerRetryPolicy,
6393    stop: Arc<AtomicBool>,
6394}
6395
6396struct StopWorkerOnDrop(Arc<AtomicBool>);
6397
6398impl Drop for StopWorkerOnDrop {
6399    fn drop(&mut self) {
6400        self.0.store(true, Ordering::SeqCst);
6401    }
6402}
6403
6404async fn wait_for_worker_stop(stop: &AtomicBool) {
6405    while !stop.load(Ordering::SeqCst) {
6406        tokio::time::sleep(Duration::from_millis(100)).await;
6407    }
6408}
6409
6410#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6411enum ManagedPollOutcome {
6412    Idle,
6413    Handled,
6414    Stop,
6415}
6416
6417#[derive(Clone)]
6418pub struct Worker {
6419    client: Client,
6420    worker_id: String,
6421    task_queue: String,
6422    workflows: HashMap<String, RegisteredWorkflow>,
6423    activities: HashMap<String, ActivityHandler>,
6424    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6425    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6426    max_concurrent_workflow_tasks: usize,
6427    max_concurrent_activity_tasks: usize,
6428    poll_timeout: Duration,
6429    heartbeat_interval: Duration,
6430    retry_policy: WorkerRetryPolicy,
6431    recover_transient_outages: bool,
6432    run_stop: Option<Arc<AtomicBool>>,
6433    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6434    cooperative_cancellation_enabled: bool,
6435    allow_cancellation_scope_authoring: bool,
6436    allow_cancellation_scope_delivery: bool,
6437    cooperative_registration_confirmed: Arc<AtomicBool>,
6438    local_registration_confirmed: Arc<AtomicBool>,
6439    session_registration_confirmed: Arc<AtomicBool>,
6440    resource_capabilities: Vec<String>,
6441    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6442}
6443
6444impl Worker {
6445    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6446        Self {
6447            client,
6448            worker_id: default_worker_id(),
6449            task_queue: task_queue.into(),
6450            workflows: HashMap::new(),
6451            activities: HashMap::new(),
6452            queries: HashMap::new(),
6453            updates: HashMap::new(),
6454            max_concurrent_workflow_tasks: 10,
6455            max_concurrent_activity_tasks: 10,
6456            poll_timeout: Duration::from_secs(30),
6457            heartbeat_interval: Duration::from_secs(60),
6458            retry_policy: WorkerRetryPolicy::default(),
6459            recover_transient_outages: false,
6460            run_stop: None,
6461            heartbeat_observer: None,
6462            cooperative_cancellation_enabled: false,
6463            allow_cancellation_scope_authoring: false,
6464            allow_cancellation_scope_delivery: false,
6465            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6466            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6467            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6468            resource_capabilities: Vec::new(),
6469            sessions: Arc::new(Mutex::new(HashMap::new())),
6470        }
6471    }
6472
6473    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6474        self.worker_id = worker_id.into();
6475        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6476        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6477        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6478        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6479        self
6480    }
6481
6482    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6483        self.poll_timeout = timeout;
6484        self
6485    }
6486
6487    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6488        self.heartbeat_interval = interval;
6489        self
6490    }
6491
6492    /// Explicitly enable inline local activities in this workflow worker.
6493    ///
6494    /// The worker advertises the capability to Server only when enabled.
6495    /// These callbacks must yield to Tokio and have idempotent side effects.
6496    /// Cooperative prepared local supervision is a separate capability.
6497    pub fn local_activities(mut self, enabled: bool) -> Self {
6498        self.client.local_activities_enabled = enabled;
6499        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6500        self
6501    }
6502
6503    /// Opt in to separate cooperative workflow cancellation requests.
6504    ///
6505    /// Registration requires the Server to acknowledge this exact worker,
6506    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6507    /// processing uses canonical delivery and activity ownership fences.
6508    /// Existing terminal cancel and terminate operations remain terminal.
6509    /// The default is disabled, preserving ordinary protocol 1.19 workers.
6510    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6511    /// and [`Worker::run_until`] register automatically.
6512    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6513        self.cooperative_cancellation_enabled = enabled;
6514        self.client.cooperative_worker_protocol = enabled;
6515        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6516        self
6517    }
6518
6519    /// Enable candidate scope authoring without advertising scoped execution.
6520    #[doc(hidden)]
6521    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6522        self.allow_cancellation_scope_authoring = enabled;
6523        self
6524    }
6525
6526    /// Enable the candidate scoped call consumer with canonical authoring.
6527    #[doc(hidden)]
6528    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6529        self.allow_cancellation_scope_delivery = enabled;
6530        self
6531    }
6532
6533    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6534    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6535        self.retry_policy = policy;
6536        self
6537    }
6538
6539    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6540    ///
6541    /// Retries preserve the poll request identity and use capped exponential
6542    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6543    /// An in-flight poll is allowed to finish so leased work is not discarded.
6544    /// Authentication, protocol, codec, handler and task settlement failures
6545    /// remain errors. Registration and deregistration are not retried here.
6546    ///
6547    /// The default is disabled, preserving the bounded retry contract.
6548    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6549    /// even when this option is enabled.
6550    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6551        self.recover_transient_outages = enabled;
6552        self
6553    }
6554
6555    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6556    where
6557        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6558    {
6559        self.heartbeat_observer = Some(Arc::new(observer));
6560        self
6561    }
6562
6563    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6564        self.max_concurrent_workflow_tasks = count.max(1);
6565        self
6566    }
6567
6568    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6569        self.max_concurrent_activity_tasks = count.max(1);
6570        self
6571    }
6572
6573    /// Register a workflow handler.
6574    ///
6575    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6576    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6577    /// while acquiring or decoding a worker task remain worker-operation
6578    /// failures and do not get converted into workflow outcomes.
6579    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6580    where
6581        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6582        Fut: Future<Output = Result<Value>> + Send + 'static,
6583    {
6584        let handler = Arc::new(handler);
6585        self.workflows.insert(
6586            workflow_type.into(),
6587            RegisteredWorkflow {
6588                execute: Arc::new(move |ctx, input| {
6589                    let handler = Arc::clone(&handler);
6590                    Box::pin(async move {
6591                        let result = handler(ctx, input.into_json()?).await?;
6592                        AvroValue::from_serialize(&result)
6593                    })
6594                }),
6595                replay: None,
6596                state_type: None,
6597                definition_fingerprint: None,
6598            },
6599        );
6600    }
6601
6602    /// Register a workflow with one Serde request value and a Serde result.
6603    ///
6604    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
6605    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
6606    /// workflow-specific schema. A task must contain zero arguments for a unit
6607    /// request or exactly one argument for every other request type.
6608    ///
6609    /// See the runnable
6610    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
6611    /// for typed workflow and activity contracts with retry and timeout policy.
6612    pub fn register_typed_workflow<I, O, F, Fut>(
6613        &mut self,
6614        workflow_type: impl Into<String>,
6615        handler: F,
6616    ) where
6617        I: DeserializeOwned + Send + 'static,
6618        O: Serialize + Send + 'static,
6619        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
6620        Fut: Future<Output = Result<O>> + Send + 'static,
6621    {
6622        let workflow_type = workflow_type.into();
6623        let handler_name = workflow_type.clone();
6624        let handler = Arc::new(handler);
6625        self.workflows.insert(
6626            workflow_type,
6627            RegisteredWorkflow {
6628                execute: Arc::new(move |ctx, input| {
6629                    let handler = Arc::clone(&handler);
6630                    let handler_name = handler_name.clone();
6631                    Box::pin(async move {
6632                        let input =
6633                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6634                        let result = handler(ctx, input).await?;
6635                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6636                    })
6637                }),
6638                replay: None,
6639                state_type: None,
6640                definition_fingerprint: None,
6641            },
6642        );
6643    }
6644
6645    /// Register a workflow on the lossless fixed Avro Value surface.
6646    pub fn register_workflow_avro_value<F, Fut>(
6647        &mut self,
6648        workflow_type: impl Into<String>,
6649        handler: F,
6650    ) where
6651        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
6652        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6653    {
6654        self.workflows.insert(
6655            workflow_type.into(),
6656            RegisteredWorkflow {
6657                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
6658                replay: None,
6659                state_type: None,
6660                definition_fingerprint: None,
6661            },
6662        );
6663    }
6664
6665    /// Register a workflow whose typed instance state can be reconstructed for queries.
6666    ///
6667    /// `state_factory` creates a fresh instance for every normal workflow task and
6668    /// query replay. The workflow handler is the single source of truth for state
6669    /// transitions: it updates [`WorkflowInstance`] after activities and signals
6670    /// resolve. Query replay runs this same handler over committed history and
6671    /// discards any commands it would emit.
6672    pub fn register_replayed_workflow<S, Factory, F, Fut>(
6673        &mut self,
6674        workflow_type: impl Into<String>,
6675        state_factory: Factory,
6676        handler: F,
6677    ) where
6678        S: Clone + Send + Sync + 'static,
6679        Factory: Fn() -> S + Send + Sync + 'static,
6680        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6681        Fut: Future<Output = Result<Value>> + Send + 'static,
6682    {
6683        let state_factory = Arc::new(state_factory);
6684        let handler = Arc::new(handler);
6685
6686        let execute_factory = Arc::clone(&state_factory);
6687        let execute_handler = Arc::clone(&handler);
6688        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6689            let state = WorkflowInstance::new(execute_factory());
6690            let handler = Arc::clone(&execute_handler);
6691            Box::pin(async move {
6692                let result = handler(ctx, input.into_json()?, state).await?;
6693                AvroValue::from_serialize(&result)
6694            }) as WorkflowFuture
6695        });
6696
6697        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6698            let state = WorkflowInstance::new(state_factory());
6699            let snapshot_state = state.clone();
6700            let snapshot: WorkflowStateSnapshot =
6701                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6702            let replay_handler = Arc::clone(&handler);
6703            let future = async move {
6704                let result = replay_handler(ctx, input.into_json()?, state).await?;
6705                AvroValue::from_serialize(&result)
6706            };
6707            ReplayedWorkflowInvocation {
6708                future: Box::pin(future),
6709                snapshot,
6710            }
6711        });
6712
6713        self.workflows.insert(
6714            workflow_type.into(),
6715            RegisteredWorkflow {
6716                execute,
6717                replay: Some(replay),
6718                state_type: Some(TypeId::of::<S>()),
6719                definition_fingerprint: None,
6720            },
6721        );
6722    }
6723
6724    /// Register a replayable workflow with one Serde request value and result.
6725    ///
6726    /// Normal task execution and instance-state query replay both decode and
6727    /// encode through the fixed Avro Value codec. The state factory and handler
6728    /// otherwise follow [`Worker::register_replayed_workflow`].
6729    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
6730        &mut self,
6731        workflow_type: impl Into<String>,
6732        state_factory: Factory,
6733        handler: F,
6734    ) where
6735        I: DeserializeOwned + Send + 'static,
6736        O: Serialize + Send + 'static,
6737        S: Clone + Send + Sync + 'static,
6738        Factory: Fn() -> S + Send + Sync + 'static,
6739        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6740        Fut: Future<Output = Result<O>> + Send + 'static,
6741    {
6742        let workflow_type = workflow_type.into();
6743        let state_factory = Arc::new(state_factory);
6744        let handler = Arc::new(handler);
6745
6746        let execute_name = workflow_type.clone();
6747        let execute_factory = Arc::clone(&state_factory);
6748        let execute_handler = Arc::clone(&handler);
6749        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6750            let state = WorkflowInstance::new(execute_factory());
6751            let handler = Arc::clone(&execute_handler);
6752            let handler_name = execute_name.clone();
6753            Box::pin(async move {
6754                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6755                let result = handler(ctx, input, state).await?;
6756                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6757            }) as WorkflowFuture
6758        });
6759
6760        let replay_name = workflow_type.clone();
6761        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6762            let state = WorkflowInstance::new(state_factory());
6763            let snapshot_state = state.clone();
6764            let snapshot: WorkflowStateSnapshot =
6765                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6766            let handler = Arc::clone(&handler);
6767            let handler_name = replay_name.clone();
6768            let future = async move {
6769                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6770                let result = handler(ctx, input, state).await?;
6771                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6772            };
6773            ReplayedWorkflowInvocation {
6774                future: Box::pin(future),
6775                snapshot,
6776            }
6777        });
6778
6779        self.workflows.insert(
6780            workflow_type,
6781            RegisteredWorkflow {
6782                execute,
6783                replay: Some(replay),
6784                state_type: Some(TypeId::of::<S>()),
6785                definition_fingerprint: None,
6786            },
6787        );
6788    }
6789
6790    /// Bind a registered workflow to compile-time embedded source for safe redrive.
6791    ///
6792    /// Supply `include_str!` values for the workflow body and every helper whose
6793    /// behavior can affect replay. A handler re-registration clears the local
6794    /// identity; call this after registering the final handler. The server
6795    /// rejects reusing a worker ID when its prior fingerprint disappears.
6796    /// Workflows without source identity remain runnable but cannot be safely redriven.
6797    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
6798    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
6799    pub fn set_workflow_definition_sources(
6800        &mut self,
6801        workflow_type: &str,
6802        sources: &[&str],
6803    ) -> Result<()> {
6804        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
6805            return Err(Error::Codec(
6806                "workflow definition sources must be non-empty".to_string(),
6807            ));
6808        }
6809        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
6810            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
6811        })?;
6812        let mut hasher = Sha256::new();
6813        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
6814        hasher.update((workflow_type.len() as u64).to_be_bytes());
6815        hasher.update(workflow_type.as_bytes());
6816        for source in sources {
6817            hasher.update((source.len() as u64).to_be_bytes());
6818            hasher.update(source.as_bytes());
6819        }
6820        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
6821        Ok(())
6822    }
6823
6824    /// Register a replayable workflow on the lossless fixed Avro Value surface.
6825    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
6826        &mut self,
6827        workflow_type: impl Into<String>,
6828        state_factory: Factory,
6829        handler: F,
6830    ) where
6831        S: Clone + Send + Sync + 'static,
6832        Factory: Fn() -> S + Send + Sync + 'static,
6833        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6834        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6835    {
6836        let state_factory = Arc::new(state_factory);
6837        let handler = Arc::new(handler);
6838
6839        let execute_factory = Arc::clone(&state_factory);
6840        let execute_handler = Arc::clone(&handler);
6841        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6842            let state = WorkflowInstance::new(execute_factory());
6843            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
6844        });
6845
6846        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6847            let state = WorkflowInstance::new(state_factory());
6848            let snapshot_state = state.clone();
6849            let snapshot: WorkflowStateSnapshot =
6850                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6851            ReplayedWorkflowInvocation {
6852                future: Box::pin(handler(ctx, input, state)),
6853                snapshot,
6854            }
6855        });
6856
6857        self.workflows.insert(
6858            workflow_type.into(),
6859            RegisteredWorkflow {
6860                execute,
6861                replay: Some(replay),
6862                state_type: Some(TypeId::of::<S>()),
6863                definition_fingerprint: None,
6864            },
6865        );
6866    }
6867
6868    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
6869    where
6870        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
6871        Fut: Future<Output = Result<Value>> + Send + 'static,
6872    {
6873        let handler = Arc::new(handler);
6874        self.activities.insert(
6875            activity_type.into(),
6876            Arc::new(move |ctx, args| {
6877                let handler = Arc::clone(&handler);
6878                Box::pin(async move {
6879                    let result = handler(ctx, args.into_json()?).await?;
6880                    AvroValue::from_serialize(&result)
6881                })
6882            }),
6883        );
6884    }
6885
6886    /// Register an activity with one Serde request value and a Serde result.
6887    ///
6888    /// Inputs and results use the platform's fixed Avro Value schema. Shape
6889    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
6890    /// with the activity name and Rust type.
6891    pub fn register_typed_activity<I, O, F, Fut>(
6892        &mut self,
6893        activity_type: impl Into<String>,
6894        handler: F,
6895    ) where
6896        I: DeserializeOwned + Send + 'static,
6897        O: Serialize + Send + 'static,
6898        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
6899        Fut: Future<Output = Result<O>> + Send + 'static,
6900    {
6901        let activity_type = activity_type.into();
6902        let handler_name = activity_type.clone();
6903        let handler = Arc::new(handler);
6904        self.activities.insert(
6905            activity_type,
6906            Arc::new(move |ctx, input| {
6907                let handler = Arc::clone(&handler);
6908                let handler_name = handler_name.clone();
6909                Box::pin(async move {
6910                    let input =
6911                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
6912                    let result = handler(ctx, input).await?;
6913                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
6914                })
6915            }),
6916        );
6917    }
6918
6919    /// Register an activity on the lossless fixed Avro Value surface.
6920    pub fn register_activity_avro_value<F, Fut>(
6921        &mut self,
6922        activity_type: impl Into<String>,
6923        handler: F,
6924    ) where
6925        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
6926        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6927    {
6928        self.activities.insert(
6929            activity_type.into(),
6930            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
6931        );
6932    }
6933
6934    /// Register a named, read-only query handler for a workflow type.
6935    ///
6936    /// The workflow type must also be registered with [`Worker::register_workflow`]
6937    /// before the worker runs. The handler receives only an immutable committed
6938    /// state snapshot and normalized query arguments.
6939    pub fn register_query<F, Fut>(
6940        &mut self,
6941        workflow_type: impl Into<String>,
6942        query_name: impl Into<String>,
6943        handler: F,
6944    ) where
6945        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
6946        Fut: Future<Output = Result<Value>> + Send + 'static,
6947    {
6948        let handler = Arc::new(handler);
6949        self.queries
6950            .entry(workflow_type.into())
6951            .or_default()
6952            .insert(
6953                query_name.into(),
6954                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
6955                    let handler = Arc::clone(&handler);
6956                    Box::pin(async move {
6957                        let result = handler(ctx, args.into_json()?).await?;
6958                        AvroValue::from_serialize(&result)
6959                    })
6960                })),
6961            );
6962    }
6963
6964    /// Register a query handler on the lossless fixed Avro Value surface.
6965    pub fn register_query_avro_value<F, Fut>(
6966        &mut self,
6967        workflow_type: impl Into<String>,
6968        query_name: impl Into<String>,
6969        handler: F,
6970    ) where
6971        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
6972        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6973    {
6974        self.queries
6975            .entry(workflow_type.into())
6976            .or_default()
6977            .insert(
6978                query_name.into(),
6979                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
6980            );
6981    }
6982
6983    /// Register a named query against deterministically replayed instance state.
6984    ///
6985    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
6986    /// same state type `S`. The handler receives an immutable, detached state
6987    /// clone, so successful and failed queries cannot affect workflow execution
6988    /// or the state reconstructed by a later query.
6989    pub fn register_replayed_query<S, F, Fut>(
6990        &mut self,
6991        workflow_type: impl Into<String>,
6992        query_name: impl Into<String>,
6993        handler: F,
6994    ) where
6995        S: Clone + Send + Sync + 'static,
6996        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
6997        Fut: Future<Output = Result<Value>> + Send + 'static,
6998    {
6999        let handler = Arc::new(handler);
7000        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7001            let state = state.downcast::<S>().map_err(|_| {
7002                "registered query state type does not match the replayed workflow state".to_string()
7003            })?;
7004            let handler = Arc::clone(&handler);
7005            Ok(Box::pin(async move {
7006                let result = handler(ctx, state, args.into_json()?).await?;
7007                AvroValue::from_serialize(&result)
7008            }))
7009        });
7010
7011        self.queries
7012            .entry(workflow_type.into())
7013            .or_default()
7014            .insert(
7015                query_name.into(),
7016                RegisteredQuery::Replayed {
7017                    state_type: TypeId::of::<S>(),
7018                    handler: erased_handler,
7019                },
7020            );
7021    }
7022
7023    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7024    pub fn register_replayed_query_avro_value<S, F, Fut>(
7025        &mut self,
7026        workflow_type: impl Into<String>,
7027        query_name: impl Into<String>,
7028        handler: F,
7029    ) where
7030        S: Clone + Send + Sync + 'static,
7031        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7032        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7033    {
7034        let handler = Arc::new(handler);
7035        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7036            let state = state.downcast::<S>().map_err(|_| {
7037                "registered query state type does not match the replayed workflow state".to_string()
7038            })?;
7039            Ok(Box::pin(handler(ctx, state, args)))
7040        });
7041
7042        self.queries
7043            .entry(workflow_type.into())
7044            .or_default()
7045            .insert(
7046                query_name.into(),
7047                RegisteredQuery::Replayed {
7048                    state_type: TypeId::of::<S>(),
7049                    handler: erased_handler,
7050                },
7051            );
7052    }
7053
7054    /// Register a synchronous workflow update handler.
7055    pub fn register_update<F, Fut>(
7056        &mut self,
7057        workflow_type: impl Into<String>,
7058        update_name: impl Into<String>,
7059        handler: F,
7060    ) where
7061        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7062        Fut: Future<Output = Result<Value>> + Send + 'static,
7063    {
7064        let handler = Arc::new(handler);
7065        self.updates
7066            .entry(workflow_type.into())
7067            .or_default()
7068            .insert(
7069                update_name.into(),
7070                Arc::new(move |ctx, args| {
7071                    let handler = Arc::clone(&handler);
7072                    Box::pin(async move {
7073                        let result = handler(ctx, args.into_json()?).await?;
7074                        AvroValue::from_serialize(&result)
7075                    })
7076                }),
7077            );
7078    }
7079
7080    /// Register an update handler on the lossless fixed Avro Value surface.
7081    pub fn register_update_avro_value<F, Fut>(
7082        &mut self,
7083        workflow_type: impl Into<String>,
7084        update_name: impl Into<String>,
7085        handler: F,
7086    ) where
7087        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7088        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7089    {
7090        self.updates
7091            .entry(workflow_type.into())
7092            .or_default()
7093            .insert(
7094                update_name.into(),
7095                Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7096            );
7097    }
7098
7099    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7100        self.session_registration_confirmed
7101            .store(false, Ordering::SeqCst);
7102        for capability in &self.resource_capabilities {
7103            worker_session::validate_resource_capability(capability)?;
7104        }
7105        self.local_registration_confirmed
7106            .store(false, Ordering::SeqCst);
7107        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7108            return Err(Error::CooperativeCancellationUnavailable(
7109                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7110            ));
7111        }
7112        let mut command_contracts = serde_json::Map::new();
7113        for workflow_type in self.workflows.keys() {
7114            let mut queries = self
7115                .queries
7116                .get(workflow_type)
7117                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7118                .unwrap_or_default();
7119            queries.sort();
7120            let mut updates = self
7121                .updates
7122                .get(workflow_type)
7123                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7124                .unwrap_or_default();
7125            updates.sort();
7126            command_contracts.insert(
7127                workflow_type.clone(),
7128                json!({
7129                    "queries": queries,
7130                    "query_contracts": argument_vector_contracts(&queries),
7131                    "signals": [],
7132                    "signal_contracts": [],
7133                    "updates": updates,
7134                    "update_contracts": argument_vector_contracts(&updates),
7135                    "update_validators": [],
7136                }),
7137            );
7138        }
7139
7140        self.cooperative_registration_confirmed
7141            .store(false, Ordering::SeqCst);
7142        let response = self
7143            .client
7144            .register_worker_with_definition_fingerprints(
7145                &self.worker_id,
7146                &self.task_queue,
7147                self.workflows.keys().cloned().collect(),
7148                self.activities.keys().cloned().collect(),
7149                self.max_concurrent_workflow_tasks,
7150                self.max_concurrent_activity_tasks,
7151                [
7152                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7153                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7154                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7155                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7156                    self.client
7157                        .local_activities_enabled
7158                        .then(|| "local_activities".to_string()),
7159                    self.client
7160                        .worker_sessions_enabled
7161                        .then(|| "worker_sessions".to_string()),
7162                    self.cooperative_cancellation_enabled
7163                        .then(|| "cooperative_cancellation".to_string()),
7164                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7165                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7166                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7167                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7168                ]
7169                .into_iter()
7170                .flatten()
7171                .chain(self.resource_capabilities.iter().cloned())
7172                .collect(),
7173                Value::Object(command_contracts),
7174                Some(
7175                    self.workflows
7176                        .iter()
7177                        .filter_map(|(workflow_type, workflow)| {
7178                            workflow
7179                                .definition_fingerprint
7180                                .as_ref()
7181                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7182                        })
7183                        .collect(),
7184                ),
7185            )
7186            .await?;
7187        if self.cooperative_cancellation_enabled && response.registered {
7188            self.cooperative_registration_confirmed
7189                .store(true, Ordering::SeqCst);
7190        }
7191        if self.client.local_activities_enabled && response.registered {
7192            self.local_registration_confirmed
7193                .store(true, Ordering::SeqCst);
7194        }
7195        if self.client.worker_sessions_enabled && response.registered {
7196            self.session_registration_confirmed
7197                .store(true, Ordering::SeqCst);
7198        }
7199        Ok(response)
7200    }
7201
7202    /// Run until shutdown or a terminal worker error occurs.
7203    ///
7204    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7205    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7206    /// authentication, protocol, and other non-retryable failures are returned.
7207    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7208    /// poll and heartbeat outages beyond the ordinary retry budget.
7209    pub async fn run(&self) -> Result<()> {
7210        self.run_until(std::future::pending::<()>()).await
7211    }
7212
7213    /// Run until `shutdown` resolves or a terminal worker error occurs.
7214    ///
7215    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7216    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7217    where
7218        F: Future<Output = ()>,
7219    {
7220        let stop = Arc::new(AtomicBool::new(false));
7221        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7222        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7223        worker.run_stop = Some(Arc::clone(&stop));
7224        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7225        tokio::pin!(run);
7226        tokio::pin!(shutdown);
7227        tokio::select! {
7228            result = &mut run => result,
7229            _ = &mut shutdown => {
7230                stop.store(true, Ordering::SeqCst);
7231                run.await
7232            }
7233        }
7234    }
7235
7236    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7237        let mut worker = self.clone();
7238        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7239            policy: self.retry_policy,
7240            stop,
7241        });
7242        worker
7243    }
7244
7245    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7246        let registration = self.register().await?;
7247        if !registration.registered {
7248            return Err(Error::WorkerLoop(format!(
7249                "worker registration for {:?} was not accepted",
7250                self.worker_id
7251            )));
7252        }
7253        let registered_worker_id = registration.worker_id.clone();
7254        let primary = self.run_registered_until(stop, registration).await;
7255        let primary = match (primary, self.close_worker_sessions().await) {
7256            (Ok(()), result) => result,
7257            (Err(error), Ok(())) => Err(error),
7258            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7259                primary: Box::new(primary),
7260                deregistration: Box::new(close),
7261            }),
7262        };
7263        self.session_registration_confirmed
7264            .store(false, Ordering::SeqCst);
7265        self.cooperative_registration_confirmed
7266            .store(false, Ordering::SeqCst);
7267        self.local_registration_confirmed
7268            .store(false, Ordering::SeqCst);
7269        let deregistration = self
7270            .client
7271            .deregister_worker_registration(&registered_worker_id)
7272            .await;
7273
7274        match (primary, deregistration) {
7275            (Ok(()), Ok(_)) => Ok(()),
7276            (Ok(()), Err(deregistration)) => Err(deregistration),
7277            (Err(primary), Ok(_)) => Err(primary),
7278            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7279                primary: Box::new(primary),
7280                deregistration: Box::new(deregistration),
7281            }),
7282        }
7283    }
7284
7285    async fn run_registered_until(
7286        &self,
7287        stop: Arc<AtomicBool>,
7288        registration: RegisterWorkerResponse,
7289    ) -> Result<()> {
7290        let heartbeat_interval = Duration::from_secs(
7291            registration
7292                .heartbeat_interval_seconds
7293                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7294        );
7295        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7296        // from the completion of the preceding attempt, including its bounded
7297        // retries. A fixed-epoch interval can leave an already-due tick queued
7298        // while an acknowledgement is slow, producing a catch-up heartbeat as
7299        // soon as that request completes.
7300        let heartbeat = tokio::time::sleep(Duration::ZERO);
7301        tokio::pin!(heartbeat);
7302        // Poll responses may already have leased server-side work by the time
7303        // they become ready, so each poller owns its responses through
7304        // completion or failure instead of racing raw polls in this select.
7305        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7306            let worker = self.clone();
7307            let stop = Arc::clone(&stop);
7308            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7309        });
7310        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7311            let worker = self.clone();
7312            let stop = Arc::clone(&stop);
7313            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7314        });
7315        let mut query_poller = (!self.queries.is_empty()).then(|| {
7316            let worker = self.clone();
7317            let stop = Arc::clone(&stop);
7318            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7319        });
7320
7321        loop {
7322            tokio::select! {
7323                _ = wait_for_worker_stop(&stop) => {
7324                    stop.store(true, Ordering::SeqCst);
7325                    break;
7326                }
7327                _ = &mut heartbeat => {
7328                    let result = self.retry_worker_operation(|| {
7329                        self.client.heartbeat_worker_with_sessions(
7330                            &self.worker_id,
7331                            self.max_concurrent_workflow_tasks,
7332                            self.max_concurrent_activity_tasks,
7333                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7334                        )
7335                    }).await;
7336                    heartbeat
7337                        .as_mut()
7338                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7339                    match result {
7340                        Ok(Some(acknowledgement)) => {
7341                            if let Some(observer) = &self.heartbeat_observer {
7342                                observer(&WorkerHeartbeatObservation {
7343                                    worker_id: self.worker_id.clone(),
7344                                    task_queue: self.task_queue.clone(),
7345                                    acknowledged_at_unix_millis: SystemTime::now()
7346                                        .duration_since(UNIX_EPOCH)
7347                                        .unwrap_or_default()
7348                                        .as_millis()
7349                                        .min(u64::MAX as u128)
7350                                        as u64,
7351                                    acknowledgement,
7352                                });
7353                            }
7354                        }
7355                        Ok(None) => break,
7356                        Err(error) => {
7357                            stop.store(true, Ordering::SeqCst);
7358                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7359                            return Err(error);
7360                        }
7361                    }
7362                }
7363                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7364                    workflow_poller = None;
7365                    let stopped_by_server = stop.load(Ordering::SeqCst);
7366                    stop.store(true, Ordering::SeqCst);
7367                    let poller_result = optional_poller_result("workflow", result);
7368                    let join_result =
7369                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7370                    poller_result?;
7371                    join_result?;
7372                    if stopped_by_server {
7373                        return Ok(());
7374                    }
7375                    return Err(Error::WorkerLoop(
7376                        "workflow poller stopped unexpectedly".to_string(),
7377                    ));
7378                }
7379                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7380                    activity_poller = None;
7381                    let stopped_by_server = stop.load(Ordering::SeqCst);
7382                    stop.store(true, Ordering::SeqCst);
7383                    let poller_result = optional_poller_result("activity", result);
7384                    let join_result =
7385                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7386                    poller_result?;
7387                    join_result?;
7388                    if stopped_by_server {
7389                        return Ok(());
7390                    }
7391                    return Err(Error::WorkerLoop(
7392                        "activity poller stopped unexpectedly".to_string(),
7393                    ));
7394                }
7395                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7396                    query_poller = None;
7397                    let stopped_by_server = stop.load(Ordering::SeqCst);
7398                    stop.store(true, Ordering::SeqCst);
7399                    let poller_result = optional_poller_result("query", result);
7400                    let join_result =
7401                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7402                    poller_result?;
7403                    join_result?;
7404                    if stopped_by_server {
7405                        return Ok(());
7406                    }
7407                    return Err(Error::WorkerLoop(
7408                        "query poller stopped unexpectedly".to_string(),
7409                    ));
7410                }
7411            }
7412        }
7413
7414        join_pollers(
7415            workflow_poller.take(),
7416            activity_poller.take(),
7417            query_poller.take(),
7418        )
7419        .await
7420    }
7421
7422    /// Poll and settle at most one task from each enabled task family.
7423    ///
7424    /// A workflow may reach its server-enforced run deadline while this worker
7425    /// holds a task. When the completion endpoint authoritatively rejects that
7426    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
7427    /// terminal `run_status=failed`, the workflow tick is considered settled:
7428    /// the late command was not recorded and cannot replace the terminal run.
7429    /// Every other completion rejection remains an error. This worker-level
7430    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
7431    /// only bounds how long a client waits for a result.
7432    ///
7433    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
7434    /// the original [`Error::Http`] status and response body.
7435    pub async fn run_once(&self) -> Result<usize> {
7436        if self.client.worker_sessions_enabled {
7437            self.require_session_registration()?;
7438        }
7439        if self.cooperative_cancellation_enabled
7440            && !self
7441                .cooperative_registration_confirmed
7442                .load(Ordering::SeqCst)
7443        {
7444            return Err(Error::CooperativeCancellationUnavailable(
7445                "register this cooperative worker before polling tasks".into(),
7446            ));
7447        }
7448        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
7449        let mut handled = 0;
7450        match worker.poll_workflow_once().await? {
7451            ManagedPollOutcome::Handled => handled += 1,
7452            ManagedPollOutcome::Stop => return Ok(handled),
7453            ManagedPollOutcome::Idle => {}
7454        }
7455        match worker.poll_activity_once().await? {
7456            ManagedPollOutcome::Handled => handled += 1,
7457            ManagedPollOutcome::Stop => return Ok(handled),
7458            ManagedPollOutcome::Idle => {}
7459        }
7460        if !self.queries.is_empty() {
7461            match worker.poll_query_once().await? {
7462                ManagedPollOutcome::Handled => handled += 1,
7463                ManagedPollOutcome::Stop => return Ok(handled),
7464                ManagedPollOutcome::Idle => {}
7465            }
7466        }
7467        Ok(handled)
7468    }
7469
7470    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
7471        if self.client.local_activities_enabled
7472            && !self.local_registration_confirmed.load(Ordering::SeqCst)
7473        {
7474            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
7475        }
7476        if self.cooperative_cancellation_enabled {
7477            return self.poll_cooperative_workflow_once().await;
7478        }
7479        let poll_request_id = unique_request_id("rust-workflow-poll");
7480        let response = self
7481            .retry_worker_operation(|| {
7482                self.client.poll_workflow_task_response_with_request_id(
7483                    &self.worker_id,
7484                    &self.task_queue,
7485                    self.poll_timeout,
7486                    &poll_request_id,
7487                    0,
7488                )
7489            })
7490            .await;
7491        let Some(response) = self.settle_worker_poll_response(response).await? else {
7492            return Ok(ManagedPollOutcome::Idle);
7493        };
7494        if response.outcome().should_stop() {
7495            return Ok(ManagedPollOutcome::Stop);
7496        }
7497        let memo_updates_supported =
7498            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
7499        let Some(task) = response.task else {
7500            return Ok(ManagedPollOutcome::Idle);
7501        };
7502
7503        let task_id = task.task_id.clone();
7504        let attempt = task.workflow_task_attempt;
7505        let run_id = task.run_id.clone();
7506        let lease_owner = task
7507            .lease_owner
7508            .clone()
7509            .unwrap_or_else(|| self.worker_id.clone());
7510
7511        let decision = match self.execute_workflow_with_local_activities(task).await {
7512            Ok(Some(decision)) => Ok(decision),
7513            Ok(None) => return Ok(ManagedPollOutcome::Handled),
7514            Err(error) => Err(error),
7515        };
7516        self.settle_workflow_task_decision(
7517            &task_id,
7518            &lease_owner,
7519            attempt,
7520            run_id.as_deref(),
7521            decision,
7522            memo_updates_supported,
7523        )
7524        .await
7525    }
7526
7527    async fn settle_workflow_task_decision(
7528        &self,
7529        task_id: &str,
7530        lease_owner: &str,
7531        attempt: u64,
7532        run_id: Option<&str>,
7533        decision: Result<WorkflowTaskDecision>,
7534        memo_updates_supported: bool,
7535    ) -> Result<ManagedPollOutcome> {
7536        match decision {
7537            Ok(decision)
7538                if decision.cancellation_delivery.is_some()
7539                    || decision.cancellation_scope_delivery.is_some()
7540                    || decision.cancellation_scope_opening.is_some() =>
7541            {
7542                return Err(Error::CooperativeCancellationUnavailable(
7543                    "worker cancellation delivery has not been negotiated".into(),
7544                ));
7545            }
7546            Ok(decision)
7547                if commands_use_workflow_memo_updates(&decision.commands)
7548                    && !memo_updates_supported =>
7549            {
7550                self.client
7551                    .fail_workflow_task(
7552                        task_id,
7553                        lease_owner,
7554                        attempt,
7555                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
7556                    )
7557                    .await?;
7558            }
7559            Ok(decision) if decision.commands.is_empty() => {
7560                // A replay can consume a recorded pending durable command
7561                // without producing a new command. The standalone protocol
7562                // acknowledges that state through the typed waiting outcome;
7563                // an empty completion is rejected by servers that require at
7564                // least one executable command.
7565                self.client
7566                    .fail_workflow_task_with_type(
7567                        task_id,
7568                        lease_owner,
7569                        attempt,
7570                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
7571                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
7572                    )
7573                    .await?;
7574            }
7575            Ok(decision) => {
7576                let completion = self
7577                    .client
7578                    .complete_workflow_task_with_message_streams(
7579                        task_id,
7580                        lease_owner,
7581                        attempt,
7582                        decision.commands,
7583                        decision.message_stream_cursors,
7584                        decision.message_stream_waits,
7585                    )
7586                    .await;
7587                if let Err(error) = completion {
7588                    if !workflow_task_completion_is_terminal_timeout(
7589                        &error, task_id, attempt, run_id,
7590                    ) {
7591                        return Err(error);
7592                    }
7593                }
7594            }
7595            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
7596            Err(error) => {
7597                self.client
7598                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
7599                    .await?;
7600            }
7601        }
7602
7603        Ok(ManagedPollOutcome::Handled)
7604    }
7605
7606    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7607        while !stop.load(Ordering::SeqCst) {
7608            match self.poll_workflow_once().await {
7609                Ok(ManagedPollOutcome::Stop) => {
7610                    stop.store(true, Ordering::SeqCst);
7611                    break;
7612                }
7613                Err(error) => {
7614                    stop.store(true, Ordering::SeqCst);
7615                    return Err(error);
7616                }
7617                _ => {}
7618            }
7619        }
7620
7621        Ok(())
7622    }
7623
7624    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
7625        if self.client.worker_sessions_enabled {
7626            self.require_session_registration()?;
7627        }
7628        if self.cooperative_cancellation_enabled {
7629            return self.poll_cooperative_activity_once().await;
7630        }
7631        let poll_request_id = unique_request_id("rust-activity-poll");
7632        let response = self
7633            .retry_worker_operation(|| {
7634                self.client.poll_activity_task_response_with_request_id(
7635                    &self.worker_id,
7636                    &self.task_queue,
7637                    self.poll_timeout,
7638                    &poll_request_id,
7639                    0,
7640                )
7641            })
7642            .await;
7643        let Some(response) = self.settle_worker_poll_response(response).await? else {
7644            return Ok(ManagedPollOutcome::Idle);
7645        };
7646        if response.outcome().should_stop() {
7647            return Ok(ManagedPollOutcome::Stop);
7648        }
7649        let Some(task) = response.task else {
7650            return Ok(ManagedPollOutcome::Idle);
7651        };
7652
7653        let session = self.track_session_task(task.worker_session.as_ref())?;
7654        let task = task.task;
7655
7656        let task_id = task.task_id.clone();
7657        let attempt_id = task
7658            .activity_attempt_id
7659            .clone()
7660            .or(task.attempt_id.clone())
7661            .unwrap_or_default();
7662        let lease_owner = task
7663            .lease_owner
7664            .clone()
7665            .unwrap_or_else(|| self.worker_id.clone());
7666        let codec = task.payload_codec.clone();
7667        let result = self.execute_session_activity_task(task, session).await;
7668        match result {
7669            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
7670            Ok(value) => {
7671                let completion = self
7672                    .client
7673                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
7674                    .await;
7675                if let Err(error) = completion {
7676                    if !activity_task_rejection_is_final(&error) {
7677                        return Err(error);
7678                    }
7679                }
7680            }
7681            Err(error) => {
7682                let failure = self
7683                    .client
7684                    .fail_activity_task(
7685                        &task_id,
7686                        &attempt_id,
7687                        &lease_owner,
7688                        error.to_string(),
7689                        false,
7690                    )
7691                    .await;
7692                if let Err(error) = failure {
7693                    if !activity_task_rejection_is_final(&error) {
7694                        return Err(error);
7695                    }
7696                }
7697            }
7698        }
7699
7700        Ok(ManagedPollOutcome::Handled)
7701    }
7702
7703    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7704        // Each lane retains its leased response through callback settlement.
7705        // A bounded independent activity must not occupy the cleanup lane too.
7706        // Preserve the existing serial loop for default protocol 1.19 workers.
7707        let lane_count = if self.cooperative_cancellation_enabled {
7708            self.max_concurrent_activity_tasks
7709        } else {
7710            1
7711        };
7712        let mut lanes = FuturesUnordered::new();
7713        for _ in 0..lane_count {
7714            let worker = self.clone();
7715            let stop = Arc::clone(&stop);
7716            lanes.push(async move {
7717                while !stop.load(Ordering::SeqCst) {
7718                    match worker.poll_activity_once().await {
7719                        Ok(ManagedPollOutcome::Stop) => {
7720                            stop.store(true, Ordering::SeqCst);
7721                            break;
7722                        }
7723                        Err(error) => {
7724                            stop.store(true, Ordering::SeqCst);
7725                            return Err(error);
7726                        }
7727                        _ => {}
7728                    }
7729                }
7730                Ok(())
7731            });
7732        }
7733        // Join every lane before deregistration, including after one fails.
7734        let mut first_error = None;
7735        while let Some(result) = lanes.next().await {
7736            if let Err(error) = result {
7737                first_error.get_or_insert(error);
7738            }
7739        }
7740        first_error.map_or(Ok(()), Err)
7741    }
7742
7743    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
7744        let poll_request_id = unique_request_id("rust-query-poll");
7745        let response = self
7746            .retry_worker_operation(|| {
7747                self.client.poll_query_task_response_with_request_id(
7748                    &self.worker_id,
7749                    &self.task_queue,
7750                    self.poll_timeout,
7751                    &poll_request_id,
7752                    0,
7753                )
7754            })
7755            .await;
7756        let Some(response) = self.settle_worker_poll_response(response).await? else {
7757            return Ok(ManagedPollOutcome::Idle);
7758        };
7759        if response.outcome().should_stop() {
7760            return Ok(ManagedPollOutcome::Stop);
7761        }
7762        let Some(task) = response.task else {
7763            return Ok(ManagedPollOutcome::Idle);
7764        };
7765
7766        let query_task_id = task.query_task_id.clone();
7767        let attempt = task.query_task_attempt;
7768        let lease_owner = task
7769            .lease_owner
7770            .clone()
7771            .unwrap_or_else(|| self.worker_id.clone());
7772        let codec = task.payload_codec.clone();
7773
7774        match self.execute_query_task(task).await {
7775            Ok(value) => {
7776                let result_envelope = match encode_typed_envelope(&value, &codec) {
7777                    Ok(result_envelope) => result_envelope,
7778                    Err(error) => {
7779                        let failure = self
7780                            .client
7781                            .fail_query_task(
7782                                &query_task_id,
7783                                &lease_owner,
7784                                attempt,
7785                                error.to_string(),
7786                                "query_result_encode_failed",
7787                                "QueryResultEncodeFailed",
7788                            )
7789                            .await;
7790                        if let Err(error) = failure {
7791                            if !query_task_rejection_is_final(&error) {
7792                                return Err(error);
7793                            }
7794                        }
7795                        return Ok(ManagedPollOutcome::Handled);
7796                    }
7797                };
7798
7799                if let Err(error) = self
7800                    .client
7801                    .complete_query_task_with_envelope(
7802                        &query_task_id,
7803                        &lease_owner,
7804                        attempt,
7805                        value.clone().into_json()?,
7806                        result_envelope,
7807                    )
7808                    .await
7809                {
7810                    if !query_task_rejection_is_final(&error) {
7811                        return Err(error);
7812                    }
7813                }
7814            }
7815            Err(failure) => {
7816                let result = self
7817                    .client
7818                    .fail_query_task(
7819                        &query_task_id,
7820                        &lease_owner,
7821                        attempt,
7822                        failure.message,
7823                        failure.reason,
7824                        failure.failure_type,
7825                    )
7826                    .await;
7827                if let Err(error) = result {
7828                    if !query_task_rejection_is_final(&error) {
7829                        return Err(error);
7830                    }
7831                }
7832            }
7833        }
7834
7835        Ok(ManagedPollOutcome::Handled)
7836    }
7837
7838    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7839        while !stop.load(Ordering::SeqCst) {
7840            match self.poll_query_once().await {
7841                Ok(ManagedPollOutcome::Stop) => {
7842                    stop.store(true, Ordering::SeqCst);
7843                    break;
7844                }
7845                Err(error) => {
7846                    stop.store(true, Ordering::SeqCst);
7847                    return Err(error);
7848                }
7849                _ => {}
7850            }
7851        }
7852
7853        Ok(())
7854    }
7855
7856    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
7857    where
7858        F: FnMut() -> Fut,
7859        Fut: Future<Output = Result<T>>,
7860    {
7861        let mut retries = 0;
7862
7863        loop {
7864            if self
7865                .run_stop
7866                .as_ref()
7867                .is_some_and(|stop| stop.load(Ordering::SeqCst))
7868            {
7869                return Ok(None);
7870            }
7871            match operation().await {
7872                Err(error)
7873                    if worker_operation_is_retryable(&error)
7874                        && (retries < self.retry_policy.max_retries
7875                            || (self.recover_transient_outages
7876                                && self.run_stop.is_some()
7877                                && self.retry_policy.max_retries > 0)) =>
7878                {
7879                    retries = retries.saturating_add(1);
7880                    let delay = worker_retry_delay(self.retry_policy, retries)
7881                        .max(Duration::from_millis(1));
7882                    if let Some(stop) = &self.run_stop {
7883                        tokio::select! {
7884                            _ = tokio::time::sleep(delay) => {}
7885                            _ = wait_for_worker_stop(stop) => return Ok(None),
7886                        }
7887                    } else {
7888                        tokio::time::sleep(delay).await;
7889                    }
7890                }
7891                result => return result.map(Some),
7892            }
7893        }
7894    }
7895
7896    async fn settle_worker_poll_response<T>(
7897        &self,
7898        response: Result<Option<T>>,
7899    ) -> Result<Option<T>> {
7900        match response {
7901            Ok(response) => Ok(response),
7902            Err(error) => {
7903                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
7904                    return Err(error);
7905                };
7906                let minimum_delay = self
7907                    .retry_policy
7908                    .initial_backoff
7909                    .max(Duration::from_millis(1));
7910                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
7911                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
7912                Ok(None)
7913            }
7914        }
7915    }
7916
7917    async fn execute_query_task(
7918        &self,
7919        mut task: QueryTask,
7920    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
7921        validate_query_task_payloads(&task).map_err(|error| {
7922            QueryTaskExecutionFailure::new(
7923                "query_payload_decode_failed",
7924                error.to_string(),
7925                "QueryPayloadDecodeFailed",
7926            )
7927        })?;
7928
7929        if !self.workflows.contains_key(&task.workflow_type) {
7930            return Err(QueryTaskExecutionFailure::new(
7931                "query_workflow_type_not_registered",
7932                format!("no workflow registered for type {:?}", task.workflow_type),
7933                "WorkflowTypeNotRegistered",
7934            ));
7935        }
7936
7937        let Some(handlers) = self.queries.get(&task.workflow_type) else {
7938            return Err(QueryTaskExecutionFailure::new(
7939                "query_handler_unavailable",
7940                format!(
7941                    "query handlers are unavailable for workflow type {:?}",
7942                    task.workflow_type
7943                ),
7944                "QueryHandlerUnavailable",
7945            ));
7946        };
7947        let Some(query) = handlers.get(&task.query_name) else {
7948            return Err(QueryTaskExecutionFailure::new(
7949                "rejected_unknown_query",
7950                format!("unknown query {:?}", task.query_name),
7951                "QueryFailed",
7952            ));
7953        };
7954
7955        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
7956            .map_err(|error| {
7957            QueryTaskExecutionFailure::new(
7958                "query_payload_decode_failed",
7959                format!("cannot decode query arguments: {error}"),
7960                "QueryPayloadDecodeFailed",
7961            )
7962        })?;
7963        let workflow_input_typed =
7964            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
7965                .map_err(|error| {
7966                    QueryTaskExecutionFailure::new(
7967                        "query_workflow_state_unavailable",
7968                        format!("cannot decode workflow start input: {error}"),
7969                        "QueryWorkflowStateUnavailable",
7970                    )
7971                })?;
7972        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
7973            QueryTaskExecutionFailure::new(
7974                "query_workflow_state_unavailable",
7975                format!("cannot project workflow start input: {error}"),
7976                "QueryWorkflowStateUnavailable",
7977            )
7978        })?;
7979        hydrate_query_history_from_export(&mut task).map_err(|error| {
7980            QueryTaskExecutionFailure::new(
7981                "query_workflow_state_unavailable",
7982                format!("cannot restore query history snapshot: {error}"),
7983                "QueryWorkflowStateUnavailable",
7984            )
7985        })?;
7986        enrich_query_history_from_export(&mut task).map_err(|error| {
7987            QueryTaskExecutionFailure::new(
7988                "query_workflow_state_unavailable",
7989                format!("cannot restore compact query history payloads: {error}"),
7990                "QueryWorkflowStateUnavailable",
7991            )
7992        })?;
7993        let signal_events = query_signal_events(&task).map_err(|error| {
7994            QueryTaskExecutionFailure::new(
7995                "query_workflow_state_unavailable",
7996                format!("cannot decode committed workflow signals: {error}"),
7997                "QueryWorkflowStateUnavailable",
7998            )
7999        })?;
8000        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8001        let context = QueryContext {
8002            workflow_id: task.workflow_id,
8003            run_id: task.run_id,
8004            workflow_type: task.workflow_type.clone(),
8005            run_status: task.run_status,
8006            workflow_input,
8007            workflow_input_avro_value: workflow_input_typed.clone(),
8008            history_events: Arc::clone(&history_events),
8009            signal_events: Arc::new(signal_events),
8010        };
8011
8012        let future = match query {
8013            RegisteredQuery::Snapshot(handler) => handler(context, args),
8014            RegisteredQuery::Replayed {
8015                state_type,
8016                handler,
8017            } => {
8018                let workflow = self
8019                    .workflows
8020                    .get(&task.workflow_type)
8021                    .expect("workflow registration was checked above");
8022                if workflow.state_type != Some(*state_type) {
8023                    return Err(QueryTaskExecutionFailure::new(
8024                        "query_workflow_state_unavailable",
8025                        "replayed query state type does not match its workflow registration",
8026                        "QueryWorkflowStateUnavailable",
8027                    ));
8028                }
8029                let replay = workflow.replay.as_ref().ok_or_else(|| {
8030                    QueryTaskExecutionFailure::new(
8031                        "query_workflow_state_unavailable",
8032                        format!(
8033                            "workflow type {:?} is not registered for instance-state replay",
8034                            task.workflow_type
8035                        ),
8036                        "QueryWorkflowStateUnavailable",
8037                    )
8038                })?;
8039                let workflow_state = Arc::new(Mutex::new(
8040                    WorkflowState::new_with_identity(
8041                        history_events.as_ref().clone(),
8042                        context.workflow_id.clone(),
8043                        context.run_id.clone(),
8044                        self.task_queue.clone(),
8045                        task.payload_codec,
8046                        None,
8047                    )
8048                    .map_err(|error| {
8049                        QueryTaskExecutionFailure::new(
8050                            "query_workflow_state_unavailable",
8051                            format!("workflow replay failed before query: {error}"),
8052                            "QueryWorkflowStateUnavailable",
8053                        )
8054                    })?,
8055                ));
8056                let workflow_context = WorkflowContext {
8057                    state: workflow_state,
8058                    cancellation_scope_id: "root".into(),
8059                };
8060                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8061                let mut cx = TaskContext::from_waker(noop_waker_ref());
8062                let outcome = {
8063                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8064                        .map_err(|error| {
8065                            QueryTaskExecutionFailure::new(
8066                                "query_workflow_state_unavailable",
8067                                error.to_string(),
8068                                "QueryWorkflowStateUnavailable",
8069                            )
8070                        })?;
8071                    invocation.future.as_mut().poll(&mut cx)
8072                };
8073                match outcome {
8074                    Poll::Ready(Ok(_)) => {
8075                        workflow_context
8076                            .ensure_history_consumed()
8077                            .map_err(|error| {
8078                                QueryTaskExecutionFailure::new(
8079                                    "query_workflow_state_unavailable",
8080                                    format!("workflow replay failed before query: {error}"),
8081                                    "QueryWorkflowStateUnavailable",
8082                                )
8083                            })?;
8084                    }
8085                    Poll::Ready(Err(error)) => {
8086                        return Err(QueryTaskExecutionFailure::new(
8087                            "query_workflow_state_unavailable",
8088                            format!("workflow replay failed before query: {error}"),
8089                            "QueryWorkflowStateUnavailable",
8090                        ));
8091                    }
8092                    Poll::Pending => {
8093                        let commands = workflow_context.take_commands().map_err(|error| {
8094                            QueryTaskExecutionFailure::new(
8095                                "query_workflow_state_unavailable",
8096                                format!("workflow replay failed before query: {error}"),
8097                                "QueryWorkflowStateUnavailable",
8098                            )
8099                        })?;
8100                        if commands.is_empty()
8101                            && !workflow_context
8102                                .matched_recorded_pending()
8103                                .map_err(|error| {
8104                                    QueryTaskExecutionFailure::new(
8105                                        "query_workflow_state_unavailable",
8106                                        format!("workflow replay failed before query: {error}"),
8107                                        "QueryWorkflowStateUnavailable",
8108                                    )
8109                                })?
8110                        {
8111                            return Err(QueryTaskExecutionFailure::new(
8112                                "query_workflow_state_unavailable",
8113                                "workflow replay yielded without a durable command",
8114                                "QueryWorkflowStateUnavailable",
8115                            ));
8116                        }
8117                    }
8118                }
8119                let state = (invocation.snapshot)().map_err(|error| {
8120                    QueryTaskExecutionFailure::new(
8121                        "query_workflow_state_unavailable",
8122                        format!("cannot snapshot replayed workflow state: {error}"),
8123                        "QueryWorkflowStateUnavailable",
8124                    )
8125                })?;
8126                handler(context, state, args).map_err(|message| {
8127                    QueryTaskExecutionFailure::new(
8128                        "query_workflow_state_unavailable",
8129                        message,
8130                        "QueryWorkflowStateUnavailable",
8131                    )
8132                })?
8133            }
8134        };
8135
8136        future.await.map_err(|error| {
8137            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8138        })
8139    }
8140
8141    #[cfg(test)]
8142    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8143        Ok(self.execute_workflow_task_decision(task)?.commands)
8144    }
8145
8146    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8147        self.execute_workflow_task_decision_with_cancellation(task, None)
8148    }
8149
8150    fn execute_workflow_task_decision_with_cancellation(
8151        &self,
8152        task: WorkflowTask,
8153        observation: Option<&CancellationRequest>,
8154    ) -> Result<WorkflowTaskDecision> {
8155        match self.prepare_workflow_task_execution(task, observation)? {
8156            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8157            PreparedWorkflowTask::Execution {
8158                task,
8159                context,
8160                mut future,
8161            } => {
8162                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8163                self.finish_workflow_task_execution(&task, &context, outcome)
8164            }
8165        }
8166    }
8167
8168    fn prepare_workflow_task_execution(
8169        &self,
8170        task: WorkflowTask,
8171        observation: Option<&CancellationRequest>,
8172    ) -> Result<PreparedWorkflowTask> {
8173        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8174            && !self.cooperative_cancellation_enabled
8175        {
8176            return Err(Error::CancellationScopeExecutionUnavailable);
8177        }
8178        validate_workflow_task_payloads(&task)?;
8179        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8180            &task.history_events,
8181            self.allow_cancellation_scope_authoring,
8182            self.allow_cancellation_scope_delivery,
8183        )?;
8184        let cancellation_history = if let Some(observation) = observation {
8185            observation.validate_observation()?;
8186            cooperative_cancellation::cancellation_claim(&task)?;
8187            let canonical = CancellationHistory::from_events(
8188                &task.history_events,
8189                task.run_id.as_deref().unwrap_or_default(),
8190                Some(observation),
8191            )?;
8192            if canonical.request_index >= task.history_events.len() {
8193                return Err(Error::InvalidCooperativeCancellation(
8194                    "workflow replay requires the observed canonical request".into(),
8195                ));
8196            }
8197            Some(canonical)
8198        } else {
8199            None
8200        };
8201        if let Some(update_id) = task
8202            .workflow_update_id
8203            .as_deref()
8204            .filter(|update_id| !update_id.is_empty())
8205        {
8206            if self.allow_cancellation_scope_delivery {
8207                return Err(Error::CancellationScopeExecutionUnavailable);
8208            }
8209            CancellationHistory::from_events(
8210                &task.history_events,
8211                task.run_id.as_deref().unwrap_or_default(),
8212                None,
8213            )?;
8214            return self
8215                .execute_update_task(&task, update_id)
8216                .map(WorkflowTaskDecision::without_message_streams)
8217                .map(PreparedWorkflowTask::Decision);
8218        }
8219
8220        let workflow = self
8221            .workflows
8222            .get(&task.workflow_type)
8223            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8224        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8225        let resume_signal = decode_resume_signal(&task)?;
8226        let history_budget = WorkflowHistoryBudget {
8227            event_count: task
8228                .total_history_events
8229                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8230            size_bytes: task.history_size_bytes,
8231            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8232            pressure: task.history_budget_pressure.clone(),
8233        };
8234        let workflow_command_identity = task
8235            .workflow_command_id
8236            .clone()
8237            .filter(|identity| !identity.is_empty())
8238            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8239            .unwrap_or_default();
8240        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8241            task.history_events.clone(),
8242            task.workflow_id.clone(),
8243            task.run_id.clone(),
8244            self.task_queue.clone(),
8245            task.payload_codec.clone(),
8246            resume_signal,
8247            self.allow_cancellation_scope_authoring,
8248            self.allow_cancellation_scope_delivery,
8249        )?;
8250        workflow_state.history_budget = history_budget;
8251        workflow_state.workflow_command_identity = workflow_command_identity;
8252        if let Some(canonical) = cancellation_history {
8253            workflow_state.cancellation_history = canonical;
8254            workflow_state.cancellation_delivery_enabled = true;
8255        }
8256        if workflow_state.cancellation_history.request.is_none() {
8257            workflow_state.cancel_requested = task.cancel_requested;
8258        }
8259        let state = Arc::new(Mutex::new(workflow_state));
8260        let ctx = WorkflowContext {
8261            state,
8262            cancellation_scope_id: "root".into(),
8263        };
8264        let future = (workflow.execute)(ctx.clone(), input);
8265        Ok(PreparedWorkflowTask::Execution {
8266            task,
8267            context: ctx,
8268            future,
8269        })
8270    }
8271
8272    fn poll_workflow_future(
8273        ctx: &WorkflowContext,
8274        future: &mut WorkflowFuture,
8275    ) -> Result<Poll<Result<AvroValue>>> {
8276        let mut cx = TaskContext::from_waker(noop_waker_ref());
8277        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
8278        Ok(future.as_mut().poll(&mut cx))
8279    }
8280
8281    fn finish_workflow_task_execution(
8282        &self,
8283        task: &WorkflowTask,
8284        ctx: &WorkflowContext,
8285        outcome: Poll<Result<AvroValue>>,
8286    ) -> Result<WorkflowTaskDecision> {
8287        if !ctx
8288            .state
8289            .lock()
8290            .map_err(|_| Error::WorkflowStatePoisoned)?
8291            .local_activity_requests
8292            .is_empty()
8293        {
8294            return Err(Error::CooperativeCancellationUnavailable(
8295                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
8296            ));
8297        }
8298        let awaiting_canonical_boundary = {
8299            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8300            state.cancellation_delivery_intent.is_some()
8301                || state.cancellation_scope_opening.is_some()
8302                || state
8303                    .scope_delivery
8304                    .as_ref()
8305                    .is_some_and(|replay| replay.intent.is_some())
8306        };
8307        if awaiting_canonical_boundary {
8308            // A private delivery intent never becomes an application error.
8309            // Even a custom future which ignores a pending durable call cannot
8310            // publish terminal commands before canonical delivery and replay.
8311            if let Poll::Ready(Err(error)) = outcome {
8312                if workflow_task_integrity_error(&error) {
8313                    return Err(error);
8314                }
8315            }
8316            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8317        }
8318
8319        match outcome {
8320            Poll::Ready(Ok(result)) => {
8321                ctx.ensure_history_consumed()?;
8322                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8323                let mut commands = ctx.take_commands()?;
8324                commands.push(json!({
8325                    "type": "complete_workflow",
8326                    "result": result
8327                }));
8328                self.message_stream_decision(&ctx, commands)
8329            }
8330            Poll::Ready(Err(error)) => {
8331                if let Error::ContinueAsNew(request) = error {
8332                    let mut commands = ctx.take_commands()?;
8333                    if let Some(command) = ctx.continue_as_new_command(request)? {
8334                        commands.push(command);
8335                    }
8336                    ctx.ensure_history_consumed()?;
8337                    return self.message_stream_decision(&ctx, commands);
8338                }
8339                if workflow_task_integrity_error(&error) {
8340                    // Replay and protocol failures describe the workflow-task
8341                    // decision itself. Preserve their specific failure reason
8342                    // instead of replacing it with the derivative fact that
8343                    // recorded commands remain unconsumed.
8344                    return Err(error);
8345                }
8346                // A handler error must not hide a committed durable command that
8347                // upgraded workflow code no longer consumes.
8348                ctx.ensure_history_consumed()?;
8349                let mut commands = ctx.take_commands()?;
8350                commands.push(workflow_failure_command(
8351                    &error,
8352                    recorded_activity_failure_boundary(&ctx, &error),
8353                ));
8354                self.message_stream_decision(&ctx, commands)
8355            }
8356            Poll::Pending => {
8357                let commands = ctx.take_commands()?;
8358                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8359                    Err(Error::WorkflowYieldedWithoutCommand)
8360                } else {
8361                    self.message_stream_decision(&ctx, commands)
8362                }
8363            }
8364        }
8365    }
8366
8367    fn message_stream_decision(
8368        &self,
8369        ctx: &WorkflowContext,
8370        commands: Vec<Value>,
8371    ) -> Result<WorkflowTaskDecision> {
8372        if !self.cooperative_cancellation_enabled
8373            && commands.iter().any(|command| {
8374                command["type"] == "schedule_activity"
8375                    && command.get("cancellation_policy").is_some()
8376            })
8377        {
8378            return Err(Error::CooperativeCancellationUnavailable(format!(
8379                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8380                self.worker_id,
8381            )));
8382        }
8383        if !self.cooperative_cancellation_enabled
8384            && commands.iter().any(|command| {
8385                command["type"] == "start_child_workflow"
8386                    && (command["parent_close_policy"] == "request_cancellation"
8387                        || matches!(
8388                            command["cancellation_policy"].as_str(),
8389                            Some("try_cancel" | "wait_cancellation_completed")
8390                        ))
8391            })
8392        {
8393            return Err(Error::CooperativeCancellationUnavailable(format!(
8394                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8395                self.worker_id,
8396            )));
8397        }
8398        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
8399        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8400        let scope_delivery = state
8401            .scope_delivery
8402            .as_ref()
8403            .and_then(|replay| replay.intent.clone());
8404        if scope_delivery
8405            .as_ref()
8406            .is_some_and(|intent| commands.len() != intent.command_count)
8407        {
8408            return Err(invalid_recorded_history(
8409                "cancellation_scope_pending_call_escaped",
8410                scope_delivery.as_ref().unwrap().boundary.sequence,
8411                "commands preceding the pending scoped call",
8412                "commands after suspension",
8413                "workflow cannot publish beyond an uncommitted scope delivery",
8414            ));
8415        }
8416        if let Some(opening) = &state.cancellation_scope_opening {
8417            if commands.len() != opening.command_count {
8418                return Err(invalid_recorded_history(
8419                    "cancellation_scope_pending_call_escaped",
8420                    opening.sequence,
8421                    "commands before original scope opening",
8422                    "commands after suspended opening",
8423                    "workflow cannot publish beyond an uncommitted scope opening",
8424                ));
8425            }
8426        }
8427        if state.cancellation_delivery_intent.is_some()
8428            && commands.len() != state.cancellation_delivery_command_count
8429        {
8430            return Err(invalid_recorded_history(
8431                "cooperative_cancellation_pending_call_escaped",
8432                state
8433                    .cancellation_delivery_intent
8434                    .as_ref()
8435                    .expect("pending delivery")
8436                    .sequence,
8437                "only commands preceding the pending cancellation call",
8438                "commands authored after a suspended call",
8439                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
8440            ));
8441        }
8442        Ok(WorkflowTaskDecision {
8443            commands,
8444            message_stream_cursors,
8445            message_stream_waits,
8446            cancellation_delivery: state.cancellation_delivery_intent.clone(),
8447            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
8448            cancellation_scope_delivery: scope_delivery,
8449        })
8450    }
8451
8452    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
8453        if !self.workflows.contains_key(&task.workflow_type) {
8454            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
8455        }
8456
8457        let accepted = task.history_events.iter().rev().find_map(|event| {
8458            (event.event_type == "UpdateAccepted"
8459                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
8460            .then_some(&event.payload)
8461        });
8462        let update_name = accepted
8463            .and_then(|payload| payload.get("update_name"))
8464            .and_then(Value::as_str)
8465            .or(task.update_name.as_deref())
8466            .unwrap_or_default();
8467        let Some(handler) = self
8468            .updates
8469            .get(&task.workflow_type)
8470            .and_then(|handlers| handlers.get(update_name))
8471        else {
8472            return Ok(vec![json!({
8473                "type": "fail_update",
8474                "update_id": update_id,
8475                "message": format!(
8476                    "no update handler is registered for {}.{update_name}",
8477                    task.workflow_type
8478                ),
8479                "exception_type": "UnknownUpdate",
8480                "non_retryable": true,
8481            })]);
8482        };
8483        let arguments = accepted
8484            .and_then(|payload| payload.get("arguments"))
8485            .or(task.arguments.as_ref());
8486        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
8487        let context = QueryContext {
8488            workflow_id: task.workflow_id.clone(),
8489            run_id: task.run_id.clone(),
8490            workflow_type: task.workflow_type.clone(),
8491            run_status: Some("running".to_string()),
8492            workflow_input: Value::Null,
8493            workflow_input_avro_value: AvroValue::Null,
8494            history_events: Arc::new(task.history_events.clone()),
8495            signal_events: Arc::new(Vec::new()),
8496        };
8497        let mut future = handler(context, arguments);
8498        let mut cx = TaskContext::from_waker(noop_waker_ref());
8499
8500        match future.as_mut().poll(&mut cx) {
8501            Poll::Ready(Ok(result)) => Ok(vec![json!({
8502                "type": "complete_update",
8503                "update_id": update_id,
8504                "result": encode_typed_envelope(&result, &task.payload_codec)?,
8505            })]),
8506            Poll::Ready(Err(error)) => Ok(vec![json!({
8507                "type": "fail_update",
8508                "update_id": update_id,
8509                "message": error.to_string(),
8510                "exception_type": "UpdateFailed",
8511                "non_retryable": true,
8512            })]),
8513            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
8514        }
8515    }
8516
8517    #[cfg(test)]
8518    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
8519        self.execute_session_activity_task(task, None).await
8520    }
8521
8522    async fn execute_session_activity_task(
8523        &self,
8524        task: ActivityTask,
8525        worker_session: Option<WorkerSession>,
8526    ) -> Result<AvroValue> {
8527        validate_activity_task_payloads(&task)?;
8528        if worker_session.is_some() {
8529            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
8530                || task
8531                    .activity_attempt_id
8532                    .as_deref()
8533                    .or(task.attempt_id.as_deref())
8534                    .is_none_or(str::is_empty)
8535                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
8536            {
8537                return Err(Error::ActivityExecutionAbandoned(
8538                    "session activity requires this worker's exact immutable claim".into(),
8539                ));
8540            }
8541        }
8542
8543        let handler = self
8544            .activities
8545            .get(&task.activity_type)
8546            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
8547        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8548        let attempt_id = task
8549            .activity_attempt_id
8550            .clone()
8551            .or(task.attempt_id.clone())
8552            .unwrap_or_default();
8553        let lease_owner = task
8554            .lease_owner
8555            .clone()
8556            .unwrap_or_else(|| self.worker_id.clone());
8557        let session = worker_session.clone();
8558        let ctx = ActivityContext {
8559            client: self.client.clone(),
8560            task_id: task.task_id,
8561            activity_attempt_id: attempt_id,
8562            lease_owner,
8563            activity_type: task.activity_type,
8564            attempt_number: task.attempt_number,
8565            task_queue: self.task_queue.clone(),
8566            worker_id: self.worker_id.clone(),
8567            claim_guard: None,
8568            local_heartbeats: None,
8569            worker_session,
8570        };
8571
8572        let callback = handler(ctx, args);
8573        if let Some(session) = session {
8574            tokio::select! {
8575                biased;
8576                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
8577                result = callback => if session.active() { result } else {
8578                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
8579                },
8580            }
8581        } else {
8582            callback.await
8583        }
8584    }
8585}
8586
8587fn poller_result(
8588    kind: &str,
8589    result: std::result::Result<Result<()>, tokio::task::JoinError>,
8590) -> Result<()> {
8591    match result {
8592        Ok(result) => result,
8593        Err(error) => Err(Error::WorkerLoop(format!(
8594            "{kind} poller join error: {error}"
8595        ))),
8596    }
8597}
8598
8599fn optional_poller_result(
8600    kind: &str,
8601    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
8602) -> Result<()> {
8603    match result {
8604        Some(result) => poller_result(kind, result),
8605        None => Ok(()),
8606    }
8607}
8608
8609async fn join_pollers(
8610    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8611    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8612    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8613) -> Result<()> {
8614    let mut first_error = None;
8615
8616    if let Some(handle) = workflow_poller {
8617        if let Err(error) = poller_result("workflow", handle.await) {
8618            first_error.get_or_insert(error);
8619        }
8620    }
8621
8622    if let Some(handle) = activity_poller {
8623        if let Err(error) = poller_result("activity", handle.await) {
8624            first_error.get_or_insert(error);
8625        }
8626    }
8627
8628    if let Some(handle) = query_poller {
8629        if let Err(error) = poller_result("query", handle.await) {
8630            first_error.get_or_insert(error);
8631        }
8632    }
8633
8634    if let Some(error) = first_error {
8635        Err(error)
8636    } else {
8637        Ok(())
8638    }
8639}
8640
8641fn default_worker_id() -> String {
8642    let millis = SystemTime::now()
8643        .duration_since(UNIX_EPOCH)
8644        .unwrap_or_default()
8645        .as_millis();
8646    format!("rust-worker-{}-{millis}", std::process::id())
8647}
8648
8649fn percent_encode_path_segment(segment: &str) -> String {
8650    const HEX: &[u8; 16] = b"0123456789ABCDEF";
8651    let mut encoded = String::with_capacity(segment.len());
8652
8653    for byte in segment.bytes() {
8654        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
8655            encoded.push(char::from(byte));
8656        } else {
8657            encoded.push('%');
8658            encoded.push(char::from(HEX[(byte >> 4) as usize]));
8659            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
8660        }
8661    }
8662
8663    encoded
8664}
8665
8666fn unique_request_id(prefix: &str) -> String {
8667    let nanos = SystemTime::now()
8668        .duration_since(UNIX_EPOCH)
8669        .unwrap_or_default()
8670        .as_nanos();
8671    format!("{prefix}-{}-{nanos}", std::process::id())
8672}
8673
8674#[derive(Debug)]
8675struct QueryTaskExecutionFailure {
8676    reason: String,
8677    message: String,
8678    failure_type: String,
8679}
8680
8681impl QueryTaskExecutionFailure {
8682    fn new(
8683        reason: impl Into<String>,
8684        message: impl Into<String>,
8685        failure_type: impl Into<String>,
8686    ) -> Self {
8687        Self {
8688            reason: reason.into(),
8689            message: message.into(),
8690            failure_type: failure_type.into(),
8691        }
8692    }
8693}
8694
8695/// Typed local state owned by one deterministic workflow invocation.
8696///
8697/// Use [`WorkflowInstance::update`] for the same state transitions during
8698/// ordinary execution and replay. A replayed query receives a detached
8699/// immutable `Arc<S>` rather than this mutation-capable handle.
8700#[derive(Clone, Debug)]
8701pub struct WorkflowInstance<S> {
8702    state: Arc<Mutex<S>>,
8703}
8704
8705impl<S> WorkflowInstance<S> {
8706    fn new(state: S) -> Self {
8707        Self {
8708            state: Arc::new(Mutex::new(state)),
8709        }
8710    }
8711
8712    /// Read the current workflow-instance state without changing it.
8713    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
8714        let state = self
8715            .state
8716            .lock()
8717            .map_err(|_| Error::WorkflowStatePoisoned)?;
8718        Ok(reader(&state))
8719    }
8720
8721    /// Apply one deterministic workflow-instance state transition.
8722    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
8723        let mut state = self
8724            .state
8725            .lock()
8726            .map_err(|_| Error::WorkflowStatePoisoned)?;
8727        Ok(transition(&mut state))
8728    }
8729}
8730
8731impl<S: Clone> WorkflowInstance<S> {
8732    fn snapshot(&self) -> Result<S> {
8733        self.read(Clone::clone)
8734    }
8735}
8736
8737#[derive(Clone, Debug, PartialEq)]
8738pub struct MessageStreamMessage {
8739    pub stream_name: String,
8740    pub message_id: String,
8741    pub position: u64,
8742    pub arguments: Vec<AvroValue>,
8743}
8744
8745#[derive(Clone, Debug)]
8746pub struct MessageStream {
8747    ctx: WorkflowContext,
8748    name: String,
8749}
8750
8751impl MessageStream {
8752    /// Wait for one message, then return a bounded currently-available batch.
8753    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
8754        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
8755            return Err(Error::Codec(format!(
8756                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
8757            )));
8758        }
8759        loop {
8760            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
8761                return Ok(batch);
8762            }
8763
8764            self.ctx.record_message_stream_wait(&self.name)?;
8765            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
8766            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
8767            self.ctx.buffer_message_stream_delivery(arguments)?;
8768            if let Some(sequence) = replay_wait_sequence {
8769                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
8770            }
8771        }
8772    }
8773
8774    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
8775        self.receive(1)
8776            .await?
8777            .into_iter()
8778            .next()
8779            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
8780    }
8781}
8782
8783#[derive(Clone, Debug)]
8784pub struct WorkflowContext {
8785    state: Arc<Mutex<WorkflowState>>,
8786    cancellation_scope_id: String,
8787}
8788
8789fn valid_memo_key(key: &str) -> bool {
8790    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
8791
8792    !key.is_empty()
8793        && key.len() <= 64
8794        && (numeric_candidate.is_empty()
8795            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
8796        && key
8797            .bytes()
8798            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
8799}
8800
8801fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
8802    BASE64
8803        .decode(encode_avro_value(value)?.blob)
8804        .map(|bytes| bytes.len())
8805        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
8806}
8807
8808fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
8809    let AvroValue::Map(entries) = value else {
8810        return Err(Error::InvalidMemoUpdate(
8811            "entries must serialize to an Avro string-keyed map".to_string(),
8812        ));
8813    };
8814    if require_entries && entries.is_empty() {
8815        return Err(Error::InvalidMemoUpdate(
8816            "at least one entry is required".to_string(),
8817        ));
8818    }
8819    if entries.len() > MAX_MEMO_ENTRIES {
8820        return Err(Error::InvalidMemoUpdate(format!(
8821            "at most {MAX_MEMO_ENTRIES} entries are allowed"
8822        )));
8823    }
8824
8825    for (key, value) in &entries {
8826        if !valid_memo_key(&key) {
8827            return Err(Error::InvalidMemoUpdate(
8828                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
8829            ));
8830        }
8831        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
8832            return Err(Error::InvalidMemoUpdate(format!(
8833                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
8834            )));
8835        }
8836    }
8837
8838    let value = AvroValue::Map(entries);
8839    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
8840        return Err(Error::InvalidMemoUpdate(format!(
8841            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
8842        )));
8843    }
8844    Ok(value)
8845}
8846
8847fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
8848    let object = envelope.as_object().ok_or_else(|| {
8849        Error::InvalidMemoUpdate(
8850            "history field must use the public {codec, blob} payload envelope".to_string(),
8851        )
8852    })?;
8853    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
8854        return Err(Error::InvalidMemoUpdate(
8855            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
8856        ));
8857    }
8858
8859    canonical_memo_entries(
8860        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
8861        require_entries,
8862    )
8863}
8864
8865impl WorkflowContext {
8866    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
8867        let name = name.into();
8868        if name.is_empty()
8869            || name.len() > 128
8870            || !name.bytes().all(|byte| {
8871                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
8872            })
8873        {
8874            return Err(Error::Codec(
8875                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
8876                    .to_string(),
8877            ));
8878        }
8879        Ok(MessageStream {
8880            ctx: self.clone(),
8881            name,
8882        })
8883    }
8884
8885    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
8886        let mut state = self
8887            .state
8888            .lock()
8889            .map_err(|_| Error::WorkflowStatePoisoned)?;
8890        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
8891        state
8892            .message_stream_waits
8893            .insert(name.to_string(), position);
8894        Ok(())
8895    }
8896
8897    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
8898        let mut state = self
8899            .state
8900            .lock()
8901            .map_err(|_| Error::WorkflowStatePoisoned)?;
8902        let cursor = state
8903            .message_stream_cursors
8904            .get(&message.stream_name)
8905            .copied()
8906            .unwrap_or(0);
8907        if message.position <= cursor {
8908            return Ok(());
8909        }
8910        let pending = state
8911            .message_stream_messages
8912            .entry(message.stream_name.clone())
8913            .or_default();
8914        if pending.iter().any(|candidate| {
8915            candidate.position == message.position || candidate.message_id == message.message_id
8916        }) {
8917            return Ok(());
8918        }
8919        pending.push(message);
8920        pending.sort_by_key(|candidate| candidate.position);
8921        Ok(())
8922    }
8923
8924    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
8925        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
8926            match delivery {
8927                MessageStreamDelivery::Message(message) => {
8928                    let stream_name = message.stream_name.clone();
8929                    self.buffer_message_stream(message)?;
8930                    return Ok(Some(stream_name));
8931                }
8932                MessageStreamDelivery::Cursor {
8933                    stream_name,
8934                    through_position,
8935                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
8936            }
8937        }
8938        Ok(None)
8939    }
8940
8941    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
8942        let state = self
8943            .state
8944            .lock()
8945            .map_err(|_| Error::WorkflowStatePoisoned)?;
8946        Ok(match state.recorded_commands.get(state.command_cursor) {
8947            Some(RecordedCommand::SignalWait {
8948                sequence,
8949                signal_name,
8950                ..
8951            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
8952            _ => None,
8953        })
8954    }
8955
8956    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
8957        let (history, payload_codec) = {
8958            let state = self
8959                .state
8960                .lock()
8961                .map_err(|_| Error::WorkflowStatePoisoned)?;
8962            (
8963                Arc::clone(&state.history_events),
8964                state.payload_codec.clone(),
8965            )
8966        };
8967
8968        let Some(opened_index) = history.iter().position(|event| {
8969            event.event_type == "SignalWaitOpened"
8970                && durable_event_sequence(event) == Some(wait_sequence)
8971                && event.payload.get("signal_name").and_then(Value::as_str)
8972                    == Some(MESSAGE_STREAM_SIGNAL)
8973        }) else {
8974            return Ok(());
8975        };
8976        let boundary_index = history
8977            .iter()
8978            .enumerate()
8979            .skip(opened_index + 1)
8980            .find_map(|(index, event)| {
8981                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
8982                    && is_authored_command_open_event(event))
8983                .then_some(index)
8984            })
8985            .unwrap_or(history.len());
8986
8987        for event in history[opened_index + 1..boundary_index]
8988            .iter()
8989            .filter(|event| {
8990                event.event_type == "SignalReceived"
8991                    && event.payload.get("signal_name").and_then(Value::as_str)
8992                        == Some(MESSAGE_STREAM_SIGNAL)
8993            })
8994        {
8995            let arguments = decode_signal_event_arguments(event, &payload_codec)?
8996                .into_iter()
8997                .map(AvroValue::into_json)
8998                .collect::<Result<Vec<_>>>()?;
8999            self.buffer_message_stream_delivery(arguments)?;
9000        }
9001        Ok(())
9002    }
9003
9004    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9005        let mut state = self
9006            .state
9007            .lock()
9008            .map_err(|_| Error::WorkflowStatePoisoned)?;
9009        let cursor = state
9010            .message_stream_cursors
9011            .entry(name.to_string())
9012            .or_default();
9013        *cursor = (*cursor).max(through_position);
9014        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9015            pending.retain(|message| message.position > through_position);
9016        }
9017        Ok(())
9018    }
9019
9020    fn take_message_stream_batch(
9021        &self,
9022        name: &str,
9023        max_items: usize,
9024    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9025        let mut state = self
9026            .state
9027            .lock()
9028            .map_err(|_| Error::WorkflowStatePoisoned)?;
9029        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9030        let pending = state
9031            .message_stream_messages
9032            .entry(name.to_string())
9033            .or_default();
9034        let count = contiguous_message_stream_count(pending, cursor, max_items);
9035        if count == 0 {
9036            return Ok(None);
9037        }
9038        let batch = pending.drain(..count).collect::<Vec<_>>();
9039        let position = batch.last().map(|message| message.position).unwrap_or(0);
9040        state
9041            .message_stream_cursors
9042            .insert(name.to_string(), position);
9043        state.message_stream_waits.remove(name);
9044        Ok(Some(batch))
9045    }
9046
9047    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9048        let state = self
9049            .state
9050            .lock()
9051            .map_err(|_| Error::WorkflowStatePoisoned)?;
9052        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9053        cursors.sort_by_key(|(name, _)| *name);
9054        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9055        waits.sort_by_key(|(name, _)| *name);
9056        Ok((
9057            cursors
9058                .into_iter()
9059                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9060                .collect(),
9061            waits
9062                .into_iter()
9063                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9064                .collect(),
9065        ))
9066    }
9067    /// Identity of the parent workflow currently being replayed.
9068    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9069        let state = self
9070            .state
9071            .lock()
9072            .map_err(|_| Error::WorkflowStatePoisoned)?;
9073        Ok(WorkflowIdentity {
9074            workflow_id: state.workflow_id.clone(),
9075            run_id: state.run_id.clone(),
9076        })
9077    }
9078
9079    /// Return the server-published history budget for this workflow task.
9080    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9081        let state = self
9082            .state
9083            .lock()
9084            .map_err(|_| Error::WorkflowStatePoisoned)?;
9085        Ok(state.history_budget.clone())
9086    }
9087
9088    /// Continue this workflow instance as a fresh run with replacement arguments.
9089    ///
9090    /// Return this value directly from the workflow handler. The worker converts
9091    /// it to the terminal protocol command only after replay has consumed every
9092    /// recorded durable command.
9093    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9094        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9095    }
9096
9097    /// Continue as new with optional workflow-type and task-queue overrides.
9098    pub fn continue_as_new_with_options<T: Serialize>(
9099        &self,
9100        options: ContinueAsNewOptions,
9101        args: T,
9102    ) -> Result<Value> {
9103        options.validate()?;
9104        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9105            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9106            options,
9107        }))
9108    }
9109
9110    pub fn activity<T: Serialize>(
9111        &self,
9112        activity_type: impl Into<String>,
9113        args: T,
9114    ) -> ActivityCall {
9115        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9116    }
9117
9118    pub fn activity_on_queue<T, Q>(
9119        &self,
9120        activity_type: impl Into<String>,
9121        task_queue: Option<Q>,
9122        args: T,
9123    ) -> ActivityCall
9124    where
9125        T: Serialize,
9126        Q: Into<String>,
9127    {
9128        let mut options = ActivityOptions::new();
9129        options.task_queue = task_queue.map(Into::into);
9130        self.activity_with_options(activity_type, options, args)
9131    }
9132
9133    /// Schedule one durable activity with retry, routing, and timeout options.
9134    ///
9135    /// Options are validated before the command is emitted. Once the command is
9136    /// recorded, replay consumes the same activity lifecycle at this command
9137    /// position and never emits a duplicate schedule.
9138    ///
9139    /// ```no_run
9140    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9141    /// # use std::time::Duration;
9142    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9143    /// let result = ctx
9144    ///     .activity_with_options(
9145    ///         "charge-card",
9146    ///         ActivityOptions::new()
9147    ///             .task_queue("payments")
9148    ///             .retry_policy(
9149    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9150    ///                     Duration::from_secs(1),
9151    ///                     2,
9152    ///                     Some(Duration::from_secs(30)),
9153    ///                 ),
9154    ///             )
9155    ///             .start_to_close_timeout(Duration::from_secs(60))
9156    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9157    ///             .heartbeat_timeout(Duration::from_secs(15)),
9158    ///         json!([{"order_id": "order-42"}]),
9159    ///     )
9160    ///     .await;
9161    /// match result {
9162    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9163    ///         "reason": failure.reason,
9164    ///         "timeout_kind": failure.timeout_kind,
9165    ///     })),
9166    ///     other => other,
9167    /// }
9168    /// # }
9169    /// ```
9170    pub fn activity_with_options<T: Serialize>(
9171        &self,
9172        activity_type: impl Into<String>,
9173        options: ActivityOptions,
9174        args: T,
9175    ) -> ActivityCall {
9176        ActivityCall {
9177            ctx: self.clone(),
9178            activity_type: activity_type.into(),
9179            options,
9180            worker_session: None,
9181            args: Some(AvroValue::from_serialize(&args)),
9182            scheduled: false,
9183            local: false,
9184            local_result: None,
9185            parallel_group_path: Vec::new(),
9186        }
9187    }
9188
9189    pub async fn activity_avro_value<T: Serialize>(
9190        &self,
9191        activity_type: impl Into<String>,
9192        args: T,
9193    ) -> Result<AvroValue> {
9194        let mut call = self.activity(activity_type, args);
9195        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9196    }
9197
9198    pub async fn activity_avro_value_with_options<T: Serialize>(
9199        &self,
9200        activity_type: impl Into<String>,
9201        options: ActivityOptions,
9202        args: T,
9203    ) -> Result<AvroValue> {
9204        let mut call = self.activity_with_options(activity_type, options, args);
9205        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9206    }
9207
9208    /// Schedule an activity with a Serde request and decode its Serde result.
9209    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9210    where
9211        I: Serialize,
9212        O: DeserializeOwned,
9213    {
9214        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9215            .await
9216    }
9217
9218    /// Schedule an activity with options and decode its result into `O`.
9219    ///
9220    /// Both directions use the fixed Avro Value codec. In particular, this
9221    /// method does not deserialize the JSON-safe inspection projection returned
9222    /// by the dynamic [`ActivityCall`] future.
9223    pub async fn activity_typed_with_options<I, O>(
9224        &self,
9225        activity_type: impl Into<String>,
9226        options: ActivityOptions,
9227        args: I,
9228    ) -> Result<O>
9229    where
9230        I: Serialize,
9231        O: DeserializeOwned,
9232    {
9233        let activity_type = activity_type.into();
9234        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9235            handler_type_error::<I>(
9236                HandlerKind::Activity,
9237                &activity_type,
9238                HandlerValueKind::Input,
9239                error.to_string(),
9240            )
9241        });
9242        let mut call = ActivityCall {
9243            ctx: self.clone(),
9244            activity_type: activity_type.clone(),
9245            options,
9246            worker_session: None,
9247            args: Some(encoded),
9248            scheduled: false,
9249            local: false,
9250            local_result: None,
9251            parallel_group_path: Vec::new(),
9252        };
9253        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9254        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9255    }
9256
9257    /// Schedule and join a deterministic activity/child/timer group.
9258    ///
9259    /// Nested groups retain their input shape. Every durable leaf is scheduled
9260    /// before this future yields, results are assembled by declaration order,
9261    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9262    /// declaration path, stable group metadata, and completed siblings.
9263    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9264        ParallelCall::new(self.clone(), operations)
9265    }
9266
9267    /// Alias for [`WorkflowContext::parallel`].
9268    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9269        self.parallel(operations)
9270    }
9271
9272    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
9273    pub async fn parallel_avro_value(
9274        &self,
9275        operations: Vec<ParallelOperation>,
9276    ) -> Result<Vec<ParallelAvroResult>> {
9277        let mut call = self.parallel(operations);
9278        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9279    }
9280
9281    /// Start every durable operation and resume from the one winner persisted
9282    /// by Server. Non-winning operations continue and remain addressable.
9283    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
9284        let operations = operations
9285            .into_iter()
9286            .enumerate()
9287            .map(|(index, operation)| (SelectionKey::Index(index), operation))
9288            .collect();
9289        SelectCall::new(self.clone(), operations)
9290    }
9291
9292    /// Named-key variant of [`WorkflowContext::select`].
9293    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
9294    where
9295        K: Into<SelectionKey>,
9296    {
9297        SelectCall::new(
9298            self.clone(),
9299            operations
9300                .into_iter()
9301                .map(|(key, operation)| (key.into(), operation))
9302                .collect(),
9303        )
9304    }
9305
9306    /// Create a workflow-local deterministic compensation registry.
9307    pub fn saga(&self) -> Saga {
9308        Saga::new(self.clone())
9309    }
9310
9311    /// Whether cancellation has reached this replay's authored boundary.
9312    ///
9313    /// Server's current `/cancel` route is terminal and does not set this flag.
9314    /// A canonical service request remains pending until its committed delivery
9315    /// is consumed. Request observation alone does not authorize an exception.
9316    pub fn is_cancellation_requested(&self) -> Result<bool> {
9317        let state = self
9318            .state
9319            .lock()
9320            .map_err(|_| Error::WorkflowStatePoisoned)?;
9321        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9322            return Ok(state
9323                .scope_delivery
9324                .as_ref()
9325                .unwrap()
9326                .contexts
9327                .contains_key(&self.cancellation_scope_id));
9328        }
9329        Ok(state.cancel_requested
9330            || state
9331                .scope_delivery
9332                .as_ref()
9333                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
9334    }
9335
9336    /// Raise a typed cooperative cancellation at an author-controlled point.
9337    ///
9338    /// Passing this result to [`Saga::finish`] compensates already registered
9339    /// forward steps before the cancellation remains the initiating outcome.
9340    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
9341        let mut state = self
9342            .state
9343            .lock()
9344            .map_err(|_| Error::WorkflowStatePoisoned)?;
9345        if state.cancellation_shield_depth == 0 {
9346            if let Some(replay) = &state.scope_delivery {
9347                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
9348                    let delivered = replay
9349                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
9350                        .ok_or_else(|| {
9351                            Error::InvalidCooperativeCancellation(
9352                                "scoped request lacks its consumed original delivery".into(),
9353                            )
9354                        })?;
9355                    return Err(Error::CancellationScopeRequested(
9356                        CancellationScopeRequested {
9357                            context: context
9358                                .clone()
9359                                .with_replay(Some(Arc::downgrade(&self.state))),
9360                            delivery: delivered.boundary.clone(),
9361                        },
9362                    ));
9363                }
9364            }
9365        }
9366        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9367            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9368                return Ok(());
9369            }
9370            return Err(state.cancellation_error());
9371        }
9372        Ok(())
9373    }
9374
9375    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9376        SignalCall {
9377            ctx: self.clone(),
9378            signal_name: signal_name.into(),
9379            runtime_reserved_allowed: false,
9380            opened_wait: false,
9381            matched_pending: false,
9382            parallel_group_path: Vec::new(),
9383        }
9384    }
9385
9386    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9387        SignalCall {
9388            ctx: self.clone(),
9389            signal_name: signal_name.into(),
9390            runtime_reserved_allowed: true,
9391            opened_wait: false,
9392            matched_pending: false,
9393            parallel_group_path: Vec::new(),
9394        }
9395    }
9396
9397    pub async fn wait_signal_avro_value(
9398        &self,
9399        signal_name: impl Into<String>,
9400    ) -> Result<Vec<AvroValue>> {
9401        let mut call = self.wait_signal(signal_name);
9402        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9403    }
9404
9405    /// Return every committed signal argument list with the given name.
9406    ///
9407    /// This history-backed view is deterministic and is intended for
9408    /// condition predicates that must be re-evaluated after a signal while the
9409    /// workflow is blocked on [`WorkflowContext::wait_condition`].
9410    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
9411        self.signals_avro_value(signal_name)?
9412            .into_iter()
9413            .map(|arguments| {
9414                arguments
9415                    .into_iter()
9416                    .map(AvroValue::into_json)
9417                    .collect::<Result<Vec<_>>>()
9418            })
9419            .collect()
9420    }
9421
9422    /// Lossless fixed Avro Value view of committed signals with the given name.
9423    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9424        let state = self
9425            .state
9426            .lock()
9427            .map_err(|_| Error::WorkflowStatePoisoned)?;
9428        state
9429            .history_events
9430            .iter()
9431            .filter(|event| {
9432                event.event_type == "SignalReceived"
9433                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
9434            })
9435            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
9436            .collect()
9437    }
9438
9439    /// Return every committed update argument list with the given name.
9440    ///
9441    /// Accepted and applied records for the same update ID are de-duplicated.
9442    /// A Server task created after an update therefore replays the workflow and
9443    /// re-evaluates an open condition without application polling.
9444    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
9445        self.updates_avro_value(update_name)?
9446            .into_iter()
9447            .map(|arguments| {
9448                arguments
9449                    .into_iter()
9450                    .map(AvroValue::into_json)
9451                    .collect::<Result<Vec<_>>>()
9452            })
9453            .collect()
9454    }
9455
9456    /// Lossless fixed Avro Value view of committed updates with the given name.
9457    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9458        let state = self
9459            .state
9460            .lock()
9461            .map_err(|_| Error::WorkflowStatePoisoned)?;
9462        let mut seen = Vec::new();
9463        let mut updates = Vec::new();
9464        for event in state.history_events.iter() {
9465            if !matches!(
9466                event.event_type.as_str(),
9467                "UpdateAccepted" | "UpdateApplied"
9468            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
9469                || event.payload.get("arguments").is_none()
9470            {
9471                continue;
9472            }
9473            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
9474                if seen.iter().any(|recorded| recorded == update_id) {
9475                    continue;
9476                }
9477                seen.push(update_id.to_string());
9478            }
9479            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
9480        }
9481        Ok(updates)
9482    }
9483
9484    /// Wait for a deterministic predicate to become true or for its durable
9485    /// timeout to elapse.
9486    ///
9487    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
9488    /// predicate tokens automatically change the recorded definition
9489    /// fingerprint. Direct callers must provide an equally stable identity in
9490    /// [`ConditionWaitOptions`].
9491    pub fn wait_condition<F>(
9492        &self,
9493        options: ConditionWaitOptions,
9494        predicate: F,
9495    ) -> ConditionWaitCall
9496    where
9497        F: Fn() -> Result<bool> + Send + 'static,
9498    {
9499        ConditionWaitCall {
9500            ctx: self.clone(),
9501            options,
9502            predicate: Box::new(predicate),
9503            occurrence_id: None,
9504            opened_wait: false,
9505            parallel_group_path: Vec::new(),
9506        }
9507    }
9508
9509    /// Wait for server-backed durable time without blocking the worker executor.
9510    ///
9511    /// Polling this future emits one `start_timer` command and yields. The
9512    /// server records the deadline, so neither worker nor server restarts reset
9513    /// the wait. Replay resolves the future only from a `TimerScheduled` and
9514    /// `TimerFired` pair at the same position in the shared durable-command
9515    /// stream, with matching sequence, timer identity, and delay. Sub-second
9516    /// durations round up because protocol deadlines use whole seconds.
9517    ///
9518    /// ```no_run
9519    /// # use durable_workflow::{json, Client, Worker};
9520    /// # use std::time::Duration;
9521    /// # fn configure(client: Client) {
9522    /// let mut worker = Worker::new(client, "rust-workers");
9523    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
9524    ///     ctx.sleep(Duration::from_secs(5)).await?;
9525    ///     Ok(json!({"status": "timer fired"}))
9526    /// });
9527    /// # }
9528    /// ```
9529    pub fn sleep(&self, duration: Duration) -> TimerCall {
9530        let delay_seconds = duration
9531            .as_secs()
9532            .checked_add(u64::from(duration.subsec_nanos() > 0));
9533        TimerCall {
9534            ctx: self.clone(),
9535            delay_seconds,
9536            scheduled: false,
9537            matched_pending: false,
9538            parallel_group_path: Vec::new(),
9539        }
9540    }
9541
9542    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
9543    pub fn start_timer(&self, duration: Duration) -> TimerCall {
9544        self.sleep(duration)
9545    }
9546
9547    /// Evaluate a non-deterministic callback once and durably record its typed value.
9548    ///
9549    /// On replay the callback is not invoked: the value is decoded from the
9550    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
9551    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
9552    /// small values that must remain fixed for the lifetime of a workflow run.
9553    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
9554    where
9555        T: Serialize + DeserializeOwned,
9556        F: FnOnce() -> T,
9557    {
9558        {
9559            let mut state = self
9560                .state
9561                .lock()
9562                .map_err(|_| Error::WorkflowStatePoisoned)?;
9563            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9564                return match recorded {
9565                    RecordedCommand::SideEffect { sequence, value } => {
9566                        state.command_cursor += 1;
9567                        value.deserialize().map_err(|error| {
9568                            Error::NonDeterministicReplay(ReplayFailure::new(
9569                                "side_effect_type_mismatch",
9570                                Some(sequence),
9571                                Some(std::any::type_name::<T>().to_string()),
9572                                Some(error.to_string()),
9573                                "recorded side-effect value is incompatible with the requested Rust type",
9574                            ))
9575                        })
9576                    }
9577                    other => Err(command_mismatch(&other, "side effect")),
9578                };
9579            }
9580        }
9581
9582        let value = callback();
9583        let avro_value = AvroValue::from_serialize(&value)?;
9584        let mut state = self
9585            .state
9586            .lock()
9587            .map_err(|_| Error::WorkflowStatePoisoned)?;
9588        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
9589        state.commands.push(json!({
9590            "type": "record_side_effect",
9591            "result": result,
9592        }));
9593        Ok(value)
9594    }
9595
9596    /// Record or replay a lossless fixed Avro Value side effect.
9597    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
9598    where
9599        F: FnOnce() -> AvroValue,
9600    {
9601        {
9602            let mut state = self
9603                .state
9604                .lock()
9605                .map_err(|_| Error::WorkflowStatePoisoned)?;
9606            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9607                return match recorded {
9608                    RecordedCommand::SideEffect { value, .. } => {
9609                        state.command_cursor += 1;
9610                        Ok(value)
9611                    }
9612                    other => Err(command_mismatch(&other, "side effect")),
9613                };
9614            }
9615        }
9616
9617        let value = callback();
9618        let mut state = self
9619            .state
9620            .lock()
9621            .map_err(|_| Error::WorkflowStatePoisoned)?;
9622        let result = encode_typed_envelope(&value, &state.payload_codec)?;
9623        state.commands.push(json!({
9624            "type": "record_side_effect",
9625            "result": result,
9626        }));
9627        Ok(value)
9628    }
9629
9630    /// Append output items at a deterministic workflow command boundary.
9631    ///
9632    /// Stable idempotency keys are derived from the server-provided durable
9633    /// workflow command identity, command ordinal, and item index. Replay
9634    /// consumes the recorded side effect and never emits another append.
9635    pub fn append_workflow_stream(
9636        &self,
9637        stream_name: impl Into<String>,
9638        items: &[WorkflowStreamAppendItem],
9639        max_pending_items: Option<u64>,
9640    ) -> Result<()> {
9641        if items.is_empty() {
9642            return Err(Error::Codec(
9643                "workflow_stream_items_empty: append requires at least one item".to_string(),
9644            ));
9645        }
9646        if max_pending_items == Some(0) {
9647            return Err(Error::Codec(
9648                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
9649                    .to_string(),
9650            ));
9651        }
9652        let stream_name = stream_name.into();
9653        if stream_name.is_empty() {
9654            return Err(Error::Codec(
9655                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9656            ));
9657        }
9658
9659        let mut state = self
9660            .state
9661            .lock()
9662            .map_err(|_| Error::WorkflowStatePoisoned)?;
9663        let command_ordinal = state.workflow_stream_command_counter;
9664        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9665            state.workflow_stream_command_counter += 1;
9666            return match recorded {
9667                RecordedCommand::SideEffect { .. } => {
9668                    state.command_cursor += 1;
9669                    Ok(())
9670                }
9671                other => Err(command_mismatch(&other, "workflow stream append")),
9672            };
9673        }
9674
9675        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9676        state.workflow_stream_command_counter += 1;
9677        let wire_items = items
9678            .iter()
9679            .enumerate()
9680            .map(|(item_index, item)| {
9681                item.wire_value(Some(format!(
9682                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
9683                )))
9684            })
9685            .collect::<Vec<_>>();
9686        let mut directive = json!({
9687            "operation": "append",
9688            "stream_name": stream_name,
9689            "command_identity": identity,
9690            "command_ordinal": command_ordinal,
9691            "items": wire_items,
9692        });
9693        if let Some(max_pending_items) = max_pending_items {
9694            directive["max_pending_items"] = json!(max_pending_items);
9695        }
9696        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9697        state.commands.push(json!({
9698            "type": "record_side_effect",
9699            "result": result,
9700            "workflow_stream": directive,
9701        }));
9702        Ok(())
9703    }
9704
9705    /// Close a run-scoped output stream at a deterministic command boundary.
9706    pub fn close_workflow_stream(
9707        &self,
9708        stream_name: impl Into<String>,
9709        retention_seconds: Option<u64>,
9710    ) -> Result<()> {
9711        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
9712    }
9713
9714    /// Mark a run-scoped output stream errored at a deterministic command boundary.
9715    pub fn error_workflow_stream(
9716        &self,
9717        stream_name: impl Into<String>,
9718        error_reason: impl Into<String>,
9719        retention_seconds: Option<u64>,
9720    ) -> Result<()> {
9721        let error_reason = error_reason.into();
9722        if error_reason.is_empty() {
9723            return Err(Error::Codec(
9724                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
9725            ));
9726        }
9727        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
9728    }
9729
9730    fn finish_workflow_stream(
9731        &self,
9732        stream_name: String,
9733        error_reason: Option<String>,
9734        retention_seconds: Option<u64>,
9735    ) -> Result<()> {
9736        if stream_name.is_empty() {
9737            return Err(Error::Codec(
9738                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9739            ));
9740        }
9741        if retention_seconds == Some(0) {
9742            return Err(Error::Codec(
9743                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
9744            ));
9745        }
9746        let mut state = self
9747            .state
9748            .lock()
9749            .map_err(|_| Error::WorkflowStatePoisoned)?;
9750        let command_ordinal = state.workflow_stream_command_counter;
9751        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9752            state.workflow_stream_command_counter += 1;
9753            return match recorded {
9754                RecordedCommand::SideEffect { .. } => {
9755                    state.command_cursor += 1;
9756                    Ok(())
9757                }
9758                other => Err(command_mismatch(&other, "workflow stream close")),
9759            };
9760        }
9761        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9762        state.workflow_stream_command_counter += 1;
9763        let mut directive = json!({
9764            "operation": if error_reason.is_some() { "error" } else { "close" },
9765            "stream_name": stream_name,
9766            "command_identity": identity,
9767            "command_ordinal": command_ordinal,
9768        });
9769        if let Some(error_reason) = error_reason {
9770            directive["error_reason"] = json!(error_reason);
9771        }
9772        if let Some(retention_seconds) = retention_seconds {
9773            directive["retention_seconds"] = json!(retention_seconds);
9774        }
9775        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9776        state.commands.push(json!({
9777            "type": "record_side_effect",
9778            "result": result,
9779            "workflow_stream": directive,
9780        }));
9781        Ok(())
9782    }
9783
9784    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
9785        let identity = state.workflow_command_identity.as_str();
9786        if identity.is_empty() {
9787            return Err(Error::MissingWorkflowCommandIdentity);
9788        }
9789        Ok(identity)
9790    }
9791
9792    /// Validate, emit, or replay a typed workflow search-attribute update.
9793    ///
9794    /// The command is non-blocking within a workflow decision, but its
9795    /// `SearchAttributesUpserted` event occupies the same deterministic command
9796    /// stream as activities, timers, conditions, and other durable operations.
9797    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
9798        update.validate()?;
9799        let (attributes, attribute_types) = update.into_wire_parts();
9800        let mut state = self
9801            .state
9802            .lock()
9803            .map_err(|_| Error::WorkflowStatePoisoned)?;
9804
9805        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9806            return match recorded {
9807                RecordedCommand::SearchAttributes {
9808                    sequence,
9809                    attributes: recorded_attributes,
9810                    attribute_types: recorded_attribute_types,
9811                } => {
9812                    if recorded_attributes != attributes {
9813                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9814                            "search_attribute_value_mismatch",
9815                            Some(sequence),
9816                            Some(recorded_attributes.to_string()),
9817                            Some(attributes.to_string()),
9818                            "search-attribute values differ from the recorded durable command",
9819                        )));
9820                    }
9821                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
9822                        if recorded_types != attribute_types {
9823                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9824                                "search_attribute_type_mismatch",
9825                                Some(sequence),
9826                                Some(json!(recorded_types).to_string()),
9827                                Some(json!(attribute_types).to_string()),
9828                                "search-attribute declared types differ from the recorded durable command",
9829                            )));
9830                        }
9831                    }
9832                    state.command_cursor += 1;
9833                    Ok(())
9834                }
9835                other => Err(command_mismatch(&other, "search-attribute update")),
9836            };
9837        }
9838
9839        let mut command = serde_json::Map::from_iter([
9840            ("type".to_string(), json!("upsert_search_attributes")),
9841            ("attributes".to_string(), attributes),
9842        ]);
9843        if !attribute_types.is_empty() {
9844            command.insert("attribute_types".to_string(), json!(attribute_types));
9845        }
9846        state.commands.push(Value::Object(command));
9847        Ok(())
9848    }
9849
9850    /// Record a UUIDv4 once and return the same UUID on every replay.
9851    pub fn uuid_v4(&self) -> Result<Uuid> {
9852        self.side_effect(Uuid::new_v4)
9853    }
9854
9855    /// Select the newest supported version for a change, or replay the version
9856    /// already committed for that stable change ID.
9857    pub fn get_version(
9858        &self,
9859        change_id: impl Into<String>,
9860        min_supported: i32,
9861        max_supported: i32,
9862    ) -> Result<i32> {
9863        let change_id = change_id.into();
9864        if change_id.trim().is_empty() {
9865            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9866                "version_change_id_invalid",
9867                None,
9868                Some("non-empty change ID".to_string()),
9869                Some(change_id),
9870                "version markers require a stable non-empty change ID",
9871            )));
9872        }
9873        if min_supported > max_supported {
9874            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9875                "version_range_invalid",
9876                None,
9877                Some("min_supported <= max_supported".to_string()),
9878                Some(format!("{min_supported}..={max_supported}")),
9879                "version marker supported range is invalid",
9880            )));
9881        }
9882
9883        let mut state = self
9884            .state
9885            .lock()
9886            .map_err(|_| Error::WorkflowStatePoisoned)?;
9887        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
9888            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
9889            return Ok(version);
9890        }
9891
9892        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9893            return match recorded {
9894                RecordedCommand::VersionMarker {
9895                    sequence,
9896                    change_id: recorded_change_id,
9897                    version,
9898                    ..
9899                } => {
9900                    if recorded_change_id != change_id {
9901                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9902                            "version_change_id_mismatch",
9903                            Some(sequence),
9904                            Some(recorded_change_id),
9905                            Some(change_id),
9906                            "recorded version marker change ID differs from current workflow code",
9907                        )));
9908                    }
9909                    ensure_version_supported(
9910                        &change_id,
9911                        version,
9912                        min_supported,
9913                        max_supported,
9914                        sequence,
9915                    )?;
9916                    state.command_cursor += 1;
9917                    state.version_markers.insert(change_id, (version, sequence));
9918                    Ok(version)
9919                }
9920                other => Err(command_mismatch(
9921                    &other,
9922                    format!("version marker:{change_id}"),
9923                )),
9924            };
9925        }
9926
9927        let version = max_supported;
9928        state.commands.push(json!({
9929            "type": "record_version_marker",
9930            "change_id": change_id,
9931            "version": version,
9932            "min_supported": min_supported,
9933            "max_supported": max_supported,
9934        }));
9935        // Sequence numbers are assigned by the server. Zero identifies a marker
9936        // selected in this uncommitted decision batch for duplicate-call checks.
9937        state.version_markers.insert(change_id, (version, 0));
9938        Ok(version)
9939    }
9940
9941    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
9942    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
9943        Ok(self.get_version(change_id, -1, 1)? == 1)
9944    }
9945
9946    /// Keep a patch marker in history after the legacy branch has been removed.
9947    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
9948        self.get_version(change_id, -1, 1).map(|_| ())
9949    }
9950
9951    /// Merge non-indexed workflow memo metadata through durable history.
9952    ///
9953    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
9954    /// public Avro payload envelope consumed by Server and Cloud runtimes.
9955    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
9956        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
9957        let mut state = self
9958            .state
9959            .lock()
9960            .map_err(|_| Error::WorkflowStatePoisoned)?;
9961
9962        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9963            return match recorded {
9964                RecordedCommand::Memo {
9965                    sequence,
9966                    entries: recorded_entries,
9967                } => {
9968                    if recorded_entries != entries {
9969                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9970                            "memo_update_mismatch",
9971                            Some(sequence),
9972                            Some(format!("{recorded_entries:?}")),
9973                            Some(format!("{entries:?}")),
9974                            "recorded memo entries differ from the current workflow update",
9975                        )));
9976                    }
9977                    state.command_cursor += 1;
9978                    Ok(())
9979                }
9980                other => Err(command_mismatch(&other, "memo upsert")),
9981            };
9982        }
9983
9984        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
9985        state.commands.push(json!({
9986            "type": "upsert_memo",
9987            "entries": entries_envelope,
9988        }));
9989        Ok(())
9990    }
9991
9992    /// Start a named durable child on an explicit queue and await its result.
9993    ///
9994    /// The command is recorded in the parent's sequence-ordered durable command
9995    /// stream. Replay keeps a scheduled child pending without emitting another
9996    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
9997    /// values preserve the history payload codec and include both sides of the
9998    /// durable relationship; failures are returned as
9999    /// [`Error::ChildWorkflowFailed`].
10000    ///
10001    /// ```no_run
10002    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10003    /// # fn configure(client: Client) {
10004    /// let mut worker = Worker::new(client, "parent-workers");
10005    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10006    ///     let child = ctx
10007    ///         .start_child_workflow(
10008    ///             "fulfil-order",
10009    ///             ChildWorkflowOptions::new("fulfilment-workers")
10010    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10011    ///             json!([{"order_id": "order-42"}]),
10012    ///         )
10013    ///         .await?;
10014    ///     Ok(child.result)
10015    /// });
10016    /// # }
10017    /// ```
10018    pub fn start_child_workflow<T: Serialize>(
10019        &self,
10020        workflow_type: impl Into<String>,
10021        options: ChildWorkflowOptions,
10022        args: T,
10023    ) -> ChildWorkflowCall {
10024        ChildWorkflowCall {
10025            ctx: self.clone(),
10026            workflow_type: workflow_type.into(),
10027            options,
10028            args: Some(AvroValue::from_serialize(&args)),
10029            scheduled: false,
10030            matched_pending: false,
10031            parallel_group_path: Vec::new(),
10032        }
10033    }
10034
10035    pub async fn start_child_workflow_avro_value<T: Serialize>(
10036        &self,
10037        workflow_type: impl Into<String>,
10038        options: ChildWorkflowOptions,
10039        args: T,
10040    ) -> Result<ChildWorkflowAvroResult> {
10041        let mut call = self.start_child_workflow(workflow_type, options, args);
10042        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10043    }
10044
10045    fn take_commands(&self) -> Result<Vec<Value>> {
10046        let mut state = self
10047            .state
10048            .lock()
10049            .map_err(|_| Error::WorkflowStatePoisoned)?;
10050        Ok(std::mem::take(&mut state.commands))
10051    }
10052
10053    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10054        let mut state = self
10055            .state
10056            .lock()
10057            .map_err(|_| Error::WorkflowStatePoisoned)?;
10058
10059        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10060            return Err(command_mismatch(&recorded, "continue as new"));
10061        }
10062        if state.recorded_continue_as_new_sequence.is_some() {
10063            state.continue_as_new_consumed = true;
10064            return Ok(None);
10065        }
10066
10067        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10068        let mut command = serde_json::Map::from_iter([
10069            ("type".to_string(), json!("continue_as_new")),
10070            ("arguments".to_string(), arguments),
10071            ("queue".to_string(), json!(state.task_queue.clone())),
10072        ]);
10073        if let Some(workflow_type) = request.options.workflow_type {
10074            command.insert("workflow_type".to_string(), json!(workflow_type));
10075        }
10076        if let Some(task_queue) = request.options.task_queue {
10077            command.insert("queue".to_string(), json!(task_queue));
10078        }
10079        Ok(Some(Value::Object(command)))
10080    }
10081
10082    fn matched_recorded_pending(&self) -> Result<bool> {
10083        let state = self
10084            .state
10085            .lock()
10086            .map_err(|_| Error::WorkflowStatePoisoned)?;
10087        Ok(state.matched_recorded_pending)
10088    }
10089
10090    fn ensure_history_consumed(&self) -> Result<()> {
10091        let state = self
10092            .state
10093            .lock()
10094            .map_err(|_| Error::WorkflowStatePoisoned)?;
10095        if let Some(replay) = &state.scope_delivery {
10096            if let Some((&sequence, _)) = replay
10097                .canonical
10098                .deliveries
10099                .iter()
10100                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10101            {
10102                return Err(invalid_recorded_history(
10103                    "cancellation_scope_delivery_unconsumed",
10104                    sequence,
10105                    "original scoped delivery",
10106                    "workflow completion",
10107                    "workflow completed without consuming its committed scope delivery",
10108                ));
10109            }
10110        }
10111        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10112            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10113                "recorded_commands_unconsumed",
10114                Some(command.sequence()),
10115                Some(command.shape().to_string()),
10116                Some("workflow completion".to_string()),
10117                "workflow completed before consuming all recorded durable commands",
10118            )));
10119        }
10120        if let Some(delivery) = state
10121            .cancellation_history
10122            .delivery
10123            .as_ref()
10124            .filter(|_| !state.cancellation_consumed)
10125        {
10126            return Err(invalid_recorded_history(
10127                "cooperative_cancellation_unconsumed",
10128                delivery.sequence,
10129                "committed cancellation call",
10130                "workflow completion",
10131                "workflow completed without reaching its committed cancellation boundary",
10132            ));
10133        }
10134        if let Some(sequence) = state
10135            .recorded_continue_as_new_sequence
10136            .filter(|_| !state.continue_as_new_consumed)
10137        {
10138            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10139                "recorded_continue_as_new_unconsumed",
10140                Some(sequence),
10141                Some("continue as new".to_string()),
10142                Some("workflow completion".to_string()),
10143                "workflow completed without consuming its recorded continue-as-new transition",
10144            )));
10145        }
10146        Ok(())
10147    }
10148}
10149
10150fn contiguous_message_stream_count(
10151    pending: &[MessageStreamMessage],
10152    cursor: u64,
10153    max_items: usize,
10154) -> usize {
10155    pending
10156        .iter()
10157        .take(max_items)
10158        .enumerate()
10159        .take_while(|(offset, message)| {
10160            u64::try_from(*offset)
10161                .ok()
10162                .and_then(|offset| cursor.checked_add(offset + 1))
10163                == Some(message.position)
10164        })
10165        .count()
10166}
10167
10168fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10169    matches!(
10170        event.event_type.as_str(),
10171        "ActivityScheduled"
10172            | "TimerScheduled"
10173            | "ChildWorkflowScheduled"
10174            | "SignalWaitOpened"
10175            | "ConditionWaitOpened"
10176            | "SearchAttributesUpserted"
10177            | "SideEffectRecorded"
10178            | "VersionMarkerRecorded"
10179            | "MemoUpserted"
10180            | "WorkflowContinuedAsNew"
10181    )
10182}
10183
10184#[derive(Debug)]
10185struct WorkflowState {
10186    workflow_id: Option<String>,
10187    run_id: Option<String>,
10188    task_queue: String,
10189    payload_codec: String,
10190    history_events: Arc<Vec<HistoryEvent>>,
10191    history_budget: WorkflowHistoryBudget,
10192    cancel_requested: bool,
10193    cancellation_history: CancellationHistory,
10194    cancellation_consumed: bool,
10195    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10196    cancellation_shield_depth: u64,
10197    cancellation_delivery_enabled: bool,
10198    cancellation_delivery_intent: Option<CancellationDelivery>,
10199    cancellation_delivery_command_count: usize,
10200    allow_cancellation_scope_authoring: bool,
10201    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10202    cancellation_scope_memberships: BTreeMap<u64, String>,
10203    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10204    resume_signal: Option<ResumeSignal>,
10205    recorded_commands: Vec<RecordedCommand>,
10206    selection_markers: Vec<SelectionMarker>,
10207    selection_marker_cursor: usize,
10208    cancelled_selection_members: Vec<SelectionCancellation>,
10209    recorded_continue_as_new_sequence: Option<u64>,
10210    continue_as_new_consumed: bool,
10211    command_cursor: usize,
10212    condition_wait_occurrence_counter: u64,
10213    matched_recorded_pending: bool,
10214    version_markers: HashMap<String, (i32, u64)>,
10215    workflow_command_identity: String,
10216    workflow_stream_command_counter: u64,
10217    commands: Vec<Value>,
10218    local_activity_requests: Vec<local_activity::Request>,
10219    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
10220    message_stream_cursors: HashMap<String, u64>,
10221    message_stream_waits: HashMap<String, u64>,
10222}
10223
10224impl WorkflowState {
10225    #[cfg(test)]
10226    fn new(
10227        history: Vec<HistoryEvent>,
10228        task_queue: String,
10229        payload_codec: String,
10230        resume_signal: Option<ResumeSignal>,
10231    ) -> Result<Self> {
10232        Self::new_with_identity(
10233            history,
10234            None,
10235            None,
10236            task_queue,
10237            payload_codec,
10238            resume_signal,
10239        )
10240    }
10241
10242    fn new_with_identity(
10243        history: Vec<HistoryEvent>,
10244        workflow_id: Option<String>,
10245        run_id: Option<String>,
10246        task_queue: String,
10247        payload_codec: String,
10248        resume_signal: Option<ResumeSignal>,
10249    ) -> Result<Self> {
10250        Self::new_with_identity_and_scopes(
10251            history,
10252            workflow_id,
10253            run_id,
10254            task_queue,
10255            payload_codec,
10256            resume_signal,
10257            false,
10258        )
10259    }
10260
10261    fn new_with_identity_and_scopes(
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    ) -> Result<Self> {
10270        Self::new_with_identity_and_scope_delivery(
10271            history,
10272            workflow_id,
10273            run_id,
10274            task_queue,
10275            payload_codec,
10276            resume_signal,
10277            allow_cancellation_scope_authoring,
10278            false,
10279        )
10280    }
10281
10282    fn new_with_identity_and_scope_delivery(
10283        history: Vec<HistoryEvent>,
10284        workflow_id: Option<String>,
10285        run_id: Option<String>,
10286        task_queue: String,
10287        payload_codec: String,
10288        resume_signal: Option<ResumeSignal>,
10289        allow_cancellation_scope_authoring: bool,
10290        allow_cancellation_scope_delivery: bool,
10291    ) -> Result<Self> {
10292        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10293            &history,
10294            allow_cancellation_scope_authoring,
10295            allow_cancellation_scope_delivery,
10296        )?;
10297        let scopes = if allow_cancellation_scope_authoring {
10298            cancellation_scope::CancellationScopeHistory::read(
10299                &history,
10300                run_id.as_deref().unwrap_or_default(),
10301            )?
10302        } else {
10303            cancellation_scope::CancellationScopeHistory::default()
10304        };
10305        let cancellation_history = CancellationHistory::from_events(
10306            &history,
10307            run_id.as_deref().unwrap_or_default(),
10308            None,
10309        )?;
10310        if allow_cancellation_scope_authoring
10311            && cancellation_history.request.is_some()
10312            && !allow_cancellation_scope_delivery
10313        {
10314            return Err(Error::CancellationScopeExecutionUnavailable);
10315        }
10316        let scope_delivery = if allow_cancellation_scope_delivery {
10317            Some(cancellation_scope_replay::ScopeReplay::read(
10318                &history,
10319                &scopes,
10320                run_id.as_deref().unwrap_or_default(),
10321                workflow_id.as_deref().unwrap_or_default(),
10322            )?)
10323        } else {
10324            None
10325        };
10326        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
10327            &history,
10328            &payload_codec,
10329            WorkflowIdentity {
10330                workflow_id: workflow_id.clone(),
10331                run_id: run_id.clone(),
10332            },
10333        )?)?;
10334        for (sequence, opening) in &scopes.openings {
10335            if recorded_commands
10336                .iter()
10337                .any(|command| command.sequence() == *sequence)
10338            {
10339                return Err(invalid_recorded_history(
10340                    "invalid_cancellation_scope_history",
10341                    *sequence,
10342                    "distinct authored scope opening",
10343                    "operation collision",
10344                    "scope opening collides with a command",
10345                ));
10346            }
10347            recorded_commands.push(RecordedCommand::CancellationScope {
10348                sequence: *sequence,
10349                scope_id: opening.scope_id.clone(),
10350                parent_scope_id: opening.parent_scope_id.clone(),
10351                shield_parent: opening.shield_parent,
10352            });
10353        }
10354        recorded_commands.sort_by_key(RecordedCommand::sequence);
10355        if let Some(replay) = &scope_delivery {
10356            replay.bind_commands(&mut recorded_commands)?;
10357        }
10358        let selection_markers = recorded_selection_markers(&history)?;
10359        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
10360        let recorded_continue_as_new = history
10361            .iter()
10362            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
10363            .collect::<Vec<_>>();
10364        if recorded_continue_as_new.len() > 1 {
10365            return Err(invalid_recorded_history(
10366                "duplicate_continue_as_new_transition",
10367                recorded_continue_as_new
10368                    .last()
10369                    .and_then(|event| durable_event_sequence(event))
10370                    .unwrap_or(0),
10371                "one WorkflowContinuedAsNew event",
10372                &format!(
10373                    "{} WorkflowContinuedAsNew events",
10374                    recorded_continue_as_new.len()
10375                ),
10376                "workflow history records one continue-as-new transition more than once",
10377            ));
10378        }
10379        let recorded_continue_as_new_sequence = recorded_continue_as_new
10380            .first()
10381            .map(|event| {
10382                durable_event_sequence(event).ok_or_else(|| {
10383                    Error::NonDeterministicReplay(ReplayFailure::new(
10384                        "continue_as_new_sequence_missing",
10385                        None,
10386                        Some("recorded transition sequence".to_string()),
10387                        Some("missing sequence".to_string()),
10388                        "WorkflowContinuedAsNew history is missing its recorded sequence",
10389                    ))
10390                })
10391            })
10392            .transpose()?;
10393        let mut message_stream_cursors = HashMap::new();
10394        for event in &history {
10395            if !matches!(
10396                event.event_type.as_str(),
10397                "SignalReceived" | "SignalApplied"
10398            ) || event.payload.get("signal_name").and_then(Value::as_str)
10399                != Some(MESSAGE_STREAM_SIGNAL)
10400            {
10401                continue;
10402            }
10403            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
10404            if arguments.len() != 1 {
10405                continue;
10406            }
10407            let envelope = arguments[0].clone().into_json()?;
10408            let Some(envelope) = envelope.as_object() else {
10409                continue;
10410            };
10411            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
10412            {
10413                continue;
10414            }
10415            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10416                continue;
10417            };
10418            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10419            else {
10420                continue;
10421            };
10422            let cursor = message_stream_cursors
10423                .entry(stream_name.to_string())
10424                .or_insert(0);
10425            *cursor = (*cursor).max(through_position);
10426        }
10427        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
10428        let cancel_requested = history.iter().any(|event| {
10429            matches!(
10430                event.event_type.as_str(),
10431                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
10432            )
10433        });
10434        let cancellation_clock = cancellation_history
10435            .request
10436            .as_ref()
10437            .and_then(|request| request.context.as_ref())
10438            .map(|_| {
10439                cancellation_replay_clock::ReplayClock::new(
10440                    &history,
10441                    &recorded_commands,
10442                    cancellation_history.delivery_index,
10443                )
10444            })
10445            .or_else(|| {
10446                scope_delivery.as_ref().map(|_| {
10447                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
10448                })
10449            });
10450        Ok(Self {
10451            workflow_command_identity: String::new(),
10452            workflow_stream_command_counter: 0,
10453            workflow_id,
10454            run_id,
10455            task_queue,
10456            payload_codec,
10457            history_events: Arc::new(history),
10458            history_budget: WorkflowHistoryBudget {
10459                event_count,
10460                ..WorkflowHistoryBudget::default()
10461            },
10462            cancel_requested,
10463            cancellation_history,
10464            cancellation_consumed: false,
10465            cancellation_clock,
10466            cancellation_shield_depth: 0,
10467            cancellation_delivery_enabled: false,
10468            cancellation_delivery_intent: None,
10469            cancellation_delivery_command_count: 0,
10470            allow_cancellation_scope_authoring,
10471            cancellation_scope_opening: None,
10472            cancellation_scope_memberships: scopes.memberships,
10473            scope_delivery,
10474            resume_signal,
10475            recorded_commands,
10476            selection_markers,
10477            selection_marker_cursor: 0,
10478            cancelled_selection_members,
10479            recorded_continue_as_new_sequence,
10480            continue_as_new_consumed: false,
10481            command_cursor: 0,
10482            condition_wait_occurrence_counter: 0,
10483            matched_recorded_pending: false,
10484            version_markers: HashMap::new(),
10485            commands: Vec::new(),
10486            local_activity_requests: Vec::new(),
10487            message_stream_messages: HashMap::new(),
10488            message_stream_cursors,
10489            message_stream_waits: HashMap::new(),
10490        })
10491    }
10492}
10493
10494enum MessageStreamDelivery {
10495    Message(MessageStreamMessage),
10496    Cursor {
10497        stream_name: String,
10498        through_position: u64,
10499    },
10500}
10501
10502fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
10503    if arguments.len() != 1 {
10504        return Ok(None);
10505    }
10506    let envelope = arguments
10507        .into_iter()
10508        .next()
10509        .expect("one argument was checked");
10510    let Some(envelope) = envelope.as_object() else {
10511        return Ok(None);
10512    };
10513    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10514        return Ok(None);
10515    };
10516    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
10517        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10518        else {
10519            return Ok(None);
10520        };
10521        return Ok(Some(MessageStreamDelivery::Cursor {
10522            stream_name: stream_name.to_string(),
10523            through_position,
10524        }));
10525    }
10526    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
10527        return Ok(None);
10528    }
10529    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
10530        return Ok(None);
10531    };
10532    let Some(position) = envelope
10533        .get("position")
10534        .and_then(Value::as_u64)
10535        .filter(|value| *value > 0)
10536    else {
10537        return Ok(None);
10538    };
10539    let Some(payload_envelope) = envelope.get("payload_envelope") else {
10540        return Ok(None);
10541    };
10542    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
10543    else {
10544        return Ok(None);
10545    };
10546    let decoded = decode_avro_value(&payload_envelope)?;
10547    let AvroValue::Array(values) = decoded else {
10548        return Ok(None);
10549    };
10550    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
10551        stream_name: stream_name.to_string(),
10552        message_id: message_id.to_string(),
10553        position,
10554        arguments: values,
10555    })))
10556}
10557
10558#[derive(Clone, Debug)]
10559enum RecordedCommand {
10560    CancellationScope {
10561        sequence: u64,
10562        scope_id: String,
10563        parent_scope_id: String,
10564        shield_parent: bool,
10565    },
10566    CancellationGroup {
10567        sequence: u64,
10568        span: u64,
10569        original: Vec<RecordedCommand>,
10570    },
10571    CancellationBoundary {
10572        sequence: u64,
10573        call_kind: CancellationCallKind,
10574        original: Option<Box<RecordedCommand>>,
10575    },
10576    Activity {
10577        sequence: u64,
10578        activity_type: Option<String>,
10579        cancellation_policy: String,
10580        options: Option<RecordedActivityOptions>,
10581        outcome: Option<ActivityOutcome>,
10582        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10583    },
10584    Timer {
10585        sequence: u64,
10586        delay_seconds: u64,
10587        fired: bool,
10588        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10589    },
10590    ChildWorkflow {
10591        sequence: u64,
10592        workflow_type: Option<String>,
10593        policies: RecordedChildPolicies,
10594        outcome: Option<ChildWorkflowOutcome>,
10595        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10596    },
10597    SignalWait {
10598        sequence: u64,
10599        signal_name: String,
10600        value: Option<Vec<AvroValue>>,
10601        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10602    },
10603    ConditionWait {
10604        sequence: u64,
10605        occurrence_id: String,
10606        condition_key: Option<String>,
10607        predicate_identity: String,
10608        timeout_seconds: Option<u64>,
10609        result: Option<ConditionWaitResult>,
10610        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10611    },
10612    SearchAttributes {
10613        sequence: u64,
10614        attributes: Value,
10615        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
10616    },
10617    SideEffect {
10618        sequence: u64,
10619        value: AvroValue,
10620    },
10621    VersionMarker {
10622        sequence: u64,
10623        change_id: String,
10624        version: i32,
10625    },
10626    Memo {
10627        sequence: u64,
10628        entries: AvroValue,
10629    },
10630}
10631
10632#[derive(Clone, Debug, PartialEq, Eq)]
10633struct SelectionMarker {
10634    selection_group_id: String,
10635    selection_group_base_sequence: u64,
10636    selection_group_size: usize,
10637    member_key: SelectionKey,
10638    member_index: usize,
10639    member_base_sequence: u64,
10640    member_size: usize,
10641    operation_kind: String,
10642    operation_identity: String,
10643    outcome: String,
10644    resolution_event_id: String,
10645    resolution_event_type: String,
10646}
10647
10648#[derive(Clone, Debug, PartialEq, Eq)]
10649struct SelectionCancellation {
10650    selection_group_id: String,
10651    member_key: SelectionKey,
10652    member_index: usize,
10653    member_base_sequence: u64,
10654    member_size: usize,
10655    operation_kind: String,
10656    operation_identity: String,
10657}
10658
10659fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
10660    let mut markers: Vec<SelectionMarker> = Vec::new();
10661    for event in events
10662        .iter()
10663        .filter(|event| event.event_type == "SelectionResolved")
10664    {
10665        let payload = &event.payload;
10666        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
10667        let group_size = required_selection_usize(payload, "selection_group_size")?;
10668        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
10669        let member_size = required_selection_usize(payload, "member_size")?;
10670        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
10671        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
10672            invalid_recorded_history(
10673                "selection_marker_invalid",
10674                base_sequence,
10675                "non-empty selection_group_id",
10676                &payload.to_string(),
10677                "selection winner history is missing its durable group identity",
10678            )
10679        })?;
10680        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
10681        if group_id != expected_group_id {
10682            return Err(invalid_recorded_history(
10683                "selection_marker_invalid",
10684                base_sequence,
10685                &expected_group_id,
10686                &group_id,
10687                "selection winner history contains an incompatible group identity",
10688            ));
10689        }
10690        let group_end = base_sequence
10691            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
10692            .unwrap_or(u64::MAX);
10693        let member_end = member_base_sequence
10694            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
10695            .unwrap_or(u64::MAX);
10696        if member_index >= group_size
10697            || member_base_sequence < base_sequence
10698            || member_end > group_end
10699        {
10700            return Err(invalid_recorded_history(
10701                "selection_marker_invalid",
10702                base_sequence,
10703                "winner member within selection group bounds",
10704                &payload.to_string(),
10705                "selection winner history contains an invalid member range",
10706            ));
10707        }
10708        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
10709            invalid_recorded_history(
10710                "selection_marker_invalid",
10711                base_sequence,
10712                "selection operation kind",
10713                &payload.to_string(),
10714                "selection winner history is missing its operation kind",
10715            )
10716        })?;
10717        if !matches!(
10718            operation_kind.as_str(),
10719            "activity" | "child" | "timer" | "signal" | "condition" | "group"
10720        ) {
10721            return Err(invalid_recorded_history(
10722                "selection_marker_invalid",
10723                base_sequence,
10724                "activity, child, timer, signal, condition, or group",
10725                &operation_kind,
10726                "selection winner history contains an unsupported operation kind",
10727            ));
10728        }
10729        let operation_identity =
10730            payload_string(payload, "operation_identity").ok_or_else(|| {
10731                invalid_recorded_history(
10732                    "selection_marker_invalid",
10733                    base_sequence,
10734                    "non-empty operation identity",
10735                    &payload.to_string(),
10736                    "selection winner history is missing its durable operation identity",
10737                )
10738            })?;
10739        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
10740            invalid_recorded_history(
10741                "selection_marker_invalid",
10742                base_sequence,
10743                "completed or failed selection outcome",
10744                &payload.to_string(),
10745                "selection winner history is missing its outcome",
10746            )
10747        })?;
10748        if !matches!(outcome.as_str(), "completed" | "failed") {
10749            return Err(invalid_recorded_history(
10750                "selection_marker_invalid",
10751                base_sequence,
10752                "completed or failed selection outcome",
10753                &outcome,
10754                "selection winner history contains an unsupported outcome",
10755            ));
10756        }
10757        let marker = SelectionMarker {
10758            selection_group_id: group_id,
10759            selection_group_base_sequence: base_sequence,
10760            selection_group_size: group_size,
10761            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
10762            member_index,
10763            member_base_sequence,
10764            member_size,
10765            operation_kind,
10766            operation_identity,
10767            outcome,
10768            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
10769                || {
10770                    invalid_recorded_history(
10771                        "selection_marker_invalid",
10772                        base_sequence,
10773                        "durable resolution_event_id",
10774                        &payload.to_string(),
10775                        "selection winner history is missing its terminal event identity",
10776                    )
10777                },
10778            )?,
10779            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
10780                || {
10781                    invalid_recorded_history(
10782                        "selection_marker_invalid",
10783                        base_sequence,
10784                        "durable resolution_event_type",
10785                        &payload.to_string(),
10786                        "selection winner history is missing its terminal event type",
10787                    )
10788                },
10789            )?,
10790        };
10791        if let Some(existing) = markers
10792            .iter()
10793            .find(|existing| existing.selection_group_id == marker.selection_group_id)
10794        {
10795            if existing != &marker {
10796                return Err(invalid_recorded_history(
10797                    "selection_marker_conflict",
10798                    base_sequence,
10799                    &format!("one winner for {}", marker.selection_group_id),
10800                    &payload.to_string(),
10801                    "selection history records conflicting winners for one durable group",
10802                ));
10803            }
10804            continue;
10805        }
10806        markers.push(marker);
10807    }
10808    Ok(markers)
10809}
10810
10811fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
10812    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
10813    for event in events
10814        .iter()
10815        .filter(|event| event.event_type == "SelectionOperationCancelled")
10816    {
10817        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
10818            invalid_recorded_history(
10819                "selection_cancellation_invalid",
10820                0,
10821                "non-empty selection_group_id",
10822                &event.payload.to_string(),
10823                "selection cancellation history is missing its group identity",
10824            )
10825        })?;
10826        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
10827        let marker = SelectionCancellation {
10828            selection_group_id: group_id,
10829            member_key: selection_key_from_value(
10830                event.payload.get("member_key"),
10831                member_base_sequence,
10832            )?,
10833            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
10834            member_base_sequence,
10835            member_size: required_selection_usize(&event.payload, "member_size")?,
10836            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
10837                invalid_recorded_history(
10838                    "selection_cancellation_invalid",
10839                    member_base_sequence,
10840                    "selection operation kind",
10841                    &event.payload.to_string(),
10842                    "selection cancellation is missing its operation kind",
10843                )
10844            })?,
10845            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
10846                || {
10847                    invalid_recorded_history(
10848                        "selection_cancellation_invalid",
10849                        member_base_sequence,
10850                        "selection operation identity",
10851                        &event.payload.to_string(),
10852                        "selection cancellation is missing its operation identity",
10853                    )
10854                },
10855            )?,
10856        };
10857        if let Some(existing) = cancelled.iter().find(|recorded| {
10858            recorded.selection_group_id == marker.selection_group_id
10859                && recorded.member_base_sequence == marker.member_base_sequence
10860        }) {
10861            if existing != &marker {
10862                return Err(invalid_recorded_history(
10863                    "selection_cancellation_conflict",
10864                    member_base_sequence,
10865                    "one stable SelectionOperationCancelled marker",
10866                    &event.payload.to_string(),
10867                    "selection cancellation history contains conflicting member metadata",
10868                ));
10869            }
10870        } else {
10871            cancelled.push(marker);
10872        }
10873    }
10874    Ok(cancelled)
10875}
10876
10877fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
10878    payload
10879        .get(field)
10880        .and_then(value_as_u64)
10881        .filter(|value| *value > 0)
10882        .ok_or_else(|| {
10883            invalid_recorded_history(
10884                "selection_marker_invalid",
10885                0,
10886                &format!("positive integer {field}"),
10887                &payload.to_string(),
10888                "selection history contains invalid durable identity metadata",
10889            )
10890        })
10891}
10892
10893fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
10894    required_selection_usize_allow_zero(payload, field).and_then(|value| {
10895        if value > 0 {
10896            Ok(value)
10897        } else {
10898            Err(invalid_recorded_history(
10899                "selection_marker_invalid",
10900                0,
10901                &format!("positive integer {field}"),
10902                &payload.to_string(),
10903                "selection history contains invalid durable identity metadata",
10904            ))
10905        }
10906    })
10907}
10908
10909fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
10910    payload
10911        .get(field)
10912        .and_then(value_as_u64)
10913        .and_then(|value| usize::try_from(value).ok())
10914        .ok_or_else(|| {
10915            invalid_recorded_history(
10916                "selection_marker_invalid",
10917                0,
10918                &format!("non-negative integer {field}"),
10919                &payload.to_string(),
10920                "selection history contains invalid durable identity metadata",
10921            )
10922        })
10923}
10924
10925#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
10926struct RecordedActivityOptions {
10927    task_queue: RecordedSnapshotValue<Option<String>>,
10928    execution_mode: RecordedSnapshotValue<Option<String>>,
10929    retry_policy: ActivityRetrySnapshot,
10930    worker_session: Option<Value>,
10931}
10932
10933#[derive(Clone, Debug)]
10934struct RecordedChildPolicies {
10935    parent_close_policy: String,
10936    cancellation_policy: String,
10937}
10938
10939fn recorded_activity_cancellation_policy(
10940    events: &[&HistoryEvent],
10941    sequence: u64,
10942) -> Result<String> {
10943    let mut policy: Option<String> = None;
10944    for event in events.iter().filter(|event| {
10945        matches!(
10946            event.event_type.as_str(),
10947            "ActivityScheduled"
10948                | "ActivityStarted"
10949                | "ActivityCompleted"
10950                | "ActivityFailed"
10951                | "ActivityTimedOut"
10952                | "ActivityCancelled"
10953        )
10954    }) {
10955        for source in [Some(&event.payload), event.payload.get("activity")]
10956            .into_iter()
10957            .flatten()
10958        {
10959            let Some(value) = source.get("cancellation_policy") else {
10960                continue;
10961            };
10962            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
10963                value.as_str()
10964            else {
10965                return Err(invalid_recorded_history(
10966                    "invalid_activity_cancellation_policy_history",
10967                    sequence,
10968                    "supported Activity cancellation policy",
10969                    &value.to_string(),
10970                    "Activity history contains an invalid cancellation policy",
10971                ));
10972            };
10973            if let Some(previous) = policy.as_deref() {
10974                if previous != incoming {
10975                    return Err(invalid_recorded_history(
10976                        "activity_cancellation_policy_history_conflict",
10977                        sequence,
10978                        previous,
10979                        incoming,
10980                        "Activity cancellation policy changed between history events",
10981                    ));
10982                }
10983            }
10984            policy = Some(incoming.to_string());
10985        }
10986        policy.get_or_insert_with(|| "try_cancel".to_string());
10987    }
10988    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
10989}
10990
10991fn recorded_child_policy_value<'a>(
10992    payload: &'a Value,
10993    field: &str,
10994    sequence: u64,
10995) -> Result<Option<&'a str>> {
10996    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
10997        return Ok(None);
10998    };
10999    let valid = match (field, value.as_str()) {
11000        (
11001            "parent_close_policy",
11002            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11003        ) => true,
11004        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11005            true
11006        }
11007        _ => false,
11008    };
11009    if !valid {
11010        return Err(invalid_recorded_history(
11011            "invalid_child_workflow_policy_history",
11012            sequence,
11013            "supported child workflow policy",
11014            &value.to_string(),
11015            "child workflow history contains an invalid policy",
11016        ));
11017    }
11018    Ok(value.as_str())
11019}
11020
11021fn recorded_child_policies(
11022    events: &[&HistoryEvent],
11023    scheduled: &HistoryEvent,
11024    sequence: u64,
11025) -> Result<RecordedChildPolicies> {
11026    let parent_close_policy =
11027        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11028            .unwrap_or("abandon")
11029            .to_string();
11030    let cancellation_policy =
11031        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11032            .unwrap_or("abandon")
11033            .to_string();
11034    for event in events {
11035        for (field, expected) in [
11036            ("parent_close_policy", parent_close_policy.as_str()),
11037            ("cancellation_policy", cancellation_policy.as_str()),
11038        ] {
11039            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11040                if actual != expected {
11041                    return Err(invalid_recorded_history(
11042                        "child_workflow_policy_history_conflict",
11043                        sequence,
11044                        expected,
11045                        actual,
11046                        "child workflow policy changed between history events",
11047                    ));
11048                }
11049            }
11050        }
11051    }
11052    Ok(RecordedChildPolicies {
11053        parent_close_policy,
11054        cancellation_policy,
11055    })
11056}
11057
11058fn ensure_child_policies_match(
11059    sequence: u64,
11060    recorded: &RecordedChildPolicies,
11061    current: &ChildWorkflowOptions,
11062) -> Result<()> {
11063    for (field, expected, actual) in [
11064        (
11065            "parent_close_policy",
11066            recorded.parent_close_policy.as_str(),
11067            current.parent_close_policy.as_str(),
11068        ),
11069        (
11070            "cancellation_policy",
11071            recorded.cancellation_policy.as_str(),
11072            current.cancellation_policy.as_str(),
11073        ),
11074    ] {
11075        if expected != actual {
11076            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11077                "child_workflow_policy_changed",
11078                Some(sequence),
11079                Some(expected.to_string()),
11080                Some(actual.to_string()),
11081                format!("child workflow {field} changed during replay"),
11082            )));
11083        }
11084    }
11085    Ok(())
11086}
11087
11088#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11089enum RecordedSnapshotValue<T> {
11090    /// Older history did not persist this field, so it cannot constrain replay.
11091    Unknown,
11092    Known(T),
11093}
11094
11095impl<T: PartialEq> RecordedSnapshotValue<T> {
11096    fn matches_current(&self, current: &Self) -> bool {
11097        match self {
11098            Self::Unknown => true,
11099            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11100        }
11101    }
11102}
11103
11104#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11105struct ActivityRetrySnapshot {
11106    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11107    max_attempts: RecordedSnapshotValue<Option<u64>>,
11108    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11109    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11110    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11111    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11112    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11113    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11114}
11115
11116impl ActivityRetrySnapshot {
11117    fn matches_current(&self, current: &Self) -> bool {
11118        self.snapshot_version
11119            .matches_current(&current.snapshot_version)
11120            && self.max_attempts.matches_current(&current.max_attempts)
11121            && self
11122                .backoff_seconds
11123                .matches_current(&current.backoff_seconds)
11124            && self
11125                .start_to_close_timeout
11126                .matches_current(&current.start_to_close_timeout)
11127            && self
11128                .schedule_to_start_timeout
11129                .matches_current(&current.schedule_to_start_timeout)
11130            && self
11131                .schedule_to_close_timeout
11132                .matches_current(&current.schedule_to_close_timeout)
11133            && self
11134                .heartbeat_timeout
11135                .matches_current(&current.heartbeat_timeout)
11136            && self
11137                .non_retryable_error_types
11138                .matches_current(&current.non_retryable_error_types)
11139    }
11140}
11141
11142fn recorded_optional_u64(
11143    object: Option<&serde_json::Map<String, Value>>,
11144    field: &str,
11145) -> RecordedSnapshotValue<Option<u64>> {
11146    match object.and_then(|object| object.get(field)) {
11147        None => RecordedSnapshotValue::Unknown,
11148        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11149        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11150    }
11151}
11152
11153fn recorded_optional_string(
11154    object: &serde_json::Map<String, Value>,
11155    field: &str,
11156) -> RecordedSnapshotValue<Option<String>> {
11157    match object.get(field) {
11158        None => RecordedSnapshotValue::Unknown,
11159        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11160        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11161    }
11162}
11163
11164fn recorded_activity_execution_mode(
11165    events: &[&HistoryEvent],
11166    sequence: u64,
11167) -> Result<RecordedSnapshotValue<Option<String>>> {
11168    let mut recorded = RecordedSnapshotValue::Unknown;
11169    for event in events {
11170        for object in [
11171            event.payload.as_object(),
11172            event.payload.get("activity").and_then(Value::as_object),
11173        ]
11174        .into_iter()
11175        .flatten()
11176        {
11177            let mode = match object.get("execution_mode") {
11178                None => None,
11179                Some(Value::Null) => Some(None),
11180                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11181                Some(_) => {
11182                    return Err(invalid_recorded_history(
11183                        "activity_execution_mode_invalid",
11184                        sequence,
11185                        "null or a non-empty execution mode",
11186                        "invalid execution_mode",
11187                        "activity history contains an invalid execution mode",
11188                    ))
11189                }
11190            };
11191            let legacy_mode = match object.get("local_activity") {
11192                None => None,
11193                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11194                Some(_) => {
11195                    return Err(invalid_recorded_history(
11196                        "activity_execution_mode_invalid",
11197                        sequence,
11198                        "boolean local_activity",
11199                        "invalid local_activity",
11200                        "activity history contains an invalid local-activity marker",
11201                    ))
11202                }
11203            };
11204            for mode in [mode, legacy_mode].into_iter().flatten() {
11205                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
11206                {
11207                    return Err(invalid_recorded_history(
11208                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
11209                        "activity lifecycle events at one workflow sequence disagree on execution mode",
11210                    ));
11211                }
11212                recorded = RecordedSnapshotValue::Known(mode);
11213            }
11214        }
11215    }
11216    Ok(recorded)
11217}
11218
11219fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
11220    let policy = policy.and_then(Value::as_object);
11221    let backoff_seconds = policy
11222        .and_then(|policy| policy.get("backoff_seconds"))
11223        .and_then(Value::as_array)
11224        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11225        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
11226    let mut non_retryable_error_types = Vec::new();
11227    for error_type in policy
11228        .and_then(|policy| policy.get("non_retryable_error_types"))
11229        .and_then(Value::as_array)
11230        .into_iter()
11231        .flatten()
11232        .filter_map(Value::as_str)
11233        .map(str::trim)
11234        .filter(|error_type| !error_type.is_empty())
11235    {
11236        if !non_retryable_error_types
11237            .iter()
11238            .any(|recorded| recorded == error_type)
11239        {
11240            non_retryable_error_types.push(error_type.to_string());
11241        }
11242    }
11243
11244    ActivityRetrySnapshot {
11245        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
11246        max_attempts: recorded_optional_u64(policy, "max_attempts"),
11247        backoff_seconds,
11248        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
11249        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
11250        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
11251        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
11252        non_retryable_error_types: if policy
11253            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
11254        {
11255            RecordedSnapshotValue::Known(non_retryable_error_types)
11256        } else {
11257            RecordedSnapshotValue::Unknown
11258        },
11259    }
11260}
11261
11262fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
11263    let policy = options.retry_policy.as_ref();
11264    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
11265        Some(Value::Null) => None,
11266        Some(value) => value_as_u64(value),
11267        None => Some(1),
11268    };
11269    let backoff_seconds = policy
11270        .and_then(|policy| policy.get("backoff_seconds"))
11271        .and_then(Value::as_array)
11272        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11273        .unwrap_or_default();
11274    let non_retryable_error_types = policy
11275        .and_then(|policy| policy.get("non_retryable_error_types"))
11276        .and_then(Value::as_array)
11277        .into_iter()
11278        .flatten()
11279        .filter_map(Value::as_str)
11280        .map(str::to_string)
11281        .collect();
11282
11283    ActivityRetrySnapshot {
11284        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
11285        max_attempts: RecordedSnapshotValue::Known(max_attempts),
11286        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
11287        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
11288        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
11289        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
11290        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
11291        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
11292    }
11293}
11294
11295fn activity_options_description(options: &RecordedActivityOptions) -> String {
11296    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
11297}
11298
11299impl RecordedCommand {
11300    fn sequence(&self) -> u64 {
11301        match self {
11302            Self::CancellationGroup { sequence, .. }
11303            | Self::CancellationScope { sequence, .. }
11304            | Self::CancellationBoundary { sequence, .. }
11305            | Self::Activity { sequence, .. }
11306            | Self::Timer { sequence, .. }
11307            | Self::ChildWorkflow { sequence, .. }
11308            | Self::SignalWait { sequence, .. }
11309            | Self::ConditionWait { sequence, .. }
11310            | Self::SearchAttributes { sequence, .. }
11311            | Self::SideEffect { sequence, .. }
11312            | Self::VersionMarker { sequence, .. }
11313            | Self::Memo { sequence, .. } => *sequence,
11314        }
11315    }
11316
11317    fn shape(&self) -> &'static str {
11318        match self {
11319            Self::CancellationScope { .. } => "cancellation scope",
11320            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
11321                "cooperative cancellation"
11322            }
11323            Self::Activity { .. } => "activity",
11324            Self::Timer { .. } => "timer",
11325            Self::ChildWorkflow { .. } => "child workflow",
11326            Self::SignalWait { .. } => "signal wait",
11327            Self::ConditionWait { .. } => "condition wait",
11328            Self::SearchAttributes { .. } => "search-attribute update",
11329            Self::SideEffect { .. } => "side effect",
11330            Self::VersionMarker { .. } => "version marker",
11331            Self::Memo { .. } => "memo upsert",
11332        }
11333    }
11334}
11335
11336fn ensure_version_supported(
11337    change_id: &str,
11338    version: i32,
11339    min_supported: i32,
11340    max_supported: i32,
11341    sequence: u64,
11342) -> Result<()> {
11343    if (min_supported..=max_supported).contains(&version) {
11344        return Ok(());
11345    }
11346    Err(Error::NonDeterministicReplay(ReplayFailure::new(
11347        "version_marker_incompatible_range",
11348        (sequence != 0).then_some(sequence),
11349        Some(format!("{min_supported}..={max_supported}")),
11350        Some(format!("{change_id}:{version}")),
11351        "recorded workflow version is outside the range supported by current code",
11352    )))
11353}
11354
11355#[derive(Clone, Debug)]
11356struct ResumeSignal {
11357    signal_name: String,
11358    arguments: Vec<AvroValue>,
11359}
11360
11361const MAX_PARALLEL_OPERATIONS: usize = 1000;
11362
11363fn parallel_group_prefix(kind: &str) -> &'static str {
11364    match kind {
11365        "activity" => "parallel-activities",
11366        "child" => "parallel-children",
11367        "timer" => "parallel-timers",
11368        _ => "parallel-calls",
11369    }
11370}
11371
11372fn parallel_group_entry(
11373    base_sequence: u64,
11374    size: usize,
11375    index: usize,
11376    kind: &str,
11377) -> ParallelGroupMetadata {
11378    ParallelGroupMetadata {
11379        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
11380        parallel_group_kind: kind.to_string(),
11381        parallel_group_base_sequence: base_sequence,
11382        parallel_group_size: size,
11383        parallel_group_index: index,
11384        parallel_group_mode: None,
11385        selection_member_key: None,
11386        selection_member_index: None,
11387        selection_member_base_sequence: None,
11388        selection_member_size: None,
11389        selection_member_kind: None,
11390    }
11391}
11392
11393struct SelectionMemberMetadata {
11394    key: SelectionKey,
11395    index: usize,
11396    base_sequence: u64,
11397    size: usize,
11398    kind: String,
11399}
11400
11401fn selection_group_entry(
11402    base_sequence: u64,
11403    size: usize,
11404    index: usize,
11405    kind: &str,
11406    member: &SelectionMemberMetadata,
11407) -> ParallelGroupMetadata {
11408    ParallelGroupMetadata {
11409        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
11410        parallel_group_kind: kind.to_string(),
11411        parallel_group_base_sequence: base_sequence,
11412        parallel_group_size: size,
11413        parallel_group_index: index,
11414        parallel_group_mode: Some("select".to_string()),
11415        selection_member_key: Some(member.key.clone()),
11416        selection_member_index: Some(member.index),
11417        selection_member_base_sequence: Some(member.base_sequence),
11418        selection_member_size: Some(member.size),
11419        selection_member_kind: Some(member.kind.clone()),
11420    }
11421}
11422
11423fn apply_parallel_group_path(
11424    command: &mut serde_json::Map<String, Value>,
11425    path: &[ParallelGroupMetadata],
11426) {
11427    let Some(inner) = path.last() else {
11428        return;
11429    };
11430    command.insert(
11431        "parallel_group_id".to_string(),
11432        json!(inner.parallel_group_id),
11433    );
11434    command.insert(
11435        "parallel_group_kind".to_string(),
11436        json!(inner.parallel_group_kind),
11437    );
11438    command.insert(
11439        "parallel_group_base_sequence".to_string(),
11440        json!(inner.parallel_group_base_sequence),
11441    );
11442    command.insert(
11443        "parallel_group_size".to_string(),
11444        json!(inner.parallel_group_size),
11445    );
11446    command.insert(
11447        "parallel_group_index".to_string(),
11448        json!(inner.parallel_group_index),
11449    );
11450    if let Some(mode) = &inner.parallel_group_mode {
11451        command.insert("parallel_group_mode".to_string(), json!(mode));
11452    }
11453    if let Some(key) = &inner.selection_member_key {
11454        command.insert("selection_member_key".to_string(), json!(key));
11455    }
11456    if let Some(index) = inner.selection_member_index {
11457        command.insert("selection_member_index".to_string(), json!(index));
11458    }
11459    if let Some(base_sequence) = inner.selection_member_base_sequence {
11460        command.insert(
11461            "selection_member_base_sequence".to_string(),
11462            json!(base_sequence),
11463        );
11464    }
11465    if let Some(size) = inner.selection_member_size {
11466        command.insert("selection_member_size".to_string(), json!(size));
11467    }
11468    if let Some(kind) = &inner.selection_member_kind {
11469        command.insert("selection_member_kind".to_string(), json!(kind));
11470    }
11471    command.insert("parallel_group_path".to_string(), json!(path));
11472}
11473
11474fn ensure_parallel_path_matches(
11475    sequence: u64,
11476    recorded: Option<&[ParallelGroupMetadata]>,
11477    expected: &[ParallelGroupMetadata],
11478) -> Result<()> {
11479    match (recorded, expected.is_empty()) {
11480        (None, true) => Ok(()),
11481        (Some(recorded), false) if recorded == expected => Ok(()),
11482        (None, false) => Err(invalid_recorded_history(
11483            "parallel_group_metadata_missing",
11484            sequence,
11485            &serde_json::to_string(expected).unwrap_or_default(),
11486            "<missing>",
11487            "recorded parallel member is missing its durable group path",
11488        )),
11489        (Some(recorded), true) => Err(invalid_recorded_history(
11490            "parallel_group_shape_mismatch",
11491            sequence,
11492            "sequential command",
11493            &serde_json::to_string(recorded).unwrap_or_default(),
11494            "recorded command belonged to a parallel group but current code schedules it sequentially",
11495        )),
11496        (Some(recorded), false) => Err(invalid_recorded_history(
11497            "parallel_group_shape_mismatch",
11498            sequence,
11499            &serde_json::to_string(recorded).unwrap_or_default(),
11500            &serde_json::to_string(expected).unwrap_or_default(),
11501            "recorded parallel-group identity or path changed during replay",
11502        )),
11503    }
11504}
11505
11506#[derive(Clone, Debug)]
11507enum ParallelShape {
11508    Leaf,
11509    Group(Vec<ParallelShape>),
11510}
11511
11512struct ParallelDescriptor {
11513    operation: ParallelOperation,
11514    offset: usize,
11515    member_path: Vec<usize>,
11516    group_path: Vec<ParallelGroupMetadata>,
11517}
11518
11519fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
11520    operations
11521        .iter()
11522        .map(|operation| match operation {
11523            ParallelOperation::Group(children) => parallel_leaf_count(children),
11524            _ => 1,
11525        })
11526        .sum()
11527}
11528
11529fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
11530    match operation {
11531        ParallelOperation::Activity { .. } => Some("activity"),
11532        ParallelOperation::ChildWorkflow { .. } => Some("child"),
11533        ParallelOperation::Timer(_) => Some("timer"),
11534        ParallelOperation::Signal(_) => Some("signal"),
11535        ParallelOperation::Condition { .. } => Some("condition"),
11536        ParallelOperation::Group(children) => parallel_group_kind(children),
11537    }
11538}
11539
11540fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
11541    let mut kind = None;
11542    for operation in operations {
11543        let Some(operation_kind) = parallel_operation_kind(operation) else {
11544            continue;
11545        };
11546        match kind {
11547            None => kind = Some(operation_kind),
11548            Some(current) if current == operation_kind => {}
11549            Some(_) => return Some("mixed"),
11550        }
11551    }
11552    kind
11553}
11554
11555fn validate_parallel_operations(
11556    operations: &[ParallelOperation],
11557    member_path: &mut Vec<usize>,
11558    root: bool,
11559) -> Result<()> {
11560    let leaves = parallel_leaf_count(operations);
11561    if leaves > MAX_PARALLEL_OPERATIONS {
11562        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11563            reason: "fan_out_limit_exceeded",
11564            member_path: member_path.clone(),
11565            message: format!(
11566                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
11567            ),
11568        }));
11569    }
11570    if !root && operations.is_empty() {
11571        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11572            reason: "nested_group_empty",
11573            member_path: member_path.clone(),
11574            message: "a nested group must contain at least one durable leaf".to_string(),
11575        }));
11576    }
11577
11578    for (index, operation) in operations.iter().enumerate() {
11579        member_path.push(index);
11580        match operation {
11581            ParallelOperation::Activity {
11582                options, arguments, ..
11583            } => {
11584                options
11585                    .validate()
11586                    .map_err(|error| Error::InvalidActivityOptions(error))?;
11587                if let Err(error) = arguments {
11588                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11589                        reason: "arguments_invalid",
11590                        member_path: member_path.clone(),
11591                        message: error.to_string(),
11592                    }));
11593                }
11594            }
11595            ParallelOperation::ChildWorkflow {
11596                options, arguments, ..
11597            } => {
11598                validate_parallel_child_options(options)?;
11599                if let Err(error) = arguments {
11600                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11601                        reason: "arguments_invalid",
11602                        member_path: member_path.clone(),
11603                        message: error.to_string(),
11604                    }));
11605                }
11606            }
11607            ParallelOperation::Timer(duration)
11608                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
11609            {
11610                return Err(Error::TimerDurationOverflow);
11611            }
11612            ParallelOperation::Timer(_) => {}
11613            ParallelOperation::Signal(signal_name) => {
11614                validate_user_signal_name(signal_name)?;
11615                if signal_name.trim().is_empty() {
11616                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11617                        reason: "signal_name_empty",
11618                        member_path: member_path.clone(),
11619                        message: "signal wait name must not be empty".to_string(),
11620                    }));
11621                }
11622            }
11623            ParallelOperation::Condition { options, .. } => {
11624                options.validate()?;
11625            }
11626            ParallelOperation::Group(children) => {
11627                validate_parallel_operations(children, member_path, false)?;
11628            }
11629        }
11630        member_path.pop();
11631    }
11632    Ok(())
11633}
11634
11635fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
11636    if options.task_queue.trim().is_empty() {
11637        return Err(Error::InvalidChildWorkflowOptions(
11638            "task_queue must not be empty".to_string(),
11639        ));
11640    }
11641    for (name, value) in [
11642        (
11643            "execution_timeout_seconds",
11644            options.execution_timeout_seconds,
11645        ),
11646        ("run_timeout_seconds", options.run_timeout_seconds),
11647    ] {
11648        if value == Some(0) {
11649            return Err(Error::InvalidChildWorkflowOptions(format!(
11650                "{name} must be at least 1"
11651            )));
11652        }
11653    }
11654    if options
11655        .retry_policy
11656        .as_ref()
11657        .is_some_and(|policy| policy.max_attempts == Some(0))
11658    {
11659        return Err(Error::InvalidChildWorkflowOptions(
11660            "retry_policy.max_attempts must be at least 1".to_string(),
11661        ));
11662    }
11663    Ok(())
11664}
11665
11666fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
11667    ParallelShape::Group(
11668        operations
11669            .iter()
11670            .map(|operation| match operation {
11671                ParallelOperation::Group(children) => parallel_shape(children),
11672                _ => ParallelShape::Leaf,
11673            })
11674            .collect(),
11675    )
11676}
11677
11678fn parallel_descriptors(
11679    operations: Vec<ParallelOperation>,
11680    base_sequence: u64,
11681) -> Result<Vec<ParallelDescriptor>> {
11682    let size = parallel_leaf_count(&operations);
11683    let kind = parallel_group_kind(&operations).unwrap_or("activity");
11684    let mut descriptors = Vec::with_capacity(size);
11685    let mut cursor = 0;
11686
11687    for (index, operation) in operations.into_iter().enumerate() {
11688        match operation {
11689            ParallelOperation::Group(children) => {
11690                let child_base = base_sequence
11691                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
11692                    .ok_or(Error::TimerDurationOverflow)?;
11693                for mut descriptor in parallel_descriptors(children, child_base)? {
11694                    let outer_index = cursor + descriptor.offset;
11695                    descriptor.group_path.insert(
11696                        0,
11697                        parallel_group_entry(base_sequence, size, outer_index, kind),
11698                    );
11699                    descriptor.member_path.insert(0, index);
11700                    descriptor.offset = outer_index;
11701                    descriptors.push(descriptor);
11702                }
11703                cursor = descriptors.len();
11704            }
11705            operation => {
11706                descriptors.push(ParallelDescriptor {
11707                    operation,
11708                    offset: cursor,
11709                    member_path: vec![index],
11710                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
11711                });
11712                cursor += 1;
11713            }
11714        }
11715    }
11716    Ok(descriptors)
11717}
11718
11719enum ParallelLeafCall {
11720    Activity(ActivityCall),
11721    ChildWorkflow(ChildWorkflowCall),
11722    Timer(TimerCall),
11723    Signal(SignalCall),
11724    Condition(ConditionWaitCall),
11725}
11726
11727fn parallel_leaf_call(
11728    ctx: &WorkflowContext,
11729    operation: ParallelOperation,
11730    parallel_group_path: Vec<ParallelGroupMetadata>,
11731) -> ParallelLeafCall {
11732    match operation {
11733        ParallelOperation::Activity {
11734            activity_type,
11735            options,
11736            arguments,
11737        } => ParallelLeafCall::Activity(ActivityCall {
11738            ctx: ctx.clone(),
11739            activity_type,
11740            options,
11741            worker_session: None,
11742            args: Some(arguments),
11743            scheduled: false,
11744            local: false,
11745            local_result: None,
11746            parallel_group_path,
11747        }),
11748        ParallelOperation::ChildWorkflow {
11749            workflow_type,
11750            options,
11751            arguments,
11752        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
11753            ctx: ctx.clone(),
11754            workflow_type,
11755            options,
11756            args: Some(arguments),
11757            scheduled: false,
11758            matched_pending: false,
11759            parallel_group_path,
11760        }),
11761        ParallelOperation::Timer(duration) => {
11762            let delay_seconds = duration
11763                .as_secs()
11764                .checked_add(u64::from(duration.subsec_nanos() > 0));
11765            ParallelLeafCall::Timer(TimerCall {
11766                ctx: ctx.clone(),
11767                delay_seconds,
11768                scheduled: false,
11769                matched_pending: false,
11770                parallel_group_path,
11771            })
11772        }
11773        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
11774            ctx: ctx.clone(),
11775            signal_name,
11776            runtime_reserved_allowed: false,
11777            opened_wait: false,
11778            matched_pending: false,
11779            parallel_group_path,
11780        }),
11781        ParallelOperation::Condition { options, predicate } => {
11782            ParallelLeafCall::Condition(ConditionWaitCall {
11783                ctx: ctx.clone(),
11784                options,
11785                predicate,
11786                occurrence_id: None,
11787                opened_wait: false,
11788                parallel_group_path,
11789            })
11790        }
11791        ParallelOperation::Group(_) => {
11792            unreachable!("parallel descriptors contain only durable leaves")
11793        }
11794    }
11795}
11796
11797impl ParallelLeafCall {
11798    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
11799        match self {
11800            Self::Activity(call) => Pin::new(call)
11801                .poll_avro_value(cx)
11802                .map_ok(ParallelAvroResult::Activity),
11803            Self::ChildWorkflow(call) => Pin::new(call)
11804                .poll_avro_value(cx)
11805                .map_ok(ParallelAvroResult::ChildWorkflow),
11806            Self::Timer(call) => Pin::new(call)
11807                .poll(cx)
11808                .map_ok(|()| ParallelAvroResult::Timer),
11809            Self::Signal(call) => Pin::new(call)
11810                .poll_avro_value(cx)
11811                .map_ok(ParallelAvroResult::Signal),
11812            Self::Condition(call) => Pin::new(call)
11813                .poll(cx)
11814                .map_ok(ParallelAvroResult::Condition),
11815        }
11816    }
11817}
11818
11819struct ParallelLeaf {
11820    call: ParallelLeafCall,
11821    sequence: u64,
11822    member_path: Vec<usize>,
11823    group_path: Vec<ParallelGroupMetadata>,
11824    result: Option<ParallelAvroResult>,
11825}
11826
11827/// Future returned by [`WorkflowContext::parallel`].
11828pub struct ParallelCall {
11829    ctx: WorkflowContext,
11830    operations: Option<Vec<ParallelOperation>>,
11831    shape: Option<ParallelShape>,
11832    leaves: Vec<ParallelLeaf>,
11833    pending_scope_delivery: bool,
11834    worker_session: Option<WorkerSessionOptions>,
11835}
11836
11837impl ParallelCall {
11838    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
11839        Self {
11840            ctx,
11841            operations: Some(operations),
11842            shape: None,
11843            leaves: Vec::new(),
11844            pending_scope_delivery: false,
11845            worker_session: None,
11846        }
11847    }
11848
11849    fn initialize(&mut self) -> Result<()> {
11850        if let Some(session) = &self.worker_session {
11851            session.to_wire()?;
11852        }
11853        let operations = self.operations.take().unwrap_or_default();
11854        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
11855        self.shape = Some(parallel_shape(&operations));
11856        if operations.is_empty() {
11857            return Ok(());
11858        }
11859
11860        let base_sequence = {
11861            let state = self
11862                .ctx
11863                .state
11864                .lock()
11865                .map_err(|_| Error::WorkflowStatePoisoned)?;
11866            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
11867                recorded.sequence()
11868            } else {
11869                let last = state
11870                    .recorded_commands
11871                    .last()
11872                    .map(RecordedCommand::sequence)
11873                    .unwrap_or(0);
11874                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
11875                    .and_then(|sequence| sequence.checked_add(1))
11876                    .ok_or_else(|| {
11877                        Error::InvalidParallelGroup(ParallelGroupError {
11878                            reason: "sequence_overflow",
11879                            member_path: Vec::new(),
11880                            message: "parallel group sequence identity overflowed u64".to_string(),
11881                        })
11882                    })?
11883            }
11884        };
11885
11886        let descriptors = parallel_descriptors(operations, base_sequence)?;
11887        {
11888            let mut state = self
11889                .ctx
11890                .state
11891                .lock()
11892                .map_err(|_| Error::WorkflowStatePoisoned)?;
11893            let cursor = state.command_cursor;
11894            self.ctx.validate_scope_membership(&mut state, cursor)?;
11895            if state.prepare_parallel_scope_cancellation(&descriptors)? {
11896                self.pending_scope_delivery = true;
11897                return Ok(());
11898            }
11899            state.expand_cancellation_group(&descriptors)?;
11900            state.prepare_group_cancellation(&descriptors)?;
11901        }
11902        self.leaves = descriptors
11903            .into_iter()
11904            .map(|descriptor| {
11905                let mut call = parallel_leaf_call(
11906                    &self.ctx,
11907                    descriptor.operation,
11908                    descriptor.group_path.clone(),
11909                );
11910                if let (Some(session), ParallelLeafCall::Activity(activity)) =
11911                    (&self.worker_session, &mut call)
11912                {
11913                    activity.worker_session = Some(session.clone());
11914                }
11915                ParallelLeaf {
11916                    call,
11917                    sequence: base_sequence + descriptor.offset as u64,
11918                    member_path: descriptor.member_path,
11919                    group_path: descriptor.group_path,
11920                    result: None,
11921                }
11922            })
11923            .collect();
11924        Ok(())
11925    }
11926
11927    fn poll_avro_value(
11928        mut self: Pin<&mut Self>,
11929        cx: &mut TaskContext<'_>,
11930    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
11931        if self.operations.is_some() {
11932            if let Err(error) = self.initialize() {
11933                return Poll::Ready(Err(error));
11934            }
11935        }
11936        if self.pending_scope_delivery {
11937            return Poll::Pending;
11938        }
11939        if self.leaves.is_empty() {
11940            return Poll::Ready(Ok(Vec::new()));
11941        }
11942
11943        let mut failures = Vec::new();
11944        let mut pending = false;
11945        for (index, leaf) in self.leaves.iter_mut().enumerate() {
11946            if leaf.result.is_some() {
11947                continue;
11948            }
11949            match leaf.call.poll_avro_value(cx) {
11950                Poll::Ready(Ok(result)) => leaf.result = Some(result),
11951                Poll::Ready(Err(error)) => failures.push((index, error)),
11952                Poll::Pending => pending = true,
11953            }
11954        }
11955
11956        if !failures.is_empty() {
11957            if let Some(position) = failures
11958                .iter()
11959                .position(|(_, error)| workflow_task_integrity_error(error))
11960            {
11961                return Poll::Ready(Err(failures.remove(position).1));
11962            }
11963            if self
11964                .ctx
11965                .state
11966                .lock()
11967                .map_err(|_| Error::WorkflowStatePoisoned)?
11968                .cancellation_delivery_intent
11969                .is_some()
11970            {
11971                return Poll::Pending;
11972            }
11973            if let Some(position) = failures
11974                .iter()
11975                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
11976            {
11977                return Poll::Ready(Err(failures.remove(position).1));
11978            }
11979            failures.sort_by_key(|(index, _)| *index);
11980            let (failed_index, cause) = failures.remove(0);
11981            let failed = &self.leaves[failed_index];
11982            let completed = self
11983                .leaves
11984                .iter()
11985                .filter_map(|leaf| {
11986                    leaf.result
11987                        .clone()
11988                        .and_then(|result| result.into_json_result().ok())
11989                        .map(|result| ParallelCompletion {
11990                            member_path: leaf.member_path.clone(),
11991                            result,
11992                        })
11993                })
11994                .collect();
11995            let group_id = failed
11996                .group_path
11997                .first()
11998                .map(|entry| entry.parallel_group_id.clone())
11999                .unwrap_or_default();
12000            let sequences = self
12001                .leaves
12002                .iter()
12003                .map(|leaf| leaf.sequence)
12004                .collect::<Vec<_>>();
12005            self.ctx
12006                .state
12007                .lock()
12008                .map_err(|_| Error::WorkflowStatePoisoned)?
12009                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12010            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12011                group_id,
12012                member_path: failed.member_path.clone(),
12013                group_path: failed.group_path.clone(),
12014                completed,
12015                cause: Box::new(cause),
12016            })));
12017        }
12018        if pending
12019            || self
12020                .ctx
12021                .state
12022                .lock()
12023                .map_err(|_| Error::WorkflowStatePoisoned)?
12024                .cancellation_delivery_intent
12025                .is_some()
12026        {
12027            return Poll::Pending;
12028        }
12029
12030        let mut flat_results = self
12031            .leaves
12032            .iter_mut()
12033            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12034            .collect::<Vec<_>>()
12035            .into_iter();
12036        let results = parallel_results_for_shape(
12037            self.shape.as_ref().expect("initialized parallel shape"),
12038            &mut flat_results,
12039        );
12040        let sequences = self
12041            .leaves
12042            .iter()
12043            .map(|leaf| leaf.sequence)
12044            .collect::<Vec<_>>();
12045        self.ctx
12046            .state
12047            .lock()
12048            .map_err(|_| Error::WorkflowStatePoisoned)?
12049            .advance_cancellation_sequences(&sequences, None);
12050        Poll::Ready(Ok(match results {
12051            ParallelAvroResult::Group(results) => results,
12052            ParallelAvroResult::Activity(_)
12053            | ParallelAvroResult::ChildWorkflow(_)
12054            | ParallelAvroResult::Timer
12055            | ParallelAvroResult::Signal(_)
12056            | ParallelAvroResult::Condition(_) => {
12057                unreachable!("root parallel shape is a group")
12058            }
12059        }))
12060    }
12061}
12062
12063fn parallel_results_for_shape(
12064    shape: &ParallelShape,
12065    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12066) -> ParallelAvroResult {
12067    match shape {
12068        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12069        ParallelShape::Group(children) => ParallelAvroResult::Group(
12070            children
12071                .iter()
12072                .map(|child| parallel_results_for_shape(child, flat_results))
12073                .collect(),
12074        ),
12075    }
12076}
12077
12078impl Future for ParallelCall {
12079    type Output = Result<Vec<ParallelResult>>;
12080
12081    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12082        self.poll_avro_value(cx)
12083            .map_ok(|results| {
12084                results
12085                    .into_iter()
12086                    .map(ParallelAvroResult::into_json_result)
12087                    .collect::<Result<Vec<_>>>()
12088            })
12089            .map_ok(|result| result)
12090            .flatten_result()
12091    }
12092}
12093
12094#[derive(Clone, Debug)]
12095struct SelectionMemberPlan {
12096    key: SelectionKey,
12097    index: usize,
12098    base_sequence: u64,
12099    size: usize,
12100    kind: String,
12101    shape: ParallelShape,
12102    leaf_start: usize,
12103}
12104
12105fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12106    match operation {
12107        ParallelOperation::Activity { .. } => "activity",
12108        ParallelOperation::ChildWorkflow { .. } => "child",
12109        ParallelOperation::Timer(_) => "timer",
12110        ParallelOperation::Signal(_) => "signal",
12111        ParallelOperation::Condition { .. } => "condition",
12112        ParallelOperation::Group(_) => "group",
12113    }
12114}
12115
12116fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12117    match operation {
12118        ParallelOperation::Group(children) => parallel_shape(children),
12119        _ => ParallelShape::Leaf,
12120    }
12121}
12122
12123fn selection_descriptors(
12124    operations: Vec<(SelectionKey, ParallelOperation)>,
12125    base_sequence: u64,
12126) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12127    if operations.is_empty() {
12128        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12129            reason: "selection_empty",
12130            member_path: Vec::new(),
12131            message: "durable selection requires at least one operation".to_string(),
12132        }));
12133    }
12134    let operation_refs = operations
12135        .iter()
12136        .map(|(_, operation)| operation)
12137        .collect::<Vec<_>>();
12138    let total_size = operation_refs
12139        .iter()
12140        .map(|operation| match operation {
12141            ParallelOperation::Group(children) => parallel_leaf_count(children),
12142            _ => 1,
12143        })
12144        .sum::<usize>();
12145    if total_size > MAX_PARALLEL_OPERATIONS {
12146        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12147            reason: "fan_out_limit_exceeded",
12148            member_path: Vec::new(),
12149            message: format!(
12150                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12151            ),
12152        }));
12153    }
12154    let group_kind = {
12155        let mut kind = None;
12156        for operation in &operation_refs {
12157            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12158            match kind {
12159                None => kind = Some(operation_kind),
12160                Some(current) if current == operation_kind => {}
12161                Some(_) => {
12162                    kind = Some("mixed");
12163                    break;
12164                }
12165            }
12166        }
12167        kind.unwrap_or("mixed")
12168    };
12169
12170    let mut descriptors = Vec::with_capacity(total_size);
12171    let mut members = Vec::with_capacity(operations.len());
12172    let mut cursor = 0usize;
12173    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12174    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12175        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12176            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12177                reason: "selection_key_invalid",
12178                member_path: vec![member_index],
12179                message: "selection member keys must be non-empty strings or non-negative integers"
12180                    .to_string(),
12181            }));
12182        }
12183        if seen_keys.contains(&key) {
12184            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12185                reason: "selection_key_duplicate",
12186                member_path: vec![member_index],
12187                message: format!("selection member key {key:?} is duplicated"),
12188            }));
12189        }
12190        seen_keys.push(key.clone());
12191        let member_size = match &operation {
12192            ParallelOperation::Group(children) => parallel_leaf_count(children),
12193            _ => 1,
12194        };
12195        if member_size == 0 {
12196            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12197                reason: "selection_member_empty",
12198                member_path: vec![member_index],
12199                message: "a selection member must contain at least one durable leaf".to_string(),
12200            }));
12201        }
12202        let member_base = base_sequence
12203            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12204            .ok_or(Error::TimerDurationOverflow)?;
12205        let member_kind = selection_operation_kind(&operation).to_string();
12206        let member_shape = selection_operation_shape(&operation);
12207        let leaf_start = descriptors.len();
12208        match operation {
12209            ParallelOperation::Group(children) => {
12210                validate_parallel_operations(&children, &mut vec![member_index], false)?;
12211                for mut descriptor in parallel_descriptors(children, member_base)? {
12212                    let flat_index = cursor + descriptor.offset;
12213                    descriptor.group_path.insert(
12214                        0,
12215                        selection_group_entry(
12216                            base_sequence,
12217                            total_size,
12218                            flat_index,
12219                            group_kind,
12220                            &SelectionMemberMetadata {
12221                                key: key.clone(),
12222                                index: member_index,
12223                                base_sequence: member_base,
12224                                size: member_size,
12225                                kind: member_kind.clone(),
12226                            },
12227                        ),
12228                    );
12229                    descriptor.member_path.insert(0, member_index);
12230                    descriptor.offset = flat_index;
12231                    descriptors.push(descriptor);
12232                }
12233            }
12234            operation => {
12235                validate_parallel_operations(
12236                    std::slice::from_ref(&operation),
12237                    &mut Vec::new(),
12238                    true,
12239                )?;
12240                descriptors.push(ParallelDescriptor {
12241                    operation,
12242                    offset: cursor,
12243                    member_path: vec![member_index],
12244                    group_path: vec![selection_group_entry(
12245                        base_sequence,
12246                        total_size,
12247                        cursor,
12248                        group_kind,
12249                        &SelectionMemberMetadata {
12250                            key: key.clone(),
12251                            index: member_index,
12252                            base_sequence: member_base,
12253                            size: member_size,
12254                            kind: member_kind.clone(),
12255                        },
12256                    )],
12257                });
12258            }
12259        }
12260        members.push(SelectionMemberPlan {
12261            key,
12262            index: member_index,
12263            base_sequence: member_base,
12264            size: member_size,
12265            kind: member_kind,
12266            shape: member_shape,
12267            leaf_start,
12268        });
12269        cursor += member_size;
12270    }
12271    Ok((descriptors, members))
12272}
12273
12274struct SelectionLeaf {
12275    call: ParallelLeafCall,
12276    outcome: Option<Result<ParallelAvroResult>>,
12277}
12278
12279/// Stable reference to one member of a durable selection group.
12280#[derive(Clone)]
12281pub struct DurableOperationHandle {
12282    ctx: WorkflowContext,
12283    pub key: SelectionKey,
12284    pub index: usize,
12285    pub kind: String,
12286    pub identity: String,
12287    pub base_sequence: u64,
12288    pub size: usize,
12289    pub selection_group_id: String,
12290    shape: ParallelShape,
12291}
12292
12293impl std::fmt::Debug for DurableOperationHandle {
12294    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12295        formatter
12296            .debug_struct("DurableOperationHandle")
12297            .field("key", &self.key)
12298            .field("index", &self.index)
12299            .field("kind", &self.kind)
12300            .field("identity", &self.identity)
12301            .field("base_sequence", &self.base_sequence)
12302            .field("size", &self.size)
12303            .field("selection_group_id", &self.selection_group_id)
12304            .finish()
12305    }
12306}
12307
12308impl DurableOperationHandle {
12309    /// Await this member after another member has already won the selection.
12310    pub fn await_result(&self) -> DurableOperationAwaitCall {
12311        DurableOperationAwaitCall {
12312            handle: self.clone(),
12313        }
12314    }
12315
12316    /// Request cancellation without affecting siblings. The future resolves
12317    /// to unit; only `SelectionOperationCancelled` history proves cancellation
12318    /// beat a concurrently committed terminal result.
12319    pub fn cancel(&self) -> CancelDurableOperationCall {
12320        CancelDurableOperationCall {
12321            handle: self.clone(),
12322            emitted: false,
12323        }
12324    }
12325}
12326
12327/// The one winner committed for a durable selection group.
12328#[derive(Debug)]
12329pub struct SelectionResult {
12330    pub key: SelectionKey,
12331    pub index: usize,
12332    pub kind: String,
12333    pub identity: String,
12334    pub value: Option<ParallelResult>,
12335    pub failure: Option<Error>,
12336    pub winner: DurableOperationHandle,
12337    pub handles: Vec<DurableOperationHandle>,
12338}
12339
12340impl SelectionResult {
12341    pub fn succeeded(&self) -> bool {
12342        self.failure.is_none()
12343    }
12344
12345    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
12346        self.handles.iter().find(|handle| &handle.key == key)
12347    }
12348
12349    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
12350        self.handles
12351            .iter()
12352            .filter(|handle| handle.index != self.index)
12353            .collect()
12354    }
12355
12356    pub fn into_result(self) -> Result<ParallelResult> {
12357        match (self.value, self.failure) {
12358            (Some(value), None) => Ok(value),
12359            (_, Some(error)) => Err(error),
12360            _ => Err(Error::WorkerLoop(
12361                "selection result contained neither a value nor a failure".to_string(),
12362            )),
12363        }
12364    }
12365}
12366
12367/// Future returned by [`WorkflowContext::select`].
12368pub struct SelectCall {
12369    ctx: WorkflowContext,
12370    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
12371    members: Vec<SelectionMemberPlan>,
12372    leaves: Vec<SelectionLeaf>,
12373    group_id: Option<String>,
12374}
12375
12376impl SelectCall {
12377    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
12378        Self {
12379            ctx,
12380            operations: Some(operations),
12381            members: Vec::new(),
12382            leaves: Vec::new(),
12383            group_id: None,
12384        }
12385    }
12386
12387    fn initialize(&mut self) -> Result<()> {
12388        let operations = self.operations.take().unwrap_or_default();
12389        let base_sequence = {
12390            let state = self
12391                .ctx
12392                .state
12393                .lock()
12394                .map_err(|_| Error::WorkflowStatePoisoned)?;
12395            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
12396                state.recorded_commands.get(state.command_cursor)
12397            {
12398                *sequence
12399            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
12400            {
12401                marker.selection_group_base_sequence
12402            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12403                recorded.sequence()
12404            } else {
12405                let last = state
12406                    .recorded_commands
12407                    .last()
12408                    .map(RecordedCommand::sequence)
12409                    .unwrap_or(0);
12410                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12411                    .and_then(|sequence| sequence.checked_add(1))
12412                    .ok_or(Error::TimerDurationOverflow)?
12413            }
12414        };
12415        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
12416        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
12417        {
12418            let mut state = self
12419                .ctx
12420                .state
12421                .lock()
12422                .map_err(|_| Error::WorkflowStatePoisoned)?;
12423            state.expand_cancellation_group(&descriptors)?;
12424            state.prepare_group_cancellation(&descriptors)?;
12425        }
12426        self.leaves = descriptors
12427            .into_iter()
12428            .map(|descriptor| SelectionLeaf {
12429                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
12430                outcome: None,
12431            })
12432            .collect();
12433        self.members = members;
12434        self.group_id = Some(group_id);
12435        Ok(())
12436    }
12437}
12438
12439impl Future for SelectCall {
12440    type Output = Result<SelectionResult>;
12441
12442    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12443        if self.operations.is_some() {
12444            if let Err(error) = self.initialize() {
12445                return Poll::Ready(Err(error));
12446            }
12447        }
12448
12449        for leaf in &mut self.leaves {
12450            if leaf.outcome.is_some() {
12451                continue;
12452            }
12453            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
12454                if outcome
12455                    .as_ref()
12456                    .err()
12457                    .is_some_and(workflow_task_integrity_error)
12458                {
12459                    return Poll::Ready(outcome.map(|_| unreachable!()));
12460                }
12461                leaf.outcome = Some(outcome);
12462            }
12463        }
12464
12465        if self
12466            .ctx
12467            .state
12468            .lock()
12469            .map_err(|_| Error::WorkflowStatePoisoned)?
12470            .cancellation_delivery_intent
12471            .is_some()
12472        {
12473            return Poll::Pending;
12474        }
12475
12476        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
12477            matches!(
12478                leaf.outcome,
12479                Some(Err(Error::CooperativeCancellationRequested(_)))
12480            )
12481        }) {
12482            return Poll::Ready(
12483                leaf.outcome
12484                    .take()
12485                    .expect("matched cancellation")
12486                    .map(|_| unreachable!()),
12487            );
12488        }
12489
12490        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
12491        let selection_member_range = self
12492            .members
12493            .first()
12494            .map(|member| member.base_sequence)
12495            .zip(self.leaves.len().try_into().ok())
12496            .map(|(base_sequence, size): (u64, u64)| {
12497                base_sequence..base_sequence.saturating_add(size)
12498            });
12499        let marker = {
12500            let mut state = match self.ctx.state.lock() {
12501                Ok(state) => state,
12502                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12503            };
12504            let marker = state
12505                .selection_markers
12506                .get(state.selection_marker_cursor)
12507                .cloned();
12508            if marker.is_none()
12509                && all_members_terminal
12510                && selection_member_range.as_ref().is_some_and(|member_range| {
12511                    state
12512                        .recorded_commands
12513                        .iter()
12514                        .any(|command| member_range.contains(&command.sequence()))
12515                })
12516            {
12517                // Terminal member history can be committed before the server's
12518                // SelectionResolved marker becomes visible to this task. That
12519                // marker is the durable barrier the selection is still waiting
12520                // on, so an otherwise commandless replay remains legitimately
12521                // pending instead of failing as an untracked yield.
12522                state.matched_recorded_pending = true;
12523            }
12524            marker
12525        };
12526        let Some(marker) = marker else {
12527            return Poll::Pending;
12528        };
12529        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
12530            || marker.selection_group_size != self.leaves.len()
12531            || self.members.first().map(|member| member.base_sequence)
12532                != Some(marker.selection_group_base_sequence)
12533        {
12534            return Poll::Ready(Err(invalid_recorded_history(
12535                "selection_group_shape_mismatch",
12536                marker.selection_group_base_sequence,
12537                self.group_id
12538                    .as_deref()
12539                    .unwrap_or("initialized selection group"),
12540                &marker.selection_group_id,
12541                "recorded selection group differs from current workflow code",
12542            )));
12543        }
12544        let Some(member_position) = self.members.iter().position(|member| {
12545            member.key == marker.member_key
12546                && member.index == marker.member_index
12547                && member.base_sequence == marker.member_base_sequence
12548                && member.size == marker.member_size
12549                && member.kind == marker.operation_kind
12550        }) else {
12551            return Poll::Ready(Err(invalid_recorded_history(
12552                "selection_member_shape_mismatch",
12553                marker.member_base_sequence,
12554                "winner member matching current workflow code",
12555                &format!("{:?}", marker.member_key),
12556                "recorded selection winner differs from the authored member identity",
12557            )));
12558        };
12559        let member = self.members[member_position].clone();
12560        let (handles, resolution_sequence) = {
12561            let mut state = match self.ctx.state.lock() {
12562                Ok(state) => state,
12563                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12564            };
12565            let identities = self
12566                .members
12567                .iter()
12568                .map(|candidate| {
12569                    selection_operation_identity(
12570                        &state,
12571                        &candidate.kind,
12572                        candidate.base_sequence,
12573                        candidate.size,
12574                    )
12575                })
12576                .collect::<Vec<_>>();
12577            if let Some((position, missing)) = identities
12578                .iter()
12579                .enumerate()
12580                .find(|(_, identity)| identity.is_empty())
12581                .map(|(position, identity)| (position, identity.clone()))
12582            {
12583                let candidate = &self.members[position];
12584                return Poll::Ready(Err(invalid_recorded_history(
12585                    "selection_operation_identity_missing",
12586                    candidate.base_sequence,
12587                    &format!(
12588                        "durable {} resource identity from scheduled/open history",
12589                        candidate.kind
12590                    ),
12591                    &missing,
12592                    "selection member history is missing its canonical durable identity",
12593                )));
12594            }
12595            let expected_winner_identity = &identities[member_position];
12596            let resolution_sequence = match validated_selection_resolution_sequence(
12597                &state,
12598                &marker,
12599                &member,
12600                expected_winner_identity,
12601            ) {
12602                Ok(sequence) => sequence,
12603                Err(error) => return Poll::Ready(Err(error)),
12604            };
12605            let handles = self
12606                .members
12607                .iter()
12608                .zip(identities)
12609                .map(|(member, identity)| DurableOperationHandle {
12610                    ctx: self.ctx.clone(),
12611                    key: member.key.clone(),
12612                    index: member.index,
12613                    kind: member.kind.clone(),
12614                    identity,
12615                    base_sequence: member.base_sequence,
12616                    size: member.size,
12617                    selection_group_id: marker.selection_group_id.clone(),
12618                    shape: member.shape.clone(),
12619                })
12620                .collect::<Vec<_>>();
12621            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
12622                return Poll::Ready(Err(error));
12623            }
12624            state.selection_marker_cursor += 1;
12625            (handles, resolution_sequence)
12626        };
12627
12628        let mut winner_failure = None;
12629        let mut flat_results = Vec::with_capacity(member.size);
12630        if marker.outcome == "failed" {
12631            let resolution_offset = match resolution_sequence
12632                .checked_sub(member.base_sequence)
12633                .and_then(|offset| usize::try_from(offset).ok())
12634            {
12635                Some(offset) if offset < member.size => offset,
12636                _ => {
12637                    return Poll::Ready(Err(invalid_recorded_history(
12638                        "selection_resolution_event_mismatch",
12639                        member.base_sequence,
12640                        "failure event within selected member bounds",
12641                        &resolution_sequence.to_string(),
12642                        "selection failure event is outside the authored member",
12643                    )))
12644                }
12645            };
12646            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
12647            match leaf.outcome.take() {
12648                Some(Err(error)) => winner_failure = Some(error),
12649                _ => {
12650                    return Poll::Ready(Err(invalid_recorded_history(
12651                        "selection_winner_outcome_mismatch",
12652                        member.base_sequence,
12653                        "exact failed terminal history referenced by SelectionResolved",
12654                        "missing or successful resolution event",
12655                        "selection winner marker disagrees with terminal operation history",
12656                    )))
12657                }
12658            }
12659        } else {
12660            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
12661                match leaf.outcome.take() {
12662                    Some(Ok(result)) => flat_results.push(result),
12663                    Some(Err(_)) => {
12664                        return Poll::Ready(Err(invalid_recorded_history(
12665                            "selection_winner_outcome_mismatch",
12666                            member.base_sequence,
12667                            "fully completed nested selection member",
12668                            "failed durable leaf",
12669                            "completed selection winner contains a failed leaf",
12670                        )))
12671                    }
12672                    None => {
12673                        return Poll::Ready(Err(invalid_recorded_history(
12674                            "selection_winner_unresolved",
12675                            member.base_sequence,
12676                            "terminal history for every completed winner leaf",
12677                            "pending member history",
12678                            "completed SelectionResolved member has an unfinished durable barrier",
12679                        )))
12680                    }
12681                }
12682            }
12683        }
12684        let value = if winner_failure.is_none() {
12685            let mut flat_results = flat_results.into_iter();
12686            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
12687            match value.into_json_result() {
12688                Ok(value) => Some(value),
12689                Err(error) => return Poll::Ready(Err(error)),
12690            }
12691        } else {
12692            None
12693        };
12694        let winner = handles[member_position].clone();
12695        self.ctx
12696            .state
12697            .lock()
12698            .map_err(|_| Error::WorkflowStatePoisoned)?
12699            .advance_cancellation_selection(&marker.selection_group_id);
12700        Poll::Ready(Ok(SelectionResult {
12701            key: winner.key.clone(),
12702            index: winner.index,
12703            kind: winner.kind.clone(),
12704            identity: winner.identity.clone(),
12705            value,
12706            failure: winner_failure,
12707            winner,
12708            handles,
12709        }))
12710    }
12711}
12712
12713fn selection_operation_identity(
12714    state: &WorkflowState,
12715    kind: &str,
12716    base_sequence: u64,
12717    size: usize,
12718) -> String {
12719    if kind == "group" {
12720        return format!("group:{base_sequence}:{size}");
12721    }
12722    let fields: &[&str] = match kind {
12723        "activity" => &["activity_execution_id"],
12724        "child" => &["child_workflow_run_id"],
12725        "timer" => &["timer_id"],
12726        "signal" => &["signal_wait_id"],
12727        "condition" => &["condition_wait_id"],
12728        _ => &[],
12729    };
12730    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
12731        for event in state
12732            .history_events
12733            .iter()
12734            .filter(|event| durable_event_sequence(event) == Some(sequence))
12735        {
12736            for field in fields {
12737                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
12738                    if !identity.is_empty() {
12739                        return identity.to_string();
12740                    }
12741                }
12742            }
12743        }
12744    }
12745    String::new()
12746}
12747
12748fn validated_selection_resolution_sequence(
12749    state: &WorkflowState,
12750    marker: &SelectionMarker,
12751    member: &SelectionMemberPlan,
12752    expected_identity: &str,
12753) -> Result<u64> {
12754    if expected_identity.is_empty() {
12755        return Err(invalid_recorded_history(
12756            "selection_operation_identity_missing",
12757            member.base_sequence,
12758            &format!(
12759                "durable {} resource identity from scheduled/open history",
12760                member.kind
12761            ),
12762            "missing operation identity",
12763            "selection member history is missing its canonical durable identity",
12764        ));
12765    }
12766    if marker.operation_identity != expected_identity {
12767        return Err(invalid_recorded_history(
12768            "selection_operation_identity_mismatch",
12769            member.base_sequence,
12770            expected_identity,
12771            &marker.operation_identity,
12772            "selection winner identity does not match durable scheduled/open history",
12773        ));
12774    }
12775
12776    let failure_types = [
12777        "ActivityFailed",
12778        "ActivityCancelled",
12779        "ActivityTimedOut",
12780        "ChildRunFailed",
12781        "ChildRunCancelled",
12782        "ChildRunTerminated",
12783    ];
12784    let success_types = [
12785        "ActivityCompleted",
12786        "ChildRunCompleted",
12787        "TimerFired",
12788        "SignalApplied",
12789        "ConditionWaitSatisfied",
12790        "ConditionWaitTimedOut",
12791    ];
12792    let terminal_types: &[&str] = if marker.outcome == "failed" {
12793        &failure_types
12794    } else {
12795        &success_types
12796    };
12797    let mut candidates = Vec::new();
12798    let member_commands = (member.base_sequence
12799        ..member.base_sequence.saturating_add(member.size as u64))
12800        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
12801        .map(|command| (command.sequence(), command))
12802        .collect::<BTreeMap<_, _>>();
12803    let mut resolved_conditions = BTreeSet::new();
12804    for event in state.history_events.iter() {
12805        let Some(sequence) = durable_event_sequence(event) else {
12806            continue;
12807        };
12808        let Some(command) = member_commands.get(&sequence) else {
12809            continue;
12810        };
12811        if !terminal_types.contains(&event.event_type.as_str()) {
12812            continue;
12813        }
12814        if matches!(command, RecordedCommand::ConditionWait { .. }) {
12815            if !matches!(
12816                event.event_type.as_str(),
12817                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
12818            ) && !(event.event_type == "TimerFired"
12819                && event.payload.get("timer_kind").and_then(Value::as_str)
12820                    == Some("condition_timeout"))
12821            {
12822                continue;
12823            }
12824            if !resolved_conditions.insert(sequence) {
12825                continue;
12826            }
12827        }
12828        let event_id = event
12829            .raw
12830            .get("id")
12831            .or_else(|| event.raw.get("event_id"))
12832            .and_then(Value::as_str)
12833            .filter(|value| !value.is_empty())
12834            .ok_or_else(|| {
12835                invalid_recorded_history(
12836                    "selection_resolution_event_id_missing",
12837                    member.base_sequence,
12838                    "terminal selection history with a durable event id",
12839                    &event.payload.to_string(),
12840                    "selection terminal history cannot be bound to its winner marker",
12841                )
12842            })?;
12843        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
12844    }
12845    let resolution = if marker.outcome == "failed" {
12846        candidates.first()
12847    } else {
12848        candidates.last()
12849    };
12850    let Some((event_id, event_type, sequence)) = resolution else {
12851        return Err(invalid_recorded_history(
12852            "selection_resolution_event_missing",
12853            member.base_sequence,
12854            "terminal history for the selected member",
12855            &format!("{:?}", marker.member_key),
12856            "selection winner marker has no matching durable terminal event",
12857        ));
12858    };
12859    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
12860        return Err(invalid_recorded_history(
12861            "selection_resolution_event_mismatch",
12862            member.base_sequence,
12863            &format!("{event_type}:{event_id}"),
12864            &format!(
12865                "{}:{}",
12866                marker.resolution_event_type, marker.resolution_event_id
12867            ),
12868            "selection winner marker does not reference the event that made its member terminal",
12869        ));
12870    }
12871    Ok(*sequence)
12872}
12873
12874fn selection_member_recorded_command(
12875    state: &WorkflowState,
12876    authored_sequence: u64,
12877) -> Option<&RecordedCommand> {
12878    let original = state
12879        .recorded_commands
12880        .iter()
12881        .find(|command| command.sequence() == authored_sequence)?;
12882    let RecordedCommand::ConditionWait {
12883        occurrence_id,
12884        parallel_group_path: Some(_),
12885        ..
12886    } = original
12887    else {
12888        return Some(original);
12889    };
12890    // Decoding proves each physical reopen has the same authored identity and
12891    // group path after a satisfied predecessor. Only its latest wait can make
12892    // this logical member terminal.
12893    state
12894        .recorded_commands
12895        .iter()
12896        .filter(|command| {
12897            matches!(command, RecordedCommand::ConditionWait {
12898                occurrence_id: candidate, ..
12899            } if candidate == occurrence_id)
12900        })
12901        .max_by_key(|command| command.sequence())
12902}
12903
12904fn recorded_selection_member_outcome(
12905    state: &WorkflowState,
12906    handle: &DurableOperationHandle,
12907) -> Result<Option<ParallelResult>> {
12908    for event in state.history_events.iter() {
12909        let Some(sequence) = durable_event_sequence(event) else {
12910            continue;
12911        };
12912        if sequence < handle.base_sequence
12913            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
12914            || !matches!(
12915                event.event_type.as_str(),
12916                "ActivityFailed"
12917                    | "ActivityCancelled"
12918                    | "ActivityTimedOut"
12919                    | "ChildRunFailed"
12920                    | "ChildRunCancelled"
12921                    | "ChildRunTerminated"
12922            )
12923        {
12924            continue;
12925        }
12926        let Some(command) = state
12927            .recorded_commands
12928            .iter()
12929            .find(|command| command.sequence() == sequence)
12930        else {
12931            continue;
12932        };
12933        match command {
12934            RecordedCommand::Activity {
12935                outcome: Some(Err(failure)),
12936                ..
12937            } => return Err(Error::ActivityFailed(failure.clone())),
12938            RecordedCommand::ChildWorkflow {
12939                outcome: Some(Err(failure)),
12940                ..
12941            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
12942            _ => {}
12943        }
12944    }
12945
12946    let mut results = Vec::with_capacity(handle.size);
12947    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
12948        let Some(command) = selection_member_recorded_command(state, sequence) else {
12949            return Ok(None);
12950        };
12951        let result = match command {
12952            RecordedCommand::Activity { outcome, .. } => match outcome {
12953                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
12954                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
12955                None => return Ok(None),
12956            },
12957            RecordedCommand::Timer { fired, .. } => {
12958                if !fired {
12959                    return Ok(None);
12960                }
12961                ParallelAvroResult::Timer
12962            }
12963            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
12964                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
12965                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
12966                None => return Ok(None),
12967            },
12968            RecordedCommand::SignalWait { value, .. } => match value {
12969                Some(value) => ParallelAvroResult::Signal(value.clone()),
12970                None => return Ok(None),
12971            },
12972            RecordedCommand::ConditionWait { result, .. } => match result {
12973                Some(result) => ParallelAvroResult::Condition(*result),
12974                None => return Ok(None),
12975            },
12976            other => {
12977                return Err(command_mismatch(
12978                    other,
12979                    format!("selected {} member", handle.kind),
12980                ))
12981            }
12982        };
12983        results.push(result);
12984    }
12985    let mut results = results.into_iter();
12986    parallel_results_for_shape(&handle.shape, &mut results)
12987        .into_json_result()
12988        .map(Some)
12989}
12990
12991fn recorded_selection_member_is_terminal(
12992    state: &WorkflowState,
12993    handle: &DurableOperationHandle,
12994) -> bool {
12995    let mut completed = 0usize;
12996    let mut all_completed = true;
12997    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
12998        let Some(command) = selection_member_recorded_command(state, sequence) else {
12999            all_completed = false;
13000            continue;
13001        };
13002        let terminal = match command {
13003            RecordedCommand::Activity {
13004                outcome: Some(Err(_)),
13005                ..
13006            }
13007            | RecordedCommand::ChildWorkflow {
13008                outcome: Some(Err(_)),
13009                ..
13010            } => return true,
13011            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13012            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13013            RecordedCommand::Timer { fired, .. } => *fired,
13014            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13015            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13016            RecordedCommand::SearchAttributes { .. }
13017            | RecordedCommand::CancellationScope { .. }
13018            | RecordedCommand::SideEffect { .. }
13019            | RecordedCommand::VersionMarker { .. }
13020            | RecordedCommand::Memo { .. }
13021            | RecordedCommand::CancellationBoundary { .. }
13022            | RecordedCommand::CancellationGroup { .. } => false,
13023        };
13024        if !terminal {
13025            all_completed = false;
13026            continue;
13027        }
13028        completed += 1;
13029    }
13030    all_completed && completed == handle.size
13031}
13032
13033fn selection_cancellation_for_handle(
13034    state: &WorkflowState,
13035    handle: &DurableOperationHandle,
13036) -> Result<bool> {
13037    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13038        recorded.selection_group_id == handle.selection_group_id
13039            && recorded.member_base_sequence == handle.base_sequence
13040    }) else {
13041        return Ok(false);
13042    };
13043    validate_selection_cancellation_marker(marker, handle)?;
13044    Ok(true)
13045}
13046
13047fn validate_selection_cancellations_for_handles(
13048    state: &WorkflowState,
13049    handles: &[DurableOperationHandle],
13050) -> Result<()> {
13051    let Some(group_id) = handles
13052        .first()
13053        .map(|handle| handle.selection_group_id.as_str())
13054    else {
13055        return Ok(());
13056    };
13057    for marker in state
13058        .cancelled_selection_members
13059        .iter()
13060        .filter(|marker| marker.selection_group_id == group_id)
13061    {
13062        let Some(handle) = handles
13063            .iter()
13064            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13065        else {
13066            return Err(invalid_recorded_history(
13067                "selection_cancellation_member_mismatch",
13068                marker.member_base_sequence,
13069                "SelectionOperationCancelled matching an authored selection handle",
13070                &format!("{marker:?}"),
13071                "selection cancellation member base does not name an authored member",
13072            ));
13073        };
13074        validate_selection_cancellation_marker(marker, handle)?;
13075    }
13076    Ok(())
13077}
13078
13079fn validate_selection_cancellation_marker(
13080    marker: &SelectionCancellation,
13081    handle: &DurableOperationHandle,
13082) -> Result<()> {
13083    if marker.selection_group_id != handle.selection_group_id
13084        || marker.member_key != handle.key
13085        || marker.member_index != handle.index
13086        || marker.member_base_sequence != handle.base_sequence
13087        || marker.member_size != handle.size
13088        || marker.operation_kind != handle.kind
13089        || marker.operation_identity != handle.identity
13090    {
13091        return Err(invalid_recorded_history(
13092            "selection_cancellation_member_mismatch",
13093            handle.base_sequence,
13094            "SelectionOperationCancelled matching the authored selection handle",
13095            &format!("{marker:?}"),
13096            "selection cancellation history targets different authored member metadata",
13097        ));
13098    }
13099    Ok(())
13100}
13101
13102/// Future returned by [`DurableOperationHandle::await_result`].
13103pub struct DurableOperationAwaitCall {
13104    handle: DurableOperationHandle,
13105}
13106
13107impl Future for DurableOperationAwaitCall {
13108    type Output = Result<ParallelResult>;
13109
13110    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13111        let mut state = match self.handle.ctx.state.lock() {
13112            Ok(state) => state,
13113            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13114        };
13115        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13116            return Poll::Ready(Err(error));
13117        }
13118        match state.prepare_selection_handle_cancellation(&self.handle) {
13119            Ok(true) => return Poll::Pending,
13120            Ok(false) => {}
13121            Err(error) => return Poll::Ready(Err(error)),
13122        }
13123        match selection_cancellation_for_handle(&state, &self.handle) {
13124            Err(error) => return Poll::Ready(Err(error)),
13125            Ok(false) => {}
13126            Ok(true) => {
13127                state.advance_cancellation_receipt(
13128                    &self.handle.selection_group_id,
13129                    self.handle.base_sequence,
13130                );
13131                return Poll::Ready(Err(Error::DurableOperationCancelled(
13132                    DurableOperationCancelled {
13133                        selection_group_id: self.handle.selection_group_id.clone(),
13134                        member_key: self.handle.key.clone(),
13135                        member_index: self.handle.index,
13136                        operation_kind: self.handle.kind.clone(),
13137                        operation_identity: self.handle.identity.clone(),
13138                    },
13139                )));
13140            }
13141        }
13142        match recorded_selection_member_outcome(&state, &self.handle) {
13143            Ok(Some(result)) => {
13144                state.advance_cancellation_handle(&self.handle, false);
13145                Poll::Ready(Ok(result))
13146            }
13147            Ok(None) => Poll::Pending,
13148            Err(error) => {
13149                if !workflow_task_integrity_error(&error) {
13150                    state.advance_cancellation_handle(&self.handle, true);
13151                }
13152                Poll::Ready(Err(error))
13153            }
13154        }
13155    }
13156}
13157
13158fn validate_selection_delivery_handle(
13159    state: &WorkflowState,
13160    handle: &DurableOperationHandle,
13161) -> Result<()> {
13162    let path = state
13163        .recorded_commands
13164        .iter()
13165        .find(|command| command.sequence() == handle.base_sequence)
13166        .and_then(|command| match command {
13167            RecordedCommand::Activity {
13168                parallel_group_path,
13169                ..
13170            }
13171            | RecordedCommand::ChildWorkflow {
13172                parallel_group_path,
13173                ..
13174            }
13175            | RecordedCommand::Timer {
13176                parallel_group_path,
13177                ..
13178            }
13179            | RecordedCommand::SignalWait {
13180                parallel_group_path,
13181                ..
13182            }
13183            | RecordedCommand::ConditionWait {
13184                parallel_group_path,
13185                ..
13186            } => parallel_group_path.as_ref(),
13187            _ => None,
13188        })
13189        .and_then(|path| path.first());
13190    let matches = path.is_some_and(|entry| {
13191        entry.parallel_group_mode.as_deref() == Some("select")
13192            && entry.parallel_group_id == handle.selection_group_id
13193            && entry.selection_member_key.as_ref() == Some(&handle.key)
13194            && entry.selection_member_index == Some(handle.index)
13195            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13196            && entry.selection_member_size == Some(handle.size)
13197            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13198    });
13199    if !matches
13200        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13201            != handle.identity
13202    {
13203        return Err(invalid_recorded_history(
13204            "cooperative_cancellation_call_mismatch",
13205            handle.base_sequence,
13206            "selection handle matching its authored durable identity",
13207            &format!("{handle:?}"),
13208            "selection handle identity or member metadata changed before cancellation replay",
13209        ));
13210    }
13211    Ok(())
13212}
13213
13214/// Future returned by [`DurableOperationHandle::cancel`].
13215pub struct CancelDurableOperationCall {
13216    handle: DurableOperationHandle,
13217    emitted: bool,
13218}
13219
13220impl Future for CancelDurableOperationCall {
13221    type Output = Result<()>;
13222
13223    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13224        let ctx = self.handle.ctx.clone();
13225        let mut state = match ctx.state.lock() {
13226            Ok(state) => state,
13227            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13228        };
13229        match selection_cancellation_for_handle(&state, &self.handle) {
13230            Err(error) => return Poll::Ready(Err(error)),
13231            Ok(true) => {
13232                state.advance_cancellation_receipt(
13233                    &self.handle.selection_group_id,
13234                    self.handle.base_sequence,
13235                );
13236                return Poll::Ready(Ok(()));
13237            }
13238            Ok(false) => {}
13239        }
13240        if recorded_selection_member_is_terminal(&state, &self.handle) {
13241            return Poll::Ready(Ok(()));
13242        }
13243        if !self.emitted {
13244            state.commands.push(json!({
13245                "type": "cancel_selection_operation",
13246                "selection_group_id": self.handle.selection_group_id,
13247                "member_key": self.handle.key,
13248                "member_index": self.handle.index,
13249                "member_base_sequence": self.handle.base_sequence,
13250                "member_size": self.handle.size,
13251                "operation_kind": self.handle.kind,
13252                "operation_identity": self.handle.identity,
13253            }));
13254            self.emitted = true;
13255        }
13256        // The cancellation command is only a request. Do not expose workflow
13257        // state after cancel until committed SelectionOperationCancelled
13258        // history proves that the request won the race with member completion.
13259        Poll::Pending
13260    }
13261}
13262
13263trait PollNestedResultExt<T> {
13264    fn flatten_result(self) -> Poll<Result<T>>;
13265}
13266
13267impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
13268    fn flatten_result(self) -> Poll<Result<T>> {
13269        match self {
13270            Poll::Ready(Ok(result)) => Poll::Ready(result),
13271            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13272            Poll::Pending => Poll::Pending,
13273        }
13274    }
13275}
13276
13277struct SagaCompensation {
13278    activity_type: String,
13279    options: ActivityOptions,
13280    arguments: AvroValue,
13281    registration_order: usize,
13282}
13283
13284/// Workflow-local deterministic saga compensation helper.
13285///
13286/// Register each compensation only after its forward step succeeds. Passing
13287/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
13288/// reverse registration order after any failure, including cooperative
13289/// cancellation. Each compensation is an ordinary durable activity, so replay,
13290/// duplicate delivery, and worker restart use existing history semantics.
13291pub struct Saga {
13292    ctx: WorkflowContext,
13293    compensations: Vec<SagaCompensation>,
13294}
13295
13296impl Saga {
13297    fn new(ctx: WorkflowContext) -> Self {
13298        Self {
13299            ctx,
13300            compensations: Vec::new(),
13301        }
13302    }
13303
13304    pub fn add_compensation<T: Serialize>(
13305        &mut self,
13306        activity_type: impl Into<String>,
13307        args: T,
13308    ) -> Result<&mut Self> {
13309        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
13310    }
13311
13312    pub fn add_compensation_with_options<T: Serialize>(
13313        &mut self,
13314        activity_type: impl Into<String>,
13315        options: ActivityOptions,
13316        args: T,
13317    ) -> Result<&mut Self> {
13318        let activity_type = activity_type.into();
13319        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
13320            return Err(Error::Codec(
13321                "saga compensation activity type must be non-empty without surrounding whitespace"
13322                    .to_string(),
13323            ));
13324        }
13325        options.validate().map_err(Error::InvalidActivityOptions)?;
13326        let arguments = AvroValue::from_serialize(&args)?;
13327        let registration_order = self.compensations.len() + 1;
13328        self.compensations.push(SagaCompensation {
13329            activity_type,
13330            options,
13331            arguments,
13332            registration_order,
13333        });
13334        Ok(self)
13335    }
13336
13337    /// Compensate `initiating_failure` and return the failure that must remain.
13338    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
13339        let _shield = match self.ctx.cancellation_shield() {
13340            Ok(shield) => shield,
13341            Err(error) => return error,
13342        };
13343        while let Some(compensation) = self.compensations.pop() {
13344            if let Err(compensation_failure) = self
13345                .ctx
13346                .activity_with_options(
13347                    compensation.activity_type.clone(),
13348                    compensation.options,
13349                    compensation.arguments,
13350                )
13351                .await
13352            {
13353                if workflow_task_integrity_error(&compensation_failure) {
13354                    return compensation_failure;
13355                }
13356                return Error::SagaCompensationFailed(SagaCompensationFailure {
13357                    initiating_failure: Box::new(initiating_failure),
13358                    compensation_failure: Box::new(compensation_failure),
13359                    compensation_activity_type: compensation.activity_type,
13360                    compensation_registration_order: compensation.registration_order,
13361                });
13362            }
13363        }
13364        initiating_failure
13365    }
13366
13367    /// Return a successful forward value or compensate and preserve its failure.
13368    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
13369        match outcome {
13370            Ok(value) => Ok(value),
13371            Err(error) => Err(self.compensate(error).await),
13372        }
13373    }
13374}
13375
13376pub struct ActivityCall {
13377    ctx: WorkflowContext,
13378    activity_type: String,
13379    options: ActivityOptions,
13380    worker_session: Option<WorkerSessionOptions>,
13381    args: Option<Result<AvroValue>>,
13382    scheduled: bool,
13383    local: bool,
13384    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
13385    parallel_group_path: Vec<ParallelGroupMetadata>,
13386}
13387
13388impl ActivityCall {
13389    fn poll_avro_value(
13390        mut self: Pin<&mut Self>,
13391        _cx: &mut TaskContext<'_>,
13392    ) -> Poll<Result<AvroValue>> {
13393        let ctx = self.ctx.clone();
13394        let mut state = match ctx.state.lock() {
13395            Ok(state) => state,
13396            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13397        };
13398
13399        if let Some(result) = &self.local_result {
13400            return match result.lock() {
13401                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
13402                    Poll::Ready(result.map_err(Error::ActivityFailed))
13403                }),
13404                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13405            };
13406        }
13407        if self.scheduled {
13408            return Poll::Pending;
13409        }
13410
13411        let options = match self.options.validate() {
13412            Ok(options) => options,
13413            Err(error) => {
13414                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
13415            }
13416        };
13417        if self.local {
13418            if self.worker_session.is_some() {
13419                return Poll::Ready(Err(Error::WorkerLoop(
13420                    "local activities cannot use worker-session routing".into(),
13421                )));
13422            }
13423            if let Err(error) = local_activity::validate(&options) {
13424                return Poll::Ready(Err(error));
13425            }
13426        }
13427        let session = match self
13428            .worker_session
13429            .as_ref()
13430            .map(WorkerSessionOptions::to_wire)
13431            .transpose()
13432        {
13433            Ok(value) => value,
13434            Err(error) => return Poll::Ready(Err(error)),
13435        };
13436        let session_queue = session
13437            .as_ref()
13438            .and_then(|session| session["queue"].as_str());
13439        let task_queue = options
13440            .task_queue
13441            .clone()
13442            .or_else(|| session_queue.map(str::to_owned))
13443            .unwrap_or_else(|| state.task_queue.clone());
13444        if session_queue.is_some_and(|queue| queue != task_queue) {
13445            return Poll::Ready(Err(Error::WorkerLoop(
13446                "worker-session queue must match the activity task queue".into(),
13447            )));
13448        }
13449        let current_recorded_options = RecordedActivityOptions {
13450            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
13451            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
13452            retry_policy: current_activity_retry_snapshot(&options),
13453            worker_session: session,
13454        };
13455
13456        let cursor = state.command_cursor;
13457        let call_kind = if self.local {
13458            CancellationCallKind::LocalActivity
13459        } else {
13460            CancellationCallKind::Activity
13461        };
13462        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13463            return Poll::Ready(Err(error));
13464        }
13465        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
13466            Ok(recorded) => recorded,
13467            Err(error) => return Poll::Ready(Err(error)),
13468        };
13469        if let Some(recorded) = recorded {
13470            let sequence = recorded.sequence();
13471            match recorded {
13472                RecordedCommand::Activity {
13473                    activity_type,
13474                    cancellation_policy,
13475                    options: recorded_options,
13476                    outcome,
13477                    parallel_group_path,
13478                    ..
13479                } => {
13480                    let current_policy = options
13481                        .cancellation_policy
13482                        .unwrap_or(CancellationPolicy::TryCancel)
13483                        .as_str();
13484                    if cancellation_policy != current_policy {
13485                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13486                            ReplayFailure::new(
13487                                "activity_cancellation_policy_changed",
13488                                Some(sequence),
13489                                Some(cancellation_policy),
13490                                Some(current_policy.to_string()),
13491                                "Activity cancellation policy changed during replay",
13492                            ),
13493                        )));
13494                    }
13495                    if let Err(error) = ensure_parallel_path_matches(
13496                        sequence,
13497                        parallel_group_path.as_deref(),
13498                        &self.parallel_group_path,
13499                    ) {
13500                        return Poll::Ready(Err(error));
13501                    }
13502                    if let Some(recorded_type) = activity_type {
13503                        if recorded_type != self.activity_type {
13504                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13505                                ReplayFailure::new(
13506                                    "recorded_command_detail_mismatch",
13507                                    Some(sequence),
13508                                    Some(format!("activity:{recorded_type}")),
13509                                    Some(format!("activity:{}", self.activity_type)),
13510                                    "recorded activity type differs from the current workflow command",
13511                                ),
13512                            )));
13513                        }
13514                    }
13515                    if let Some(recorded_options) = recorded_options {
13516                        if recorded_options.worker_session
13517                            != current_recorded_options.worker_session
13518                        {
13519                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
13520                                "activity_worker_session_mismatch", Some(sequence),
13521                                Some(activity_options_description(&recorded_options)),
13522                                Some(activity_options_description(&current_recorded_options)),
13523                                "recorded worker-session routing differs from the current activity",
13524                            ))));
13525                        }
13526                        if !recorded_options
13527                            .task_queue
13528                            .matches_current(&current_recorded_options.task_queue)
13529                        {
13530                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13531                                ReplayFailure::new(
13532                                    "activity_task_queue_mismatch",
13533                                    Some(sequence),
13534                                    Some(activity_options_description(&recorded_options)),
13535                                    Some(activity_options_description(&current_recorded_options)),
13536                                    "recorded activity task queue differs from the current workflow command",
13537                                ),
13538                            )));
13539                        }
13540                        if (self.local
13541                            && matches!(
13542                                recorded_options.execution_mode,
13543                                RecordedSnapshotValue::Unknown
13544                            ))
13545                            || !recorded_options
13546                                .execution_mode
13547                                .matches_current(&current_recorded_options.execution_mode)
13548                        {
13549                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13550                                ReplayFailure::new(
13551                                    "activity_execution_mode_mismatch",
13552                                    Some(sequence),
13553                                    Some(activity_options_description(&recorded_options)),
13554                                    Some(activity_options_description(&current_recorded_options)),
13555                                    "recorded activity execution mode differs from the current workflow command",
13556                                ),
13557                            )));
13558                        }
13559                        if !recorded_options
13560                            .retry_policy
13561                            .matches_current(&current_recorded_options.retry_policy)
13562                        {
13563                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13564                                ReplayFailure::new(
13565                                    "activity_retry_policy_mismatch",
13566                                    Some(sequence),
13567                                    Some(activity_options_description(&recorded_options)),
13568                                    Some(activity_options_description(&current_recorded_options)),
13569                                    "recorded activity retry policy differs from the current workflow command",
13570                                ),
13571                            )));
13572                        }
13573                    }
13574                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
13575                        return Poll::Ready(Err(error));
13576                    }
13577                    match state.prepare_scalar_cancellation(
13578                        cursor,
13579                        call_kind,
13580                        &self.parallel_group_path,
13581                    ) {
13582                        Ok(true) => {
13583                            self.scheduled = true;
13584                            return Poll::Pending;
13585                        }
13586                        Ok(false) => {}
13587                        Err(error) => return Poll::Ready(Err(error)),
13588                    }
13589                    state.command_cursor += 1;
13590                    if let Some(outcome) = outcome {
13591                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13592                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
13593                    }
13594                    state.matched_recorded_pending = true;
13595                    self.scheduled = true;
13596                    return Poll::Pending;
13597                }
13598                other => {
13599                    return Poll::Ready(Err(command_mismatch(
13600                        &other,
13601                        format!("activity:{}", self.activity_type),
13602                    )));
13603                }
13604            }
13605        }
13606
13607        if !self.scheduled {
13608            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
13609                Ok(args) => args,
13610                Err(error) => return Poll::Ready(Err(error)),
13611            };
13612            let arguments = normalize_avro_arguments(args);
13613            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
13614                Ok(envelope) => envelope,
13615                Err(error) => return Poll::Ready(Err(error)),
13616            };
13617
13618            let mut command = serde_json::Map::from_iter([
13619                (
13620                    "type".to_string(),
13621                    json!(if self.local {
13622                        "record_local_activity"
13623                    } else {
13624                        "schedule_activity"
13625                    }),
13626                ),
13627                (
13628                    "activity_type".to_string(),
13629                    json!(self.activity_type.clone()),
13630                ),
13631                ("queue".to_string(), json!(task_queue)),
13632                ("arguments".to_string(), envelope),
13633            ]);
13634            for (field, value) in [
13635                ("start_to_close_timeout", options.start_to_close_timeout),
13636                (
13637                    "schedule_to_start_timeout",
13638                    options.schedule_to_start_timeout,
13639                ),
13640                (
13641                    "schedule_to_close_timeout",
13642                    options.schedule_to_close_timeout,
13643                ),
13644                ("heartbeat_timeout", options.heartbeat_timeout),
13645            ] {
13646                if let Some(value) = value {
13647                    command.insert(field.to_string(), json!(value));
13648                }
13649            }
13650            if let Some(retry_policy) = &options.retry_policy {
13651                command.insert("retry_policy".to_string(), retry_policy.clone());
13652            }
13653            if let Some(policy) = options.cancellation_policy {
13654                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
13655            }
13656            if let Some(session) = current_recorded_options.worker_session {
13657                command.insert("worker_session".into(), session);
13658            }
13659            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13660            ctx.apply_scope_membership(&mut command);
13661            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
13662                Ok(true) => {
13663                    self.scheduled = true;
13664                    return Poll::Pending;
13665                }
13666                Ok(false) => {}
13667                Err(error) => return Poll::Ready(Err(error)),
13668            }
13669            if self.local {
13670                command.remove("queue");
13671                command.insert("execution_mode".into(), json!("local"));
13672                let result = Arc::new(Mutex::new(None));
13673                let command_index = state.commands.len();
13674                state.local_activity_requests.push(local_activity::Request {
13675                    command_index,
13676                    options,
13677                    arguments,
13678                    result: result.clone(),
13679                });
13680                self.local_result = Some(result);
13681            }
13682            state.commands.push(Value::Object(command));
13683            self.scheduled = true;
13684        }
13685
13686        Poll::Pending
13687    }
13688}
13689
13690impl Future for ActivityCall {
13691    type Output = Result<Value>;
13692
13693    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13694        match self.poll_avro_value(cx) {
13695            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
13696            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13697            Poll::Pending => Poll::Pending,
13698        }
13699    }
13700}
13701
13702/// Future returned by [`WorkflowContext::sleep`].
13703pub struct TimerCall {
13704    ctx: WorkflowContext,
13705    delay_seconds: Option<u64>,
13706    scheduled: bool,
13707    matched_pending: bool,
13708    parallel_group_path: Vec<ParallelGroupMetadata>,
13709}
13710
13711impl Future for TimerCall {
13712    type Output = Result<()>;
13713
13714    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13715        if self.matched_pending {
13716            return Poll::Pending;
13717        }
13718
13719        let ctx = self.ctx.clone();
13720        let Some(requested_delay) = self.delay_seconds else {
13721            return Poll::Ready(Err(Error::TimerDurationOverflow));
13722        };
13723        let mut state = match ctx.state.lock() {
13724            Ok(state) => state,
13725            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13726        };
13727
13728        let cursor = state.command_cursor;
13729        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13730            return Poll::Ready(Err(error));
13731        }
13732        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
13733        {
13734            Ok(recorded) => recorded,
13735            Err(error) => return Poll::Ready(Err(error)),
13736        };
13737        if let Some(recorded) = recorded {
13738            match recorded {
13739                RecordedCommand::Timer {
13740                    sequence,
13741                    delay_seconds,
13742                    fired,
13743                    parallel_group_path,
13744                    ..
13745                } => {
13746                    if let Err(error) =
13747                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
13748                    {
13749                        return Poll::Ready(Err(error));
13750                    }
13751                    if let Err(error) = ensure_parallel_path_matches(
13752                        sequence,
13753                        parallel_group_path.as_deref(),
13754                        &self.parallel_group_path,
13755                    ) {
13756                        return Poll::Ready(Err(error));
13757                    }
13758                    if delay_seconds != requested_delay {
13759                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13760                            ReplayFailure::new(
13761                                "timer_delay_mismatch",
13762                                Some(sequence),
13763                                Some(format!("timer:{delay_seconds}s")),
13764                                Some(format!("timer:{requested_delay}s")),
13765                                "recorded timer delay differs from the current workflow command",
13766                            ),
13767                        )));
13768                    }
13769                    if let Err(error) =
13770                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
13771                    {
13772                        return Poll::Ready(Err(error));
13773                    }
13774                    match state.prepare_scalar_cancellation(
13775                        cursor,
13776                        CancellationCallKind::Timer,
13777                        &self.parallel_group_path,
13778                    ) {
13779                        Ok(true) => {
13780                            self.scheduled = true;
13781                            self.matched_pending = true;
13782                            return Poll::Pending;
13783                        }
13784                        Ok(false) => {}
13785                        Err(error) => return Poll::Ready(Err(error)),
13786                    }
13787                    state.command_cursor += 1;
13788                    if fired {
13789                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13790                        return Poll::Ready(Ok(()));
13791                    }
13792                    state.matched_recorded_pending = true;
13793                    self.scheduled = true;
13794                    self.matched_pending = true;
13795                    return Poll::Pending;
13796                }
13797                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
13798            }
13799        }
13800
13801        if !self.scheduled {
13802            let mut command = serde_json::Map::from_iter([
13803                ("type".to_string(), json!("start_timer")),
13804                ("delay_seconds".to_string(), json!(requested_delay)),
13805            ]);
13806            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
13807                Ok(Some(proof)) => {
13808                    command.insert("cancellation_cleanup".into(), proof);
13809                }
13810                Ok(None) => {}
13811                Err(error) => return Poll::Ready(Err(error)),
13812            }
13813            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13814            ctx.apply_scope_membership(&mut command);
13815            match state.prepare_scalar_cancellation(
13816                cursor,
13817                CancellationCallKind::Timer,
13818                &self.parallel_group_path,
13819            ) {
13820                Ok(true) => {
13821                    self.scheduled = true;
13822                    self.matched_pending = true;
13823                    return Poll::Pending;
13824                }
13825                Ok(false) => {}
13826                Err(error) => return Poll::Ready(Err(error)),
13827            }
13828            state.commands.push(Value::Object(command));
13829            self.scheduled = true;
13830        }
13831
13832        Poll::Pending
13833    }
13834}
13835
13836/// Future returned by [`WorkflowContext::wait_condition`].
13837pub struct ConditionWaitCall {
13838    ctx: WorkflowContext,
13839    options: ConditionWaitOptions,
13840    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
13841    occurrence_id: Option<String>,
13842    opened_wait: bool,
13843    parallel_group_path: Vec<ParallelGroupMetadata>,
13844}
13845
13846impl Future for ConditionWaitCall {
13847    type Output = Result<ConditionWaitResult>;
13848
13849    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13850        if self.opened_wait {
13851            return Poll::Pending;
13852        }
13853
13854        let options = match self.options.validate() {
13855            Ok(options) => options,
13856            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
13857        };
13858        let ctx = self.ctx.clone();
13859        let occurrence_id = match self.occurrence_id.as_ref() {
13860            Some(occurrence_id) => occurrence_id.clone(),
13861            None => {
13862                let mut state = match ctx.state.lock() {
13863                    Ok(state) => state,
13864                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13865                };
13866                let ordinal = state.condition_wait_occurrence_counter;
13867                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
13868                    Some(next) => next,
13869                    None => {
13870                        return Poll::Ready(Err(Error::WorkerLoop(
13871                            "condition wait occurrence counter overflowed".to_string(),
13872                        )))
13873                    }
13874                };
13875                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
13876                drop(state);
13877                self.occurrence_id = Some(occurrence_id.clone());
13878                occurrence_id
13879            }
13880        };
13881
13882        let recorded_result = {
13883            let mut state = match ctx.state.lock() {
13884                Ok(state) => state,
13885                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13886            };
13887            let initial_cursor = state.command_cursor;
13888            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
13889                return Poll::Ready(Err(error));
13890            }
13891            let recorded = match state
13892                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
13893            {
13894                Ok(recorded) => recorded,
13895                Err(error) => return Poll::Ready(Err(error)),
13896            };
13897            let Some(recorded) = recorded else {
13898                drop(state);
13899                return self.poll_new_condition(options);
13900            };
13901            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
13902                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
13903            }
13904
13905            let mut cursor = state.command_cursor;
13906            let mut result = None;
13907            let mut pending_delivery = false;
13908            loop {
13909                if cursor > initial_cursor
13910                    && matches!(
13911                        state.recorded_commands.get(cursor),
13912                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
13913                    )
13914                {
13915                    break;
13916                }
13917                let recorded = match state
13918                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
13919                {
13920                    Ok(recorded) => recorded,
13921                    Err(error) => return Poll::Ready(Err(error)),
13922                };
13923                let Some(RecordedCommand::ConditionWait {
13924                    sequence,
13925                    occurrence_id: ref recorded_occurrence_id,
13926                    ref condition_key,
13927                    ref predicate_identity,
13928                    timeout_seconds,
13929                    result: recorded_result,
13930                    ref parallel_group_path,
13931                    ..
13932                }) = recorded
13933                else {
13934                    break;
13935                };
13936
13937                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
13938                    break;
13939                }
13940                if let Err(error) = ensure_parallel_path_matches(
13941                    sequence,
13942                    parallel_group_path.as_deref(),
13943                    &self.parallel_group_path,
13944                ) {
13945                    return Poll::Ready(Err(error));
13946                }
13947                if let Err(error) = validate_recorded_condition_wait(
13948                    sequence,
13949                    recorded_occurrence_id,
13950                    condition_key.as_deref(),
13951                    predicate_identity,
13952                    timeout_seconds,
13953                    &occurrence_id,
13954                    &options,
13955                ) {
13956                    return Poll::Ready(Err(error));
13957                }
13958                if result == Some(ConditionWaitResult::TimedOut) {
13959                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
13960                        "condition_wait_reopened_after_timeout",
13961                        Some(sequence),
13962                        Some("timed-out condition is terminal".to_string()),
13963                        Some("another physical wait-open".to_string()),
13964                        "condition history reopened one logical wait after its durable timeout",
13965                    ))));
13966                }
13967                if let Err(error) =
13968                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
13969                {
13970                    return Poll::Ready(Err(error));
13971                }
13972                match state.prepare_scalar_cancellation(
13973                    cursor,
13974                    CancellationCallKind::Condition,
13975                    &self.parallel_group_path,
13976                ) {
13977                    Ok(pending) => pending_delivery |= pending,
13978                    Err(error) => return Poll::Ready(Err(error)),
13979                }
13980                result = recorded_result;
13981                if result.is_some() {
13982                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13983                }
13984                cursor += 1;
13985            }
13986            state.command_cursor = cursor;
13987            if pending_delivery {
13988                self.opened_wait = true;
13989                return Poll::Pending;
13990            }
13991            result
13992        };
13993
13994        if let Some(result) = recorded_result {
13995            return Poll::Ready(Ok(result));
13996        }
13997
13998        self.poll_open_condition(options, true)
13999    }
14000}
14001
14002impl ConditionWaitCall {
14003    fn poll_new_condition(
14004        self: Pin<&mut Self>,
14005        options: ValidatedConditionWaitOptions,
14006    ) -> Poll<Result<ConditionWaitResult>> {
14007        self.poll_open_condition(options, false)
14008    }
14009
14010    fn poll_open_condition(
14011        mut self: Pin<&mut Self>,
14012        options: ValidatedConditionWaitOptions,
14013        recorded_wait: bool,
14014    ) -> Poll<Result<ConditionWaitResult>> {
14015        {
14016            let ctx = self.ctx.clone();
14017            let mut state = match ctx.state.lock() {
14018                Ok(state) => state,
14019                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14020            };
14021            let cursor = state.command_cursor;
14022            match state.prepare_scalar_cancellation(
14023                cursor,
14024                CancellationCallKind::Condition,
14025                &self.parallel_group_path,
14026            ) {
14027                Ok(true) => {
14028                    self.opened_wait = true;
14029                    return Poll::Pending;
14030                }
14031                Ok(false) => {}
14032                Err(error) => return Poll::Ready(Err(error)),
14033            }
14034        }
14035        let selection_member = self
14036            .parallel_group_path
14037            .first()
14038            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14039        match (self.predicate)() {
14040            Ok(true) if !selection_member || recorded_wait => {
14041                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14042            }
14043            Ok(_) => {}
14044            Err(error) => return Poll::Ready(Err(error)),
14045        }
14046        if options.timeout_seconds == Some(0) && !selection_member {
14047            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14048        }
14049
14050        let ctx = self.ctx.clone();
14051        let mut state = match ctx.state.lock() {
14052            Ok(state) => state,
14053            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14054        };
14055        let mut command = serde_json::Map::from_iter([
14056            ("type".to_string(), json!("open_condition_wait")),
14057            (
14058                "condition_wait_occurrence_id".to_string(),
14059                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14060            ),
14061            ("condition_key".to_string(), json!(options.condition_key)),
14062            (
14063                "condition_definition_fingerprint".to_string(),
14064                json!(options.predicate_identity),
14065            ),
14066        ]);
14067        if let Some(timeout_seconds) = options.timeout_seconds {
14068            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14069        }
14070        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14071        ctx.apply_scope_membership(&mut command);
14072        state.commands.push(Value::Object(command));
14073        drop(state);
14074        self.opened_wait = true;
14075        Poll::Pending
14076    }
14077}
14078
14079fn validate_recorded_condition_wait(
14080    sequence: u64,
14081    recorded_occurrence_id: &str,
14082    recorded_key: Option<&str>,
14083    recorded_predicate_identity: &str,
14084    recorded_timeout_seconds: Option<u64>,
14085    current_occurrence_id: &str,
14086    current: &ValidatedConditionWaitOptions,
14087) -> Result<()> {
14088    if recorded_occurrence_id != current_occurrence_id {
14089        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14090            "condition_wait_occurrence_mismatch",
14091            Some(sequence),
14092            Some(recorded_occurrence_id.to_string()),
14093            Some(current_occurrence_id.to_string()),
14094            "recorded condition occurrence differs from the current authored wait position",
14095        )));
14096    }
14097    if recorded_key != Some(current.condition_key.as_str()) {
14098        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14099            "condition_wait_key_mismatch",
14100            Some(sequence),
14101            recorded_key.map(str::to_string),
14102            Some(current.condition_key.clone()),
14103            "recorded condition identity differs from the current workflow wait",
14104        )));
14105    }
14106    if recorded_predicate_identity != current.predicate_identity {
14107        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14108            "condition_wait_predicate_mismatch",
14109            Some(sequence),
14110            Some(recorded_predicate_identity.to_string()),
14111            Some(current.predicate_identity.clone()),
14112            "recorded condition predicate behavior differs from current workflow code",
14113        )));
14114    }
14115    if recorded_timeout_seconds != current.timeout_seconds {
14116        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14117            "condition_wait_timeout_mismatch",
14118            Some(sequence),
14119            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14120            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14121            "recorded condition timeout differs from the current workflow wait",
14122        )));
14123    }
14124    Ok(())
14125}
14126
14127/// Future returned by [`WorkflowContext::start_child_workflow`].
14128pub struct ChildWorkflowCall {
14129    ctx: WorkflowContext,
14130    workflow_type: String,
14131    options: ChildWorkflowOptions,
14132    args: Option<Result<AvroValue>>,
14133    scheduled: bool,
14134    matched_pending: bool,
14135    parallel_group_path: Vec<ParallelGroupMetadata>,
14136}
14137
14138impl ChildWorkflowCall {
14139    fn poll_avro_value(
14140        mut self: Pin<&mut Self>,
14141        _cx: &mut TaskContext<'_>,
14142    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14143        if self.matched_pending {
14144            return Poll::Pending;
14145        }
14146
14147        let ctx = self.ctx.clone();
14148        let mut state = match ctx.state.lock() {
14149            Ok(state) => state,
14150            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14151        };
14152
14153        let cursor = state.command_cursor;
14154        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14155            return Poll::Ready(Err(error));
14156        }
14157        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14158        {
14159            Ok(recorded) => recorded,
14160            Err(error) => return Poll::Ready(Err(error)),
14161        };
14162        if let Some(recorded) = recorded {
14163            let sequence = recorded.sequence();
14164            match recorded {
14165                RecordedCommand::ChildWorkflow {
14166                    workflow_type,
14167                    policies,
14168                    outcome,
14169                    parallel_group_path,
14170                    ..
14171                } => {
14172                    if let Err(error) = ensure_parallel_path_matches(
14173                        sequence,
14174                        parallel_group_path.as_deref(),
14175                        &self.parallel_group_path,
14176                    ) {
14177                        return Poll::Ready(Err(error));
14178                    }
14179                    if let Some(recorded_type) = workflow_type {
14180                        if recorded_type != self.workflow_type {
14181                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14182                                ReplayFailure::new(
14183                                    "recorded_command_detail_mismatch",
14184                                    Some(sequence),
14185                                    Some(format!("child workflow:{recorded_type}")),
14186                                    Some(format!("child workflow:{}", self.workflow_type)),
14187                                    "recorded child workflow type differs from the current workflow command",
14188                                ),
14189                            )));
14190                        }
14191                    }
14192                    if let Err(error) =
14193                        ensure_child_policies_match(sequence, &policies, &self.options)
14194                    {
14195                        return Poll::Ready(Err(error));
14196                    }
14197                    if let Err(error) =
14198                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14199                    {
14200                        return Poll::Ready(Err(error));
14201                    }
14202                    match state.prepare_scalar_cancellation(
14203                        cursor,
14204                        CancellationCallKind::Child,
14205                        &self.parallel_group_path,
14206                    ) {
14207                        Ok(true) => {
14208                            self.scheduled = true;
14209                            self.matched_pending = true;
14210                            return Poll::Pending;
14211                        }
14212                        Ok(false) => {}
14213                        Err(error) => return Poll::Ready(Err(error)),
14214                    }
14215                    state.command_cursor += 1;
14216                    if let Some(outcome) = outcome {
14217                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14218                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
14219                    }
14220                    state.matched_recorded_pending = true;
14221                    self.scheduled = true;
14222                    self.matched_pending = true;
14223                    return Poll::Pending;
14224                }
14225                other => {
14226                    return Poll::Ready(Err(command_mismatch(
14227                        &other,
14228                        format!("child workflow:{}", self.workflow_type),
14229                    )));
14230                }
14231            }
14232        }
14233
14234        if !self.scheduled {
14235            if self.options.task_queue.trim().is_empty() {
14236                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14237                    "task_queue must not be empty".to_string(),
14238                )));
14239            }
14240            for (name, value) in [
14241                (
14242                    "execution_timeout_seconds",
14243                    self.options.execution_timeout_seconds,
14244                ),
14245                ("run_timeout_seconds", self.options.run_timeout_seconds),
14246            ] {
14247                if value == Some(0) {
14248                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
14249                        "{name} must be at least 1"
14250                    ))));
14251                }
14252            }
14253
14254            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14255                Ok(args) => args,
14256                Err(error) => return Poll::Ready(Err(error)),
14257            };
14258            let arguments = match encode_typed_envelope(
14259                &normalize_avro_arguments(args),
14260                &state.payload_codec,
14261            ) {
14262                Ok(arguments) => arguments,
14263                Err(error) => return Poll::Ready(Err(error)),
14264            };
14265            let mut command = json!({
14266                "type": "start_child_workflow",
14267                "workflow_type": self.workflow_type,
14268                "queue": self.options.task_queue,
14269                "parent_close_policy": self.options.parent_close_policy.as_str(),
14270                "arguments": arguments,
14271            });
14272            let object = command
14273                .as_object_mut()
14274                .expect("child workflow command is always an object");
14275            if self.options.cancellation_policy != CancellationPolicy::Abandon {
14276                object.insert(
14277                    "cancellation_policy".to_string(),
14278                    json!(self.options.cancellation_policy.as_str()),
14279                );
14280            }
14281            if let Some(policy) = &self.options.retry_policy {
14282                let mut retry_policy = serde_json::Map::new();
14283                if let Some(max_attempts) = policy.max_attempts {
14284                    if max_attempts == 0 {
14285                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14286                            "retry_policy.max_attempts must be at least 1".to_string(),
14287                        )));
14288                    }
14289                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
14290                }
14291                if !policy.backoff_seconds.is_empty() {
14292                    retry_policy
14293                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
14294                }
14295                if !policy.non_retryable_error_types.is_empty() {
14296                    retry_policy.insert(
14297                        "non_retryable_error_types".to_string(),
14298                        json!(policy.non_retryable_error_types),
14299                    );
14300                }
14301                if retry_policy.is_empty() {
14302                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14303                        "retry_policy must configure at least one field".to_string(),
14304                    )));
14305                }
14306                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
14307            }
14308            if let Some(seconds) = self.options.execution_timeout_seconds {
14309                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
14310            }
14311            if let Some(seconds) = self.options.run_timeout_seconds {
14312                object.insert("run_timeout_seconds".to_string(), json!(seconds));
14313            }
14314            apply_parallel_group_path(object, &self.parallel_group_path);
14315            ctx.apply_scope_membership(object);
14316            match state.prepare_scalar_cancellation(
14317                cursor,
14318                CancellationCallKind::Child,
14319                &self.parallel_group_path,
14320            ) {
14321                Ok(true) => {
14322                    self.scheduled = true;
14323                    self.matched_pending = true;
14324                    return Poll::Pending;
14325                }
14326                Ok(false) => {}
14327                Err(error) => return Poll::Ready(Err(error)),
14328            }
14329            state.commands.push(command);
14330            self.scheduled = true;
14331        }
14332
14333        Poll::Pending
14334    }
14335}
14336
14337impl Future for ChildWorkflowCall {
14338    type Output = Result<ChildWorkflowResult>;
14339
14340    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14341        match self.poll_avro_value(cx) {
14342            Poll::Ready(Ok(result)) => match result.result.into_json() {
14343                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
14344                    parent: result.parent,
14345                    child: result.child,
14346                    child_workflow_type: result.child_workflow_type,
14347                    result: projected,
14348                })),
14349                Err(error) => Poll::Ready(Err(error)),
14350            },
14351            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14352            Poll::Pending => Poll::Pending,
14353        }
14354    }
14355}
14356
14357fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
14358    Error::NonDeterministicReplay(ReplayFailure::new(
14359        "recorded_command_mismatch",
14360        Some(recorded.sequence()),
14361        Some(recorded.shape().to_string()),
14362        Some(actual.into()),
14363        "current workflow command does not match the recorded durable command sequence",
14364    ))
14365}
14366
14367pub struct SignalCall {
14368    ctx: WorkflowContext,
14369    signal_name: String,
14370    runtime_reserved_allowed: bool,
14371    opened_wait: bool,
14372    matched_pending: bool,
14373    parallel_group_path: Vec<ParallelGroupMetadata>,
14374}
14375
14376impl SignalCall {
14377    fn poll_avro_value(
14378        mut self: Pin<&mut Self>,
14379        _cx: &mut TaskContext<'_>,
14380    ) -> Poll<Result<Vec<AvroValue>>> {
14381        if self.matched_pending {
14382            return Poll::Pending;
14383        }
14384        if !self.runtime_reserved_allowed {
14385            if let Err(error) = validate_user_signal_name(&self.signal_name) {
14386                return Poll::Ready(Err(error));
14387            }
14388        }
14389
14390        let ctx = self.ctx.clone();
14391        let mut state = match ctx.state.lock() {
14392            Ok(state) => state,
14393            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14394        };
14395
14396        let cursor = state.command_cursor;
14397        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14398            return Poll::Ready(Err(error));
14399        }
14400        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
14401        {
14402            Ok(recorded) => recorded,
14403            Err(error) => return Poll::Ready(Err(error)),
14404        };
14405        if let Some(recorded) = recorded {
14406            match recorded {
14407                RecordedCommand::SignalWait {
14408                    sequence,
14409                    signal_name,
14410                    value,
14411                    parallel_group_path,
14412                } => {
14413                    if let Err(error) = ensure_parallel_path_matches(
14414                        sequence,
14415                        parallel_group_path.as_deref(),
14416                        &self.parallel_group_path,
14417                    ) {
14418                        return Poll::Ready(Err(error));
14419                    }
14420                    if signal_name != self.signal_name {
14421                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14422                            ReplayFailure::new(
14423                                "recorded_command_detail_mismatch",
14424                                Some(sequence),
14425                                Some(format!("signal wait:{signal_name}")),
14426                                Some(format!("signal wait:{}", self.signal_name)),
14427                                "recorded signal name differs from the current workflow command",
14428                            ),
14429                        )));
14430                    }
14431
14432                    if let Err(error) =
14433                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
14434                    {
14435                        return Poll::Ready(Err(error));
14436                    }
14437                    match state.prepare_scalar_cancellation(
14438                        cursor,
14439                        CancellationCallKind::Signal,
14440                        &self.parallel_group_path,
14441                    ) {
14442                        Ok(true) => {
14443                            self.opened_wait = true;
14444                            self.matched_pending = true;
14445                            return Poll::Pending;
14446                        }
14447                        Ok(false) => {}
14448                        Err(error) => return Poll::Ready(Err(error)),
14449                    }
14450                    state.command_cursor += 1;
14451                    if let Some(value) = value {
14452                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14453                        return Poll::Ready(Ok(value));
14454                    }
14455                    if state
14456                        .resume_signal
14457                        .as_ref()
14458                        .is_some_and(|signal| signal.signal_name == self.signal_name)
14459                    {
14460                        let signal = state
14461                            .resume_signal
14462                            .take()
14463                            .expect("matching resume signal is present");
14464                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
14465                        return Poll::Ready(Ok(signal.arguments));
14466                    }
14467
14468                    state.matched_recorded_pending = true;
14469                    self.opened_wait = true;
14470                    self.matched_pending = true;
14471                    return Poll::Pending;
14472                }
14473                other => {
14474                    return Poll::Ready(Err(command_mismatch(
14475                        &other,
14476                        format!("signal wait:{}", self.signal_name),
14477                    )));
14478                }
14479            }
14480        }
14481
14482        match state.prepare_scalar_cancellation(
14483            cursor,
14484            CancellationCallKind::Signal,
14485            &self.parallel_group_path,
14486        ) {
14487            Ok(true) => {
14488                self.opened_wait = true;
14489                self.matched_pending = true;
14490                return Poll::Pending;
14491            }
14492            Ok(false) => {}
14493            Err(error) => return Poll::Ready(Err(error)),
14494        }
14495
14496        if state
14497            .resume_signal
14498            .as_ref()
14499            .is_some_and(|signal| signal.signal_name == self.signal_name)
14500        {
14501            let signal = state
14502                .resume_signal
14503                .take()
14504                .expect("matching resume signal is present");
14505            state.unavailable_cancellation_boundary(&self.parallel_group_path);
14506            return Poll::Ready(Ok(signal.arguments));
14507        }
14508
14509        if !self.opened_wait {
14510            let mut command = serde_json::Map::from_iter([
14511                ("type".to_string(), json!("open_signal_wait")),
14512                ("signal_name".to_string(), json!(self.signal_name)),
14513            ]);
14514            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14515            ctx.apply_scope_membership(&mut command);
14516            state.commands.push(Value::Object(command));
14517            self.opened_wait = true;
14518        }
14519
14520        Poll::Pending
14521    }
14522}
14523
14524impl Future for SignalCall {
14525    type Output = Result<Vec<Value>>;
14526
14527    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14528        match self.poll_avro_value(cx) {
14529            Poll::Ready(Ok(values)) => Poll::Ready(
14530                values
14531                    .into_iter()
14532                    .map(AvroValue::into_json)
14533                    .collect::<Result<Vec<_>>>(),
14534            ),
14535            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14536            Poll::Pending => Poll::Pending,
14537        }
14538    }
14539}
14540
14541#[derive(Clone, Debug)]
14542pub struct ActivityContext {
14543    client: Client,
14544    pub task_id: String,
14545    pub activity_attempt_id: String,
14546    pub lease_owner: String,
14547    pub activity_type: String,
14548    pub attempt_number: u64,
14549    pub task_queue: String,
14550    pub worker_id: String,
14551    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
14552    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
14553    worker_session: Option<WorkerSession>,
14554}
14555
14556impl ActivityContext {
14557    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
14558        if let Some(heartbeats) = &self.local_heartbeats {
14559            return heartbeats
14560                .lock()
14561                .map_err(|_| Error::WorkflowStatePoisoned)?
14562                .record(details);
14563        }
14564        if let Some(guard) = &self.claim_guard {
14565            return guard.heartbeat(self, details).await;
14566        }
14567        if let Some(session) = &self.worker_session {
14568            if !session.active() {
14569                return Err(Error::ActivityExecutionAbandoned(
14570                    "worker-session lease or TTL is no longer active".into(),
14571                ));
14572            }
14573            let result = self
14574                .client
14575                .heartbeat_activity_task_value(
14576                    &self.task_id,
14577                    &self.activity_attempt_id,
14578                    &self.lease_owner,
14579                    details,
14580                )
14581                .await;
14582            return worker_session::settle_activity_heartbeat(
14583                session,
14584                result,
14585                &self.task_id,
14586                &self.activity_attempt_id,
14587                &self.lease_owner,
14588            );
14589        }
14590        self.client
14591            .heartbeat_activity_task(
14592                &self.task_id,
14593                &self.activity_attempt_id,
14594                &self.lease_owner,
14595                details,
14596            )
14597            .await
14598    }
14599}
14600
14601fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
14602    validate_payload_codec(codec)?;
14603    match value {
14604        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
14605            value, codec,
14606        )?)),
14607        None => Ok(AvroValue::Array(Vec::new())),
14608    }
14609}
14610
14611fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
14612    let Some(signal_name) = task
14613        .signal_name
14614        .as_deref()
14615        .filter(|value| !value.is_empty())
14616    else {
14617        return Ok(None);
14618    };
14619    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
14620    let AvroValue::Array(arguments) = decoded else {
14621        unreachable!("normalize_avro_arguments always returns an array");
14622    };
14623
14624    Ok(Some(ResumeSignal {
14625        signal_name: signal_name.to_string(),
14626        arguments,
14627    }))
14628}
14629
14630fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
14631    validate_payload_codec(&task.payload_codec)?;
14632    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
14633    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
14634    for event in &task.history_events {
14635        validate_history_event_payloads(event, &task.payload_codec)?;
14636    }
14637    Ok(())
14638}
14639
14640fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
14641    validate_payload_codec(&task.payload_codec)?;
14642    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
14643}
14644
14645fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
14646    validate_payload_codec(&task.payload_codec)?;
14647    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
14648    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
14649    for event in &task.history_events {
14650        validate_history_event_payloads(event, &task.payload_codec)?;
14651    }
14652
14653    let Some(export) = task.history_export.as_ref() else {
14654        return Ok(());
14655    };
14656    let export_codec = match export.get("payloads") {
14657        Some(payloads) => declared_payload_codec(payloads, "codec")?,
14658        None => None,
14659    }
14660    .unwrap_or(&task.payload_codec);
14661    validate_payload_codec(export_codec)?;
14662
14663    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
14664        for event in events {
14665            let event_type = event
14666                .get("event_type")
14667                .or_else(|| event.get("type"))
14668                .and_then(Value::as_str)
14669                .unwrap_or_default();
14670            if let Some(payload) = event.get("payload") {
14671                validate_history_payloads(event_type, payload, export_codec)?;
14672            }
14673        }
14674    }
14675    for signal in export
14676        .get("signals")
14677        .and_then(Value::as_array)
14678        .into_iter()
14679        .flatten()
14680    {
14681        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
14682        validate_payload_codec(codec)?;
14683        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
14684    }
14685    for activity in export
14686        .get("activities")
14687        .and_then(Value::as_array)
14688        .into_iter()
14689        .flatten()
14690    {
14691        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
14692        validate_payload_codec(codec)?;
14693        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
14694        validate_optional_inbound_payload(activity.get("result"), codec)?;
14695    }
14696    Ok(())
14697}
14698
14699fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
14700    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
14701}
14702
14703fn validate_history_payloads(
14704    event_type: &str,
14705    payload: &Value,
14706    fallback_codec: &str,
14707) -> Result<()> {
14708    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
14709    validate_payload_codec(codec)?;
14710    for field in history_payload_fields(event_type) {
14711        validate_optional_inbound_payload(payload.get(*field), codec)?;
14712    }
14713    Ok(())
14714}
14715
14716const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
14717
14718fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
14719    match event_type {
14720        "ActivityCompleted" => &["result"],
14721        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
14722        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
14723        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
14724        "ChildRunCompleted" => &["result", "output"],
14725        "WorkflowCompleted" => &["output"],
14726        "ServiceCallStarted"
14727        | "ServiceCallCompleted"
14728        | "ServiceCallFailed"
14729        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
14730        _ => &[],
14731    }
14732}
14733
14734fn signal_history_payload(payload: &Value) -> Option<&Value> {
14735    SIGNAL_HISTORY_PAYLOAD_FIELDS
14736        .iter()
14737        .find_map(|field| payload.get(*field))
14738}
14739
14740fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
14741    match value.get(field) {
14742        None => Ok(None),
14743        Some(Value::String(codec)) => Ok(Some(codec)),
14744        Some(_) => Err(invalid_payload_envelope()),
14745    }
14746}
14747
14748fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
14749    validate_payload_codec(codec)?;
14750    if let Some(value) = value.filter(|value| !value.is_null()) {
14751        decode_wire_avro_value(value, codec)?;
14752    }
14753    Ok(())
14754}
14755
14756fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
14757    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
14758        invalid_recorded_history(
14759            "parallel_group_metadata_invalid",
14760            sequence,
14761            "non-empty parallel_group_id",
14762            &payload.to_string(),
14763            "parallel-group history is missing its stable identity",
14764        )
14765    })?;
14766    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
14767        invalid_recorded_history(
14768            "parallel_group_metadata_invalid",
14769            sequence,
14770            "activity, child, timer, signal, condition, or mixed group kind",
14771            &payload.to_string(),
14772            "parallel-group history is missing its group kind",
14773        )
14774    })?;
14775    if !matches!(
14776        kind.as_str(),
14777        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
14778    ) {
14779        return Err(invalid_recorded_history(
14780            "parallel_group_metadata_invalid",
14781            sequence,
14782            "activity, child, timer, signal, condition, or mixed group kind",
14783            &kind,
14784            "parallel-group history contains an unsupported group kind",
14785        ));
14786    }
14787    let base_sequence = payload
14788        .get("parallel_group_base_sequence")
14789        .and_then(value_as_u64)
14790        .filter(|value| *value > 0)
14791        .ok_or_else(|| {
14792            invalid_recorded_history(
14793                "parallel_group_metadata_invalid",
14794                sequence,
14795                "positive parallel_group_base_sequence",
14796                &payload.to_string(),
14797                "parallel-group history contains an invalid base sequence",
14798            )
14799        })?;
14800    let size = payload
14801        .get("parallel_group_size")
14802        .and_then(value_as_u64)
14803        .and_then(|value| usize::try_from(value).ok())
14804        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
14805        .ok_or_else(|| {
14806            invalid_recorded_history(
14807                "parallel_group_metadata_invalid",
14808                sequence,
14809                "bounded positive parallel_group_size",
14810                &payload.to_string(),
14811                "parallel-group history contains an invalid group size",
14812            )
14813        })?;
14814    let index = payload
14815        .get("parallel_group_index")
14816        .and_then(value_as_u64)
14817        .and_then(|value| usize::try_from(value).ok())
14818        .filter(|value| *value < size)
14819        .ok_or_else(|| {
14820            invalid_recorded_history(
14821                "parallel_group_metadata_invalid",
14822                sequence,
14823                "parallel_group_index within group bounds",
14824                &payload.to_string(),
14825                "parallel-group history contains an invalid member index",
14826            )
14827        })?;
14828    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
14829        return Err(invalid_recorded_history(
14830            "parallel_group_metadata_invalid",
14831            sequence,
14832            "base sequence plus member index equals workflow sequence",
14833            &payload.to_string(),
14834            "parallel-group path does not preserve durable workflow position",
14835        ));
14836    }
14837    let mode = payload
14838        .get("parallel_group_mode")
14839        .and_then(Value::as_str)
14840        .unwrap_or("all");
14841    if !matches!(mode, "all" | "select") {
14842        return Err(invalid_recorded_history(
14843            "parallel_group_metadata_invalid",
14844            sequence,
14845            "parallel group mode all or select",
14846            mode,
14847            "parallel-group history contains an unsupported group mode",
14848        ));
14849    }
14850    let expected_id = if mode == "select" {
14851        format!("select-calls:{base_sequence}:{size}")
14852    } else {
14853        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
14854    };
14855    if group_id != expected_id {
14856        return Err(invalid_recorded_history(
14857            "parallel_group_metadata_invalid",
14858            sequence,
14859            &expected_id,
14860            &group_id,
14861            "parallel-group history contains an incompatible stable group ID",
14862        ));
14863    }
14864    let selection_member_key = if mode == "select" {
14865        Some(selection_key_from_value(
14866            payload.get("selection_member_key"),
14867            sequence,
14868        )?)
14869    } else {
14870        None
14871    };
14872    let selection_member_index = if mode == "select" {
14873        Some(required_parallel_usize(
14874            payload,
14875            "selection_member_index",
14876            sequence,
14877        )?)
14878    } else {
14879        None
14880    };
14881    let selection_member_base_sequence = if mode == "select" {
14882        Some(
14883            payload
14884                .get("selection_member_base_sequence")
14885                .and_then(value_as_u64)
14886                .filter(|value| *value >= base_sequence)
14887                .ok_or_else(|| {
14888                    invalid_recorded_history(
14889                        "parallel_group_metadata_invalid",
14890                        sequence,
14891                        "selection member base within its group",
14892                        &payload.to_string(),
14893                        "selection history contains an invalid member base sequence",
14894                    )
14895                })?,
14896        )
14897    } else {
14898        None
14899    };
14900    let selection_member_size = if mode == "select" {
14901        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
14902        if member_size == 0 {
14903            return Err(invalid_recorded_history(
14904                "parallel_group_metadata_invalid",
14905                sequence,
14906                "positive selection member size",
14907                &payload.to_string(),
14908                "selection history contains an invalid member size",
14909            ));
14910        }
14911        Some(member_size)
14912    } else {
14913        None
14914    };
14915    let selection_member_kind = if mode == "select" {
14916        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
14917            invalid_recorded_history(
14918                "parallel_group_metadata_invalid",
14919                sequence,
14920                "selection member operation kind",
14921                &payload.to_string(),
14922                "selection history is missing its authored member kind",
14923            )
14924        })?;
14925        if !matches!(
14926            kind.as_str(),
14927            "activity" | "child" | "timer" | "signal" | "condition" | "group"
14928        ) {
14929            return Err(invalid_recorded_history(
14930                "parallel_group_metadata_invalid",
14931                sequence,
14932                "activity, child, timer, signal, condition, or group selection member kind",
14933                &kind,
14934                "selection history contains an unsupported member kind",
14935            ));
14936        }
14937        Some(kind)
14938    } else {
14939        None
14940    };
14941    if let (Some(member_base), Some(member_size)) =
14942        (selection_member_base_sequence, selection_member_size)
14943    {
14944        let member_end = member_base
14945            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
14946            .ok_or_else(|| {
14947                invalid_recorded_history(
14948                    "parallel_group_metadata_invalid",
14949                    sequence,
14950                    "bounded selection member range",
14951                    &payload.to_string(),
14952                    "selection member range overflowed",
14953                )
14954            })?;
14955        let group_end = base_sequence
14956            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
14957            .unwrap_or(u64::MAX);
14958        if sequence < member_base || sequence >= member_end || member_end > group_end {
14959            return Err(invalid_recorded_history(
14960                "parallel_group_metadata_invalid",
14961                sequence,
14962                "workflow sequence within one bounded selection member",
14963                &payload.to_string(),
14964                "selection member range does not contain its durable leaf",
14965            ));
14966        }
14967    }
14968    Ok(ParallelGroupMetadata {
14969        parallel_group_id: group_id,
14970        parallel_group_kind: kind,
14971        parallel_group_base_sequence: base_sequence,
14972        parallel_group_size: size,
14973        parallel_group_index: index,
14974        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
14975        selection_member_key,
14976        selection_member_index,
14977        selection_member_base_sequence,
14978        selection_member_size,
14979        selection_member_kind,
14980    })
14981}
14982
14983fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
14984    payload
14985        .get(field)
14986        .and_then(value_as_u64)
14987        .and_then(|value| usize::try_from(value).ok())
14988        .ok_or_else(|| {
14989            invalid_recorded_history(
14990                "parallel_group_metadata_invalid",
14991                sequence,
14992                &format!("non-negative integer {field}"),
14993                &payload.to_string(),
14994                "selection history contains invalid member metadata",
14995            )
14996        })
14997}
14998
14999fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15000    match value {
15001        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15002        Some(value) => value_as_u64(value)
15003            .and_then(|value| usize::try_from(value).ok())
15004            .map(SelectionKey::Index)
15005            .ok_or_else(|| {
15006                invalid_recorded_history(
15007                    "selection_member_key_invalid",
15008                    sequence,
15009                    "non-empty string or non-negative integer member key",
15010                    &value.to_string(),
15011                    "selection history contains an invalid member key",
15012                )
15013            }),
15014        None => Err(invalid_recorded_history(
15015            "selection_member_key_missing",
15016            sequence,
15017            "selection_member_key",
15018            "<missing>",
15019            "selection history is missing its stable member key",
15020        )),
15021    }
15022}
15023
15024fn recorded_parallel_group_path(
15025    events: &[&HistoryEvent],
15026    sequence: u64,
15027) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15028    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15029    for event in events {
15030        let payload = &event.payload;
15031        let has_metadata = payload.get("parallel_group_path").is_some()
15032            || payload.get("parallel_group_id").is_some()
15033            || payload.get("parallel_group_kind").is_some()
15034            || payload.get("parallel_group_base_sequence").is_some()
15035            || payload.get("parallel_group_size").is_some()
15036            || payload.get("parallel_group_index").is_some()
15037            || payload.get("parallel_group_mode").is_some()
15038            || payload.get("selection_member_key").is_some();
15039        if !has_metadata {
15040            continue;
15041        }
15042
15043        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15044        let path = match payload.get("parallel_group_path") {
15045            None => vec![top_level.clone()],
15046            Some(Value::Array(entries)) if !entries.is_empty() => entries
15047                .iter()
15048                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15049                .collect::<Result<Vec<_>>>()?,
15050            Some(value) => {
15051                return Err(invalid_recorded_history(
15052                    "parallel_group_metadata_invalid",
15053                    sequence,
15054                    "non-empty parallel_group_path list",
15055                    &value.to_string(),
15056                    "parallel-group history contains an invalid group path",
15057                ));
15058            }
15059        };
15060        if path.last() != Some(&top_level) {
15061            return Err(invalid_recorded_history(
15062                "parallel_group_metadata_invalid",
15063                sequence,
15064                &serde_json::to_string(&path.last()).unwrap_or_default(),
15065                &serde_json::to_string(&top_level).unwrap_or_default(),
15066                "parallel-group top-level fields do not match the innermost path entry",
15067            ));
15068        }
15069        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15070            return Err(invalid_recorded_history(
15071                "parallel_group_history_conflict",
15072                sequence,
15073                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15074                &serde_json::to_string(&path).unwrap_or_default(),
15075                "parallel-group metadata changed between scheduling and resolution history",
15076            ));
15077        }
15078        recorded = Some(path);
15079    }
15080    Ok(recorded)
15081}
15082
15083fn recorded_commands(
15084    events: &[HistoryEvent],
15085    fallback_codec: &str,
15086    parent: WorkflowIdentity,
15087) -> Result<Vec<RecordedCommand>> {
15088    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15089    let mut last_new_sequence = None;
15090
15091    for event in events {
15092        let is_activity = matches!(
15093            event.event_type.as_str(),
15094            "ActivityScheduled"
15095                | "ActivityStarted"
15096                | "ActivityHeartbeatRecorded"
15097                | "ActivityRetryScheduled"
15098                | "ActivityCompleted"
15099                | "ActivityFailed"
15100                | "ActivityCancelled"
15101                | "ActivityTimedOut"
15102        );
15103        let is_workflow_timer = matches!(
15104            event.event_type.as_str(),
15105            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15106        ) && !is_internal_timer_event(event);
15107        let is_child_workflow = matches!(
15108            event.event_type.as_str(),
15109            "ChildWorkflowScheduled"
15110                | "ChildRunStarted"
15111                | "ChildRunCompleted"
15112                | "ChildRunFailed"
15113                | "ChildRunCancelled"
15114                | "ChildRunTerminated"
15115        );
15116        let is_signal_wait = is_recorded_signal_wait_event(event);
15117        let is_condition_wait = is_recorded_condition_wait_event(event);
15118        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15119        let is_side_effect = event.event_type == "SideEffectRecorded";
15120        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15121        let is_memo = event.event_type == "MemoUpserted";
15122        if !is_activity
15123            && !is_workflow_timer
15124            && !is_child_workflow
15125            && !is_signal_wait
15126            && !is_condition_wait
15127            && !is_search_attributes
15128            && !is_side_effect
15129            && !is_version_marker
15130            && !is_memo
15131        {
15132            continue;
15133        }
15134
15135        let sequence = durable_event_sequence(event).ok_or_else(|| {
15136            Error::NonDeterministicReplay(ReplayFailure::new(
15137                "durable_command_sequence_missing",
15138                None,
15139                Some("positive workflow sequence".to_string()),
15140                Some(event.event_type.clone()),
15141                "durable command history event has no workflow sequence",
15142            ))
15143        })?;
15144        if sequence == 0 {
15145            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15146                "durable_command_sequence_invalid",
15147                Some(sequence),
15148                Some("positive workflow sequence".to_string()),
15149                Some(sequence.to_string()),
15150                "durable command history uses an invalid workflow sequence",
15151            )));
15152        }
15153        if !events_by_sequence.contains_key(&sequence) {
15154            if let Some(previous) = last_new_sequence {
15155                if sequence < previous {
15156                    return Err(invalid_recorded_history(
15157                        "durable_command_sequence_mismatch",
15158                        sequence,
15159                        &format!("workflow sequence greater than {previous}"),
15160                        &sequence.to_string(),
15161                        "durable commands are not strictly ordered by their recorded workflow sequence",
15162                    ));
15163                }
15164            }
15165            last_new_sequence = Some(sequence);
15166        }
15167        events_by_sequence.entry(sequence).or_default().push(event);
15168    }
15169
15170    let commands: Vec<RecordedCommand> = events_by_sequence
15171        .into_iter()
15172        .map(|(sequence, sequence_events)| {
15173            let activity_events: Vec<_> = sequence_events
15174                .iter()
15175                .copied()
15176                .filter(|event| event.event_type.starts_with("Activity"))
15177                .collect();
15178            let timer_events: Vec<_> = sequence_events
15179                .iter()
15180                .copied()
15181                .filter(|event| event.event_type.starts_with("Timer"))
15182                .collect();
15183            let child_events: Vec<_> = sequence_events
15184                .iter()
15185                .copied()
15186                .filter(|event| {
15187                    event.event_type == "ChildWorkflowScheduled"
15188                        || event.event_type.starts_with("ChildRun")
15189                })
15190                .collect();
15191            let signal_wait_events: Vec<_> = sequence_events
15192                .iter()
15193                .copied()
15194                .filter(|event| is_recorded_signal_wait_event(event))
15195                .collect();
15196            let condition_wait_events: Vec<_> = sequence_events
15197                .iter()
15198                .copied()
15199                .filter(|event| is_recorded_condition_wait_event(event))
15200                .collect();
15201            let search_attribute_events: Vec<_> = sequence_events
15202                .iter()
15203                .copied()
15204                .filter(|event| event.event_type == "SearchAttributesUpserted")
15205                .collect();
15206            let side_effect_events: Vec<_> = sequence_events
15207                .iter()
15208                .copied()
15209                .filter(|event| event.event_type == "SideEffectRecorded")
15210                .collect();
15211            let version_marker_events: Vec<_> = sequence_events
15212                .iter()
15213                .copied()
15214                .filter(|event| event.event_type == "VersionMarkerRecorded")
15215                .collect();
15216            let memo_events: Vec<_> = sequence_events
15217                .iter()
15218                .copied()
15219                .filter(|event| event.event_type == "MemoUpserted")
15220                .collect();
15221
15222            let command_kind_count = usize::from(!activity_events.is_empty())
15223                + usize::from(!timer_events.is_empty())
15224                + usize::from(!child_events.is_empty())
15225                + usize::from(!signal_wait_events.is_empty())
15226                + usize::from(!condition_wait_events.is_empty())
15227                + usize::from(!search_attribute_events.is_empty())
15228                + usize::from(!side_effect_events.is_empty())
15229                + usize::from(!version_marker_events.is_empty())
15230                + usize::from(!memo_events.is_empty());
15231            if command_kind_count > 1 {
15232                let actual = [
15233                    (!activity_events.is_empty()).then_some("activity"),
15234                    (!timer_events.is_empty()).then_some("timer"),
15235                    (!child_events.is_empty()).then_some("child workflow"),
15236                    (!signal_wait_events.is_empty()).then_some("signal wait"),
15237                    (!condition_wait_events.is_empty()).then_some("condition wait"),
15238                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
15239                    (!side_effect_events.is_empty()).then_some("side effect"),
15240                    (!version_marker_events.is_empty()).then_some("version marker"),
15241                    (!memo_events.is_empty()).then_some("memo upsert"),
15242                ]
15243                .into_iter()
15244                .flatten()
15245                .collect::<Vec<_>>()
15246                .join(" and ");
15247                return Err(invalid_recorded_history(
15248                    "durable_command_sequence_collision",
15249                    sequence,
15250                    "one durable command kind",
15251                    &actual,
15252                    "one workflow sequence records more than one durable command kind",
15253                ));
15254            }
15255
15256            if !activity_events.is_empty() {
15257                let parallel_group_path =
15258                    recorded_parallel_group_path(&activity_events, sequence)?;
15259                let scheduled_count = activity_events
15260                    .iter()
15261                    .filter(|event| event.event_type == "ActivityScheduled")
15262                    .count();
15263                if scheduled_count > 1 {
15264                    return Err(invalid_recorded_history(
15265                        "duplicate_activity_schedule",
15266                        sequence,
15267                        "at most one ActivityScheduled event",
15268                        "multiple ActivityScheduled events",
15269                        "activity history schedules more than one command at one workflow sequence",
15270                    ));
15271                }
15272                let activity_type = activity_events.iter().find_map(|event| {
15273                    event
15274                        .payload
15275                        .get("activity_type")
15276                        .or_else(|| event.payload.get("activity_name"))
15277                        .and_then(Value::as_str)
15278                        .map(str::to_string)
15279                });
15280                if activity_events.iter().filter_map(|event| {
15281                    event
15282                        .payload
15283                        .get("activity_type")
15284                        .or_else(|| event.payload.get("activity_name"))
15285                        .and_then(Value::as_str)
15286                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
15287                    return Err(invalid_recorded_history(
15288                        "activity_identity_mismatch",
15289                        sequence,
15290                        activity_type.as_deref().unwrap_or("one activity identity"),
15291                        "conflicting activity identities",
15292                        "activity lifecycle events at one workflow sequence disagree on identity",
15293                    ));
15294                }
15295                let terminal: Vec<_> = activity_events
15296                    .iter()
15297                    .copied()
15298                    .filter(|event| {
15299                        matches!(
15300                            event.event_type.as_str(),
15301                            "ActivityCompleted"
15302                                | "ActivityFailed"
15303                                | "ActivityCancelled"
15304                                | "ActivityTimedOut"
15305                        )
15306                    })
15307                    .collect();
15308                let duplicate_delivery = terminal.first().is_some_and(|first| {
15309                    terminal.iter().all(|event| {
15310                        event.event_type == first.event_type && event.payload == first.payload
15311                    })
15312                });
15313                if terminal.len() > 1 && !duplicate_delivery {
15314                    return Err(invalid_recorded_history(
15315                        "duplicate_activity_terminal_event",
15316                        sequence,
15317                        "at most one terminal activity event",
15318                        "multiple terminal activity events",
15319                        "activity history settles one command more than once",
15320                    ));
15321                }
15322                let outcome = terminal
15323                    .first()
15324                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
15325                    .transpose()?;
15326                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
15327                let activity_snapshot = activity_events
15328                    .iter()
15329                    .find(|event| event.event_type == "ActivityScheduled")
15330                    .and_then(|event| event.payload.get("activity"))
15331                    .and_then(Value::as_object);
15332                let options = Some(match activity_snapshot {
15333                    Some(activity) => RecordedActivityOptions {
15334                        task_queue: recorded_optional_string(activity, "queue"),
15335                        execution_mode,
15336                        retry_policy: recorded_activity_retry_snapshot(
15337                            activity.get("retry_policy"),
15338                        ),
15339                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15340                    },
15341                    None => RecordedActivityOptions {
15342                        task_queue: RecordedSnapshotValue::Unknown,
15343                        execution_mode,
15344                        retry_policy: recorded_activity_retry_snapshot(None),
15345                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15346                    },
15347                });
15348                return Ok(RecordedCommand::Activity {
15349                    sequence,
15350                    activity_type,
15351                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
15352                    options,
15353                    outcome,
15354                    parallel_group_path,
15355                });
15356            }
15357
15358            if !child_events.is_empty() {
15359                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
15360                let scheduled: Vec<_> = child_events
15361                    .iter()
15362                    .copied()
15363                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
15364                    .collect();
15365                if scheduled.len() != 1 {
15366                    return Err(invalid_recorded_history(
15367                        "child_workflow_schedule_missing_or_duplicate",
15368                        sequence,
15369                        "one ChildWorkflowScheduled event",
15370                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
15371                        "child workflow replay requires exactly one recorded schedule event",
15372                    ));
15373                }
15374                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
15375                let workflow_type = child_events.iter().find_map(|event| {
15376                    event
15377                        .payload
15378                        .get("child_workflow_type")
15379                        .or_else(|| event.payload.get("workflow_type"))
15380                        .and_then(Value::as_str)
15381                        .filter(|value| !value.is_empty())
15382                        .map(str::to_string)
15383                });
15384                if child_events
15385                    .iter()
15386                    .filter_map(|event| {
15387                        event
15388                            .payload
15389                            .get("child_workflow_type")
15390                            .or_else(|| event.payload.get("workflow_type"))
15391                            .and_then(Value::as_str)
15392                    })
15393                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
15394                {
15395                    return Err(invalid_recorded_history(
15396                        "child_workflow_identity_mismatch",
15397                        sequence,
15398                        workflow_type
15399                            .as_deref()
15400                            .unwrap_or("one child workflow type"),
15401                        "conflicting child workflow types",
15402                        "child workflow lifecycle events at one sequence disagree on type",
15403                    ));
15404                }
15405                let mut outcomes = child_workflow_outcomes(
15406                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
15407                    fallback_codec,
15408                    parent.clone(),
15409                )?;
15410                let terminal_events = child_events
15411                    .iter()
15412                    .copied()
15413                    .filter(|event| event.event_type.starts_with("ChildRun"))
15414                    .collect::<Vec<_>>();
15415                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
15416                    terminal_events.iter().all(|event| {
15417                        event.event_type == first.event_type && event.payload == first.payload
15418                    })
15419                });
15420                if outcomes.len() > 1 && !duplicate_delivery {
15421                    return Err(invalid_recorded_history(
15422                        "duplicate_child_workflow_terminal_event",
15423                        sequence,
15424                        "at most one terminal child event",
15425                        "multiple terminal child events",
15426                        "child workflow history settles one command more than once",
15427                    ));
15428                }
15429                return Ok(RecordedCommand::ChildWorkflow {
15430                    sequence,
15431                    workflow_type,
15432                    policies,
15433                    outcome: outcomes.pop(),
15434                    parallel_group_path,
15435                });
15436            }
15437
15438            if !signal_wait_events.is_empty() {
15439                let opened: Vec<_> = signal_wait_events
15440                    .iter()
15441                    .copied()
15442                    .filter(|event| event.event_type == "SignalWaitOpened")
15443                    .collect();
15444                if opened.len() != 1 {
15445                    return Err(invalid_recorded_history(
15446                        "signal_wait_open_missing_or_duplicate",
15447                        sequence,
15448                        "one SignalWaitOpened event",
15449                        &format!("{} SignalWaitOpened events", opened.len()),
15450                        "signal replay requires exactly one canonical wait-open event",
15451                    ));
15452                }
15453
15454                let applied: Vec<_> = signal_wait_events
15455                    .iter()
15456                    .copied()
15457                    .filter(|event| event.event_type == "SignalApplied")
15458                    .collect();
15459                if applied.len() > 1 {
15460                    return Err(invalid_recorded_history(
15461                        "duplicate_signal_wait_apply",
15462                        sequence,
15463                        "at most one SignalApplied event",
15464                        "multiple SignalApplied events",
15465                        "signal history applies one durable wait more than once",
15466                    ));
15467                }
15468
15469                let signal_names = signal_wait_events
15470                    .iter()
15471                    .map(|event| required_signal_wait_name(event, sequence))
15472                    .collect::<Result<Vec<_>>>()?;
15473                let signal_name = signal_names
15474                    .first()
15475                    .expect("signal wait events are not empty")
15476                    .clone();
15477                if signal_names.iter().any(|candidate| candidate != &signal_name) {
15478                    return Err(invalid_recorded_history(
15479                        "signal_wait_identity_mismatch",
15480                        sequence,
15481                        &signal_name,
15482                        "conflicting signal names",
15483                        "signal wait lifecycle events at one workflow sequence disagree on identity",
15484                    ));
15485                }
15486                let value = applied
15487                    .first()
15488                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
15489                    .transpose()?;
15490                return Ok(RecordedCommand::SignalWait {
15491                    sequence,
15492                    signal_name,
15493                    value,
15494                    parallel_group_path: recorded_parallel_group_path(
15495                        &signal_wait_events,
15496                        sequence,
15497                    )?,
15498                });
15499            }
15500
15501            if !condition_wait_events.is_empty() {
15502                return recorded_condition_wait(
15503                    sequence,
15504                    &condition_wait_events,
15505                    events,
15506                );
15507            }
15508
15509            if !search_attribute_events.is_empty() {
15510                if search_attribute_events.len() != 1 {
15511                    return Err(invalid_recorded_history(
15512                        "duplicate_search_attribute_update",
15513                        sequence,
15514                        "one SearchAttributesUpserted event",
15515                        &format!(
15516                            "{} SearchAttributesUpserted events",
15517                            search_attribute_events.len()
15518                        ),
15519                        "search-attribute history records one workflow command more than once",
15520                    ));
15521                }
15522                let payload = &search_attribute_events[0].payload;
15523                let attributes = payload
15524                    .get("attributes")
15525                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
15526                    .cloned()
15527                    .ok_or_else(|| {
15528                        invalid_recorded_history(
15529                            "search_attribute_update_missing",
15530                            sequence,
15531                            "non-empty attributes object",
15532                            "missing or invalid attributes",
15533                            "search-attribute history is missing its recorded mutation",
15534                        )
15535                    })?;
15536                let attribute_types =
15537                    recorded_search_attribute_types(payload, &attributes, sequence)?;
15538                return Ok(RecordedCommand::SearchAttributes {
15539                    sequence,
15540                    attributes,
15541                    attribute_types,
15542                });
15543            }
15544
15545            if !side_effect_events.is_empty() {
15546                if side_effect_events.len() != 1 {
15547                    return Err(invalid_recorded_history(
15548                        "duplicate_side_effect_record",
15549                        sequence,
15550                        "one SideEffectRecorded event",
15551                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
15552                        "side-effect history records one workflow command more than once",
15553                    ));
15554                }
15555                let event = side_effect_events[0];
15556                let result = event.payload.get("result").ok_or_else(|| {
15557                    invalid_recorded_history(
15558                        "side_effect_result_missing",
15559                        sequence,
15560                        "recorded result payload",
15561                        "missing result",
15562                        "side-effect history is missing its recorded value",
15563                    )
15564                })?;
15565                let has_published_envelope = result.as_str().is_some()
15566                    || result.as_object().is_some_and(|envelope| {
15567                        envelope.get("codec").and_then(Value::as_str).is_some()
15568                            && envelope.get("blob").and_then(Value::as_str).is_some()
15569                    });
15570                if !has_published_envelope {
15571                    return Err(invalid_recorded_history(
15572                        "side_effect_payload_malformed",
15573                        sequence,
15574                        "payload blob or {codec, blob} envelope",
15575                        &result.to_string(),
15576                        "side-effect history result does not use a published payload envelope",
15577                    ));
15578                }
15579                let codec = event
15580                    .payload
15581                    .get("payload_codec")
15582                    .and_then(Value::as_str)
15583                    .unwrap_or(fallback_codec);
15584                let value = decode_wire_avro_value(result, codec).map_err(|error| {
15585                    if error.to_string().contains("unsupported_payload_codec") {
15586                        return error;
15587                    }
15588
15589                    invalid_recorded_history(
15590                        "side_effect_payload_incompatible",
15591                        sequence,
15592                        &format!("valid {codec} payload envelope"),
15593                        &error.to_string(),
15594                        "side-effect history payload cannot be decoded with its recorded codec",
15595                    )
15596                })?;
15597                return Ok(RecordedCommand::SideEffect { sequence, value });
15598            }
15599
15600            if !version_marker_events.is_empty() {
15601                if version_marker_events.len() != 1 {
15602                    return Err(invalid_recorded_history(
15603                        "duplicate_version_marker_record",
15604                        sequence,
15605                        "one VersionMarkerRecorded event",
15606                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
15607                        "version-marker history records one workflow command more than once",
15608                    ));
15609                }
15610                let payload = &version_marker_events[0].payload;
15611                let change_id = payload
15612                    .get("change_id")
15613                    .and_then(Value::as_str)
15614                    .filter(|value| !value.is_empty())
15615                    .map(str::to_string)
15616                    .ok_or_else(|| {
15617                        invalid_recorded_history(
15618                            "version_marker_field_missing",
15619                            sequence,
15620                            "non-empty change_id",
15621                            "missing or invalid change_id",
15622                            "version-marker history is missing its stable change ID",
15623                        )
15624                    })?;
15625                let version = required_version_i32(payload, "version", sequence)?;
15626                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
15627                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
15628                if min_supported > max_supported || version < min_supported || version > max_supported {
15629                    return Err(invalid_recorded_history(
15630                        "version_marker_history_range_invalid",
15631                        sequence,
15632                        "min_supported <= version <= max_supported",
15633                        &format!("{min_supported} <= {version} <= {max_supported}"),
15634                        "recorded version marker contains an internally incompatible range",
15635                    ));
15636                }
15637                return Ok(RecordedCommand::VersionMarker {
15638                    sequence,
15639                    change_id,
15640                    version,
15641                });
15642            }
15643
15644            if !memo_events.is_empty() {
15645                if memo_events.len() != 1 {
15646                    return Err(invalid_recorded_history(
15647                        "duplicate_memo_upsert_record",
15648                        sequence,
15649                        "one MemoUpserted event",
15650                        &format!("{} MemoUpserted events", memo_events.len()),
15651                        "memo history records one workflow update more than once",
15652                    ));
15653                }
15654                let payload = &memo_events[0].payload;
15655                let entries = payload.get("entries").cloned().ok_or_else(|| {
15656                    invalid_recorded_history(
15657                        "memo_entries_missing",
15658                        sequence,
15659                        "memo entries object",
15660                        "missing entries",
15661                        "MemoUpserted history is missing replay identity entries",
15662                    )
15663                })?;
15664                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
15665                    invalid_recorded_history(
15666                        "memo_entries_invalid",
15667                        sequence,
15668                        "valid canonical memo entries",
15669                        &error.to_string(),
15670                        "MemoUpserted history contains invalid replay identity entries",
15671                    )
15672                })?;
15673                let merged = payload.get("merged").cloned().ok_or_else(|| {
15674                    invalid_recorded_history(
15675                        "memo_merged_projection_missing",
15676                        sequence,
15677                        "merged memo projection",
15678                        "missing merged",
15679                        "MemoUpserted history is missing its merged projection",
15680                    )
15681                })?;
15682                decode_memo_history_map(&merged, false).map_err(|error| {
15683                    invalid_recorded_history(
15684                        "memo_merged_projection_invalid",
15685                        sequence,
15686                        "valid merged memo projection",
15687                        &error.to_string(),
15688                        "MemoUpserted history contains an invalid merged projection",
15689                    )
15690                })?;
15691
15692                return Ok(RecordedCommand::Memo { sequence, entries });
15693            }
15694            let scheduled: Vec<_> = timer_events
15695                .iter()
15696                .copied()
15697                .filter(|event| event.event_type == "TimerScheduled")
15698                .collect();
15699            let fired: Vec<_> = timer_events
15700                .iter()
15701                .copied()
15702                .filter(|event| event.event_type == "TimerFired")
15703                .collect();
15704            if scheduled.len() != 1 {
15705                return Err(invalid_recorded_history(
15706                    "timer_schedule_missing_or_duplicate",
15707                    sequence,
15708                    "one TimerScheduled event",
15709                    &format!("{} TimerScheduled events", scheduled.len()),
15710                    "timer replay requires exactly one recorded schedule event",
15711                ));
15712            }
15713            if fired.len() > 1 {
15714                return Err(invalid_recorded_history(
15715                    "duplicate_timer_fire",
15716                    sequence,
15717                    "at most one TimerFired event",
15718                    "multiple TimerFired events",
15719                    "timer history contains more than one fire event for a workflow sequence",
15720                ));
15721            }
15722
15723            let scheduled = scheduled[0];
15724            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
15725            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
15726            if let Some(fired) = fired.first() {
15727                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
15728                if fired_timer_id != timer_id {
15729                    return Err(invalid_recorded_history(
15730                        "timer_identity_mismatch",
15731                        sequence,
15732                        &timer_id,
15733                        &fired_timer_id,
15734                        "TimerFired does not correspond to the recorded TimerScheduled event",
15735                    ));
15736                }
15737                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
15738                if fired_delay != delay_seconds {
15739                    return Err(invalid_recorded_history(
15740                        "timer_history_delay_mismatch",
15741                        sequence,
15742                        &delay_seconds.to_string(),
15743                        &fired_delay.to_string(),
15744                        "TimerScheduled and TimerFired record different delays",
15745                    ));
15746                }
15747            }
15748
15749            Ok(RecordedCommand::Timer {
15750                sequence,
15751                delay_seconds,
15752                fired: !fired.is_empty(),
15753                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
15754            })
15755        })
15756        .collect::<Result<_>>()?;
15757
15758    let mut marker_sequences = HashMap::new();
15759    for command in &commands {
15760        if let RecordedCommand::VersionMarker {
15761            sequence,
15762            change_id,
15763            ..
15764        } = command
15765        {
15766            if let Some(first_sequence) = marker_sequences.insert(change_id.clone(), *sequence) {
15767                return Err(invalid_recorded_history(
15768                    "duplicate_version_marker",
15769                    *sequence,
15770                    &format!("one marker for change ID {change_id:?}"),
15771                    &format!("markers at sequences {first_sequence} and {sequence}"),
15772                    "workflow history contains duplicate markers for one stable change ID",
15773                ));
15774            }
15775        }
15776    }
15777
15778    Ok(commands)
15779}
15780
15781fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
15782    payload
15783        .get(field)
15784        .and_then(Value::as_i64)
15785        .and_then(|value| i32::try_from(value).ok())
15786        .ok_or_else(|| {
15787            invalid_recorded_history(
15788                "version_marker_field_missing",
15789                sequence,
15790                &format!("integer {field}"),
15791                "missing or out-of-range integer",
15792                "version-marker history is missing a required integer field",
15793            )
15794        })
15795}
15796
15797fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
15798    event
15799        .payload
15800        .get("sequence")
15801        .or_else(|| event.payload.get("workflow_sequence"))
15802        .or_else(|| event.raw.get("sequence"))
15803        .or_else(|| event.raw.get("workflow_sequence"))
15804        .and_then(value_as_u64)
15805}
15806
15807fn is_internal_timer_event(event: &HistoryEvent) -> bool {
15808    matches!(
15809        event
15810            .payload
15811            .get("timer_kind")
15812            .or_else(|| event.raw.get("timer_kind"))
15813            .and_then(Value::as_str),
15814        Some("condition_timeout" | "signal_timeout")
15815    )
15816}
15817
15818fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
15819    matches!(
15820        event.event_type.as_str(),
15821        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15822    )
15823}
15824
15825fn recorded_condition_wait(
15826    sequence: u64,
15827    condition_events: &[&HistoryEvent],
15828    all_events: &[HistoryEvent],
15829) -> Result<RecordedCommand> {
15830    let opened = condition_events
15831        .iter()
15832        .copied()
15833        .filter(|event| event.event_type == "ConditionWaitOpened")
15834        .collect::<Vec<_>>();
15835    if opened.len() != 1 {
15836        return Err(invalid_recorded_history(
15837            "condition_wait_open_missing_or_duplicate",
15838            sequence,
15839            "one ConditionWaitOpened event",
15840            &format!("{} ConditionWaitOpened events", opened.len()),
15841            "condition replay requires exactly one canonical wait-open event",
15842        ));
15843    }
15844    let terminal = condition_events
15845        .iter()
15846        .copied()
15847        .filter(|event| {
15848            matches!(
15849                event.event_type.as_str(),
15850                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15851            )
15852        })
15853        .collect::<Vec<_>>();
15854    if terminal.len() > 1 {
15855        return Err(invalid_recorded_history(
15856            "duplicate_condition_wait_terminal_event",
15857            sequence,
15858            "at most one condition terminal event",
15859            "multiple condition terminal events",
15860            "condition history settles one durable wait more than once",
15861        ));
15862    }
15863
15864    let opened = opened[0];
15865    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
15866    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
15867    for event in condition_events
15868        .iter()
15869        .copied()
15870        .filter(|event| !std::ptr::eq(*event, opened))
15871    {
15872        let event_wait_id = required_condition_wait_id(event, sequence)?;
15873        if event_wait_id != condition_wait_id {
15874            return Err(invalid_recorded_history(
15875                "condition_wait_id_mismatch",
15876                sequence,
15877                &condition_wait_id,
15878                &event_wait_id,
15879                "condition lifecycle events at one sequence disagree on wait identity",
15880            ));
15881        }
15882        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
15883        if event_occurrence_id != occurrence_id {
15884            return Err(invalid_recorded_history(
15885                "condition_wait_occurrence_history_mismatch",
15886                sequence,
15887                &occurrence_id,
15888                &event_occurrence_id,
15889                "condition lifecycle events at one sequence disagree on authored occurrence identity",
15890            ));
15891        }
15892    }
15893
15894    let condition_key = optional_non_empty_history_string(opened, "condition_key");
15895    let predicate_identity = opened
15896        .payload
15897        .get("condition_definition_fingerprint")
15898        .and_then(Value::as_str)
15899        .filter(|value| !value.is_empty())
15900        .map(str::to_string)
15901        .ok_or_else(|| {
15902            invalid_recorded_history(
15903                "condition_wait_predicate_fingerprint_missing",
15904                sequence,
15905                "non-empty condition_definition_fingerprint",
15906                &opened.event_type,
15907                "canonical condition history is missing its predicate identity",
15908            )
15909        })?;
15910    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
15911    for event in condition_events
15912        .iter()
15913        .copied()
15914        .filter(|event| !std::ptr::eq(*event, opened))
15915    {
15916        for (field, opened_value) in [
15917            ("condition_key", condition_key.as_deref()),
15918            (
15919                "condition_definition_fingerprint",
15920                Some(predicate_identity.as_str()),
15921            ),
15922        ] {
15923            if let Some(value) = optional_non_empty_history_string(event, field) {
15924                if opened_value.is_some_and(|opened_value| opened_value != value) {
15925                    return Err(invalid_recorded_history(
15926                        "condition_wait_definition_history_mismatch",
15927                        sequence,
15928                        opened_value.unwrap_or_default(),
15929                        &value,
15930                        "condition lifecycle events disagree on the recorded definition",
15931                    ));
15932                }
15933            }
15934        }
15935        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
15936            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
15937                return Err(invalid_recorded_history(
15938                    "condition_wait_definition_history_mismatch",
15939                    sequence,
15940                    &format!("{}s", timeout_seconds.unwrap_or_default()),
15941                    &format!("{event_timeout}s"),
15942                    "condition lifecycle events disagree on the recorded timeout",
15943                ));
15944            }
15945        }
15946    }
15947
15948    let timeout_timer_events = all_events
15949        .iter()
15950        .filter(|event| {
15951            matches!(
15952                event.event_type.as_str(),
15953                "TimerScheduled" | "TimerCancelled" | "TimerFired"
15954            ) && event.payload.get("timer_kind").and_then(Value::as_str)
15955                == Some("condition_timeout")
15956                && event
15957                    .payload
15958                    .get("condition_wait_id")
15959                    .and_then(Value::as_str)
15960                    == Some(condition_wait_id.as_str())
15961        })
15962        .collect::<Vec<_>>();
15963    let scheduled = timeout_timer_events
15964        .iter()
15965        .copied()
15966        .filter(|event| event.event_type == "TimerScheduled")
15967        .collect::<Vec<_>>();
15968    let fired = timeout_timer_events
15969        .iter()
15970        .copied()
15971        .filter(|event| event.event_type == "TimerFired")
15972        .collect::<Vec<_>>();
15973    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
15974        return Err(invalid_recorded_history(
15975            "condition_wait_timeout_history_invalid",
15976            sequence,
15977            "one timeout schedule and at most one fire",
15978            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
15979            "condition timeout history has a missing or duplicate lifecycle event",
15980        ));
15981    }
15982    if let Some(scheduled) = scheduled.first() {
15983        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
15984        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
15985        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
15986            return Err(invalid_recorded_history(
15987                "condition_wait_timeout_delay_mismatch",
15988                sequence,
15989                &format!("{}s", timeout_seconds.unwrap_or_default()),
15990                &format!("{delay_seconds}s"),
15991                "condition timeout timer differs from the wait definition",
15992            ));
15993        }
15994        if let Some(fired) = fired.first() {
15995            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
15996            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
15997            if fired_timer_id != timer_id || fired_delay != delay_seconds {
15998                return Err(invalid_recorded_history(
15999                    "condition_wait_timeout_identity_mismatch",
16000                    sequence,
16001                    &format!("{timer_id}:{delay_seconds}s"),
16002                    &format!("{fired_timer_id}:{fired_delay}s"),
16003                    "condition timeout fire does not match its durable schedule",
16004                ));
16005            }
16006        }
16007    }
16008
16009    let result = terminal.first().map(|event| {
16010        if event.event_type == "ConditionWaitTimedOut" {
16011            ConditionWaitResult::TimedOut
16012        } else {
16013            ConditionWaitResult::Satisfied
16014        }
16015    });
16016    let result = if !fired.is_empty() {
16017        if result == Some(ConditionWaitResult::Satisfied) {
16018            return Err(invalid_recorded_history(
16019                "condition_wait_terminal_conflict",
16020                sequence,
16021                "one satisfied or timed-out outcome",
16022                "satisfied event and fired timeout",
16023                "condition history records conflicting terminal outcomes",
16024            ));
16025        }
16026        Some(ConditionWaitResult::TimedOut)
16027    } else {
16028        result
16029    };
16030
16031    Ok(RecordedCommand::ConditionWait {
16032        sequence,
16033        occurrence_id,
16034        condition_key,
16035        predicate_identity,
16036        timeout_seconds,
16037        result,
16038        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16039    })
16040}
16041
16042fn recorded_condition_group_path(
16043    condition_events: &[&HistoryEvent],
16044    all_events: &[HistoryEvent],
16045    sequence: u64,
16046) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16047    let opened = condition_events
16048        .iter()
16049        .copied()
16050        .find(|event| event.event_type == "ConditionWaitOpened")
16051        .expect("canonical condition opener is validated first");
16052    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16053    let previous_events = all_events
16054        .iter()
16055        .take_while(|event| !std::ptr::eq(*event, opened))
16056        .collect::<Vec<_>>();
16057    let originals = previous_events
16058        .iter()
16059        .copied()
16060        .filter(|event| event.event_type == "ConditionWaitOpened")
16061        .filter(|event| {
16062            event
16063                .payload
16064                .get("condition_wait_occurrence_id")
16065                .and_then(Value::as_str)
16066                == Some(occurrence.as_str())
16067        })
16068        .collect::<Vec<_>>();
16069    let Some(original) = originals.first().copied() else {
16070        return recorded_parallel_group_path(condition_events, sequence);
16071    };
16072    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16073    if authored_sequence == sequence {
16074        return recorded_parallel_group_path(condition_events, sequence);
16075    }
16076    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16077    if original_path.is_none() {
16078        return recorded_parallel_group_path(condition_events, sequence);
16079    }
16080    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16081    let identity_matches = [
16082        "condition_key",
16083        "condition_definition_fingerprint",
16084        "timeout_seconds",
16085    ]
16086    .iter()
16087    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16088    let previous = originals
16089        .iter()
16090        .copied()
16091        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16092        .max_by_key(|event| durable_event_sequence(event));
16093    let previously_satisfied = previous.is_some_and(|previous| {
16094        previous_events.iter().any(|event| {
16095            event.event_type == "ConditionWaitSatisfied"
16096                && event.payload.get("condition_wait_id")
16097                    == previous.payload.get("condition_wait_id")
16098                && event.payload.get("condition_wait_occurrence_id")
16099                    == previous.payload.get("condition_wait_occurrence_id")
16100                && durable_event_sequence(event) == durable_event_sequence(previous)
16101        })
16102    });
16103    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16104        return Err(invalid_recorded_history(
16105            "condition_wait_group_reopen_mismatch",
16106            sequence,
16107            "same authored condition and group path after a satisfied physical wait",
16108            &opened.payload.to_string(),
16109            "grouped condition reopen has no matching recorded predecessor",
16110        ));
16111    }
16112    Ok(reopened_path)
16113}
16114
16115fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16116    event
16117        .payload
16118        .get("condition_wait_occurrence_id")
16119        .and_then(Value::as_str)
16120        .filter(|value| !value.is_empty())
16121        .map(str::to_string)
16122        .ok_or_else(|| {
16123            invalid_recorded_history(
16124                "condition_wait_occurrence_id_missing",
16125                sequence,
16126                "non-empty condition_wait_occurrence_id",
16127                &event.event_type,
16128                "condition history is missing authored occurrence identity",
16129            )
16130        })
16131}
16132
16133fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16134    event
16135        .payload
16136        .get("condition_wait_id")
16137        .and_then(Value::as_str)
16138        .filter(|value| !value.is_empty())
16139        .map(str::to_string)
16140        .ok_or_else(|| {
16141            invalid_recorded_history(
16142                "condition_wait_id_missing",
16143                sequence,
16144                "non-empty condition_wait_id",
16145                &event.event_type,
16146                "canonical condition history is missing its durable wait identity",
16147            )
16148        })
16149}
16150
16151fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16152    event
16153        .payload
16154        .get(field)
16155        .and_then(Value::as_str)
16156        .filter(|value| !value.is_empty())
16157        .map(str::to_string)
16158}
16159
16160fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16161    match event.payload.get(field) {
16162        None | Some(Value::Null) => Ok(None),
16163        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16164            invalid_recorded_history(
16165                "condition_wait_definition_invalid",
16166                sequence,
16167                &format!("non-negative integer {field}"),
16168                &value.to_string(),
16169                "condition history contains an invalid numeric definition field",
16170            )
16171        }),
16172    }
16173}
16174
16175fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16176    event
16177        .payload
16178        .get("signal_name")
16179        .or_else(|| event.raw.get("signal_name"))
16180        .and_then(Value::as_str)
16181        .filter(|value| !value.is_empty())
16182        .map(str::to_string)
16183        .ok_or_else(|| {
16184            invalid_recorded_history(
16185                "signal_wait_name_missing",
16186                sequence,
16187                "non-empty signal_name",
16188                &event.event_type,
16189                "canonical signal-wait history is missing its signal identity",
16190            )
16191        })
16192}
16193
16194fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16195    matches!(
16196        event.event_type.as_str(),
16197        "SignalWaitOpened" | "SignalApplied"
16198    )
16199}
16200
16201fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
16202    event
16203        .payload
16204        .get(field)
16205        .and_then(Value::as_str)
16206        .filter(|value| !value.is_empty())
16207        .map(str::to_string)
16208        .ok_or_else(|| {
16209            invalid_recorded_history(
16210                "timer_history_field_missing",
16211                sequence,
16212                field,
16213                &event.event_type,
16214                "timer history is missing a required identity field",
16215            )
16216        })
16217}
16218
16219fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
16220    event
16221        .payload
16222        .get(field)
16223        .and_then(value_as_u64)
16224        .ok_or_else(|| {
16225            invalid_recorded_history(
16226                "timer_history_field_missing",
16227                sequence,
16228                field,
16229                &event.event_type,
16230                "timer history is missing a required numeric field",
16231            )
16232        })
16233}
16234
16235fn recorded_search_attribute_types(
16236    payload: &Value,
16237    attributes: &Value,
16238    sequence: u64,
16239) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
16240    let Some(raw_types) = payload.get("attribute_types") else {
16241        // This is the explicit compatibility rule for histories recorded
16242        // before typed identity was persisted. Values still constrain replay;
16243        // the unknown type snapshot does not assert a typed match.
16244        return Ok(RecordedSnapshotValue::Unknown);
16245    };
16246    let Some(raw_types) = raw_types.as_object() else {
16247        return Err(invalid_recorded_history(
16248            "search_attribute_types_malformed",
16249            sequence,
16250            "canonical attribute type map",
16251            &raw_types.to_string(),
16252            "search-attribute history contains malformed type identity",
16253        ));
16254    };
16255    let attribute_keys = attributes
16256        .as_object()
16257        .expect("recorded search attributes were validated as an object");
16258    let mut types = BTreeMap::new();
16259    for (key, value) in raw_types {
16260        let Some(attribute_type) = value.as_str() else {
16261            return Err(invalid_recorded_history(
16262                "search_attribute_types_malformed",
16263                sequence,
16264                "canonical string type name",
16265                &value.to_string(),
16266                "search-attribute history contains a non-string type identity",
16267            ));
16268        };
16269        if !attribute_keys.contains_key(key)
16270            || !matches!(
16271                attribute_type,
16272                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
16273            )
16274        {
16275            return Err(invalid_recorded_history(
16276                "search_attribute_types_malformed",
16277                sequence,
16278                "canonical types for keys present in attributes",
16279                &format!("{key}:{attribute_type}"),
16280                "search-attribute history contains unsupported or orphaned type identity",
16281            ));
16282        }
16283        types.insert(key.clone(), attribute_type.to_string());
16284    }
16285    Ok(RecordedSnapshotValue::Known(types))
16286}
16287
16288fn invalid_recorded_history(
16289    reason: &str,
16290    sequence: u64,
16291    expected: &str,
16292    actual: &str,
16293    message: &str,
16294) -> Error {
16295    Error::NonDeterministicReplay(ReplayFailure::new(
16296        reason,
16297        Some(sequence),
16298        Some(expected.to_string()),
16299        Some(actual.to_string()),
16300        message,
16301    ))
16302}
16303
16304type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
16305
16306fn activity_outcome(
16307    event: &HistoryEvent,
16308    fallback_codec: &str,
16309    recorded_activity_type: Option<String>,
16310) -> Result<ActivityOutcome> {
16311    if event.event_type == "ActivityCompleted" {
16312        let codec = event
16313            .payload
16314            .get("payload_codec")
16315            .and_then(Value::as_str)
16316            .unwrap_or(fallback_codec);
16317        return Ok(Ok(decode_wire_avro_value(
16318            event.payload.get("result").unwrap_or(&Value::Null),
16319            codec,
16320        )?));
16321    }
16322
16323    let payload = &event.payload;
16324    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
16325        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
16326        "ActivityCancelled" => (
16327            ActivityFailureKind::Cancelled,
16328            "cancelled",
16329            "activity was cancelled",
16330        ),
16331        "ActivityTimedOut" => (
16332            ActivityFailureKind::TimedOut,
16333            "timeout",
16334            "activity timed out",
16335        ),
16336        _ => unreachable!("activity_outcome is called only for terminal activity events"),
16337    };
16338    let exception = payload
16339        .get("exception")
16340        .filter(|value| !value.is_null())
16341        .cloned();
16342    let failure_category = payload_string(payload, "failure_category");
16343    let timeout_kind = payload_string(payload, "timeout_kind");
16344    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
16345        ActivityFailureKind::Failed => failure_category
16346            .clone()
16347            .unwrap_or_else(|| fallback_reason.to_string()),
16348        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
16349        ActivityFailureKind::TimedOut => timeout_kind
16350            .clone()
16351            .unwrap_or_else(|| fallback_reason.to_string()),
16352    });
16353    let message = payload_string(payload, "message")
16354        .or_else(|| {
16355            exception
16356                .as_ref()
16357                .and_then(|value| payload_string(value, "message"))
16358        })
16359        .unwrap_or_else(|| fallback_message.to_string());
16360
16361    Ok(Err(ActivityFailure {
16362        kind,
16363        reason,
16364        message,
16365        activity_execution_id: payload_string(payload, "activity_execution_id"),
16366        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
16367        activity_type: payload_string(payload, "activity_type")
16368            .or_else(|| payload_string(payload, "activity_name"))
16369            .or(recorded_activity_type),
16370        activity_class: payload_string(payload, "activity_class"),
16371        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
16372        failure_id: payload_string(payload, "failure_id"),
16373        failure_category,
16374        timeout_kind,
16375        non_retryable: payload
16376            .get("non_retryable")
16377            .and_then(Value::as_bool)
16378            .unwrap_or(false),
16379        exception_type: payload_string(payload, "exception_type").or_else(|| {
16380            exception
16381                .as_ref()
16382                .and_then(|value| payload_string(value, "type"))
16383        }),
16384        exception_class: payload_string(payload, "exception_class").or_else(|| {
16385            exception
16386                .as_ref()
16387                .and_then(|value| payload_string(value, "class"))
16388        }),
16389        code: payload
16390            .get("code")
16391            .filter(|value| !value.is_null())
16392            .cloned(),
16393        exception,
16394    }))
16395}
16396
16397type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
16398
16399fn child_workflow_outcomes(
16400    events: &[HistoryEvent],
16401    fallback_codec: &str,
16402    parent: WorkflowIdentity,
16403) -> Result<Vec<ChildWorkflowOutcome>> {
16404    let mut outcomes = Vec::new();
16405
16406    for event in events {
16407        let kind = match event.event_type.as_str() {
16408            "ChildRunCompleted" => None,
16409            "ChildRunFailed" => Some((
16410                ChildWorkflowFailureKind::Failed,
16411                "child_workflow",
16412                "child workflow failed",
16413            )),
16414            "ChildRunCancelled" => Some((
16415                ChildWorkflowFailureKind::Cancelled,
16416                "cancelled",
16417                "child workflow was cancelled",
16418            )),
16419            "ChildRunTerminated" => Some((
16420                ChildWorkflowFailureKind::Terminated,
16421                "terminated",
16422                "child workflow was terminated",
16423            )),
16424            _ => continue,
16425        };
16426        let payload = &event.payload;
16427        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
16428        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
16429        let child_workflow_type = payload_string(payload, "child_workflow_type");
16430
16431        if let Some((kind, reason, fallback_message)) = kind {
16432            let exception = payload
16433                .get("exception")
16434                .filter(|value| !value.is_null())
16435                .cloned();
16436            let message = payload_string(payload, "message")
16437                .or_else(|| {
16438                    exception
16439                        .as_ref()
16440                        .and_then(|value| payload_string(value, "message"))
16441                })
16442                .unwrap_or_else(|| fallback_message.to_string());
16443            let exception_type = payload_string(payload, "exception_type").or_else(|| {
16444                exception
16445                    .as_ref()
16446                    .and_then(|value| payload_string(value, "type"))
16447            });
16448            let exception_class = payload_string(payload, "exception_class").or_else(|| {
16449                exception
16450                    .as_ref()
16451                    .and_then(|value| payload_string(value, "class"))
16452            });
16453            outcomes.push(Err(ChildWorkflowFailure {
16454                kind,
16455                reason: reason.to_string(),
16456                message,
16457                parent_workflow_id: parent.workflow_id.clone(),
16458                parent_workflow_run_id: parent.run_id.clone(),
16459                child_workflow_id,
16460                child_workflow_run_id,
16461                child_workflow_type,
16462                failure_id: payload_string(payload, "failure_id"),
16463                failure_category: payload_string(payload, "failure_category"),
16464                exception_type,
16465                exception_class,
16466                non_retryable: payload
16467                    .get("non_retryable")
16468                    .and_then(Value::as_bool)
16469                    .unwrap_or(false),
16470                code: payload
16471                    .get("code")
16472                    .filter(|value| !value.is_null())
16473                    .cloned(),
16474                exception,
16475            }));
16476            continue;
16477        }
16478
16479        let codec = payload
16480            .get("payload_codec")
16481            .and_then(Value::as_str)
16482            .unwrap_or(fallback_codec);
16483        let result = payload
16484            .get("result")
16485            .or_else(|| payload.get("output"))
16486            .unwrap_or(&Value::Null);
16487        outcomes.push(Ok(ChildWorkflowAvroResult {
16488            parent: parent.clone(),
16489            child: WorkflowIdentity {
16490                workflow_id: child_workflow_id,
16491                run_id: child_workflow_run_id,
16492            },
16493            child_workflow_type,
16494            result: decode_wire_avro_value(result, codec)?,
16495        }));
16496    }
16497
16498    Ok(outcomes)
16499}
16500
16501fn payload_string(payload: &Value, key: &str) -> Option<String> {
16502    payload
16503        .get(key)
16504        .and_then(Value::as_str)
16505        .filter(|value| !value.is_empty())
16506        .map(str::to_string)
16507}
16508
16509fn recorded_activity_failure_boundary(
16510    ctx: &WorkflowContext,
16511    error: &Error,
16512) -> Option<(u64, String)> {
16513    let Error::ActivityFailed(failure) = error else {
16514        return None;
16515    };
16516    if failure.kind != ActivityFailureKind::Failed {
16517        return None;
16518    }
16519    let activity_execution_id = failure
16520        .activity_execution_id
16521        .as_deref()
16522        .filter(|value| !value.is_empty())?;
16523    let state = ctx.state.lock().ok()?;
16524    let mut matches = state.recorded_commands.iter().filter_map(|command| {
16525        let RecordedCommand::Activity {
16526            sequence,
16527            outcome: Some(Err(recorded_failure)),
16528            ..
16529        } = command
16530        else {
16531            return None;
16532        };
16533        (*sequence > 0 && recorded_failure == failure)
16534            .then_some((*sequence, activity_execution_id.to_string()))
16535    });
16536    let boundary = matches.next()?;
16537    matches.next().is_none().then_some(boundary)
16538}
16539
16540fn workflow_failure_command(
16541    error: &Error,
16542    failed_activity_boundary: Option<(u64, String)>,
16543) -> Value {
16544    let (exception_type, exception_class, properties) = match error {
16545        Error::ActivityFailed(failure) => (
16546            match failure.kind {
16547                ActivityFailureKind::Failed => "ActivityFailed",
16548                ActivityFailureKind::Cancelled => "ActivityCancelled",
16549                ActivityFailureKind::TimedOut => "ActivityTimedOut",
16550            },
16551            "durable_workflow::ActivityFailure",
16552            json!({
16553                "reason": failure.reason,
16554                "activity_execution_id": failure.activity_execution_id,
16555                "activity_attempt_id": failure.activity_attempt_id,
16556                "activity_type": failure.activity_type,
16557                "activity_class": failure.activity_class,
16558                "attempt_number": failure.attempt_number,
16559                "failure_id": failure.failure_id,
16560                "failure_category": failure.failure_category,
16561                "timeout_kind": failure.timeout_kind,
16562                "activity_non_retryable": failure.non_retryable,
16563                "activity_exception_type": failure.exception_type,
16564                "activity_exception_class": failure.exception_class,
16565                "activity_code": failure.code,
16566                "activity_exception": failure.exception,
16567            }),
16568        ),
16569        Error::ChildWorkflowFailed(failure) => (
16570            match failure.kind {
16571                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16572                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16573                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16574            },
16575            "durable_workflow::ChildWorkflowFailure",
16576            json!({
16577                "reason": failure.reason,
16578                "parent_workflow_id": failure.parent_workflow_id,
16579                "parent_workflow_run_id": failure.parent_workflow_run_id,
16580                "child_workflow_id": failure.child_workflow_id,
16581                "child_workflow_run_id": failure.child_workflow_run_id,
16582                "child_workflow_type": failure.child_workflow_type,
16583                "failure_id": failure.failure_id,
16584                "failure_category": failure.failure_category,
16585                "child_exception_type": failure.exception_type,
16586                "child_exception_class": failure.exception_class,
16587                "child_non_retryable": failure.non_retryable,
16588                "child_code": failure.code,
16589                "child_exception": failure.exception,
16590            }),
16591        ),
16592        Error::ParallelFailed(failure) => (
16593            "ParallelFailed",
16594            "durable_workflow::ParallelFailure",
16595            json!({
16596                "parallel_group_id": failure.group_id,
16597                "parallel_member_path": failure.member_path,
16598                "parallel_group_path": failure.group_path,
16599                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
16600                "cause_type": workflow_error_type(&failure.cause),
16601                "cause_message": failure.cause.to_string(),
16602            }),
16603        ),
16604        Error::SagaCompensationFailed(failure) => (
16605            "SagaCompensationFailed",
16606            "durable_workflow::SagaCompensationFailure",
16607            json!({
16608                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
16609                "initiating_failure_message": failure.initiating_failure.to_string(),
16610                "compensation_activity_type": failure.compensation_activity_type,
16611                "compensation_registration_order": failure.compensation_registration_order,
16612                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
16613                "compensation_failure_message": failure.compensation_failure.to_string(),
16614            }),
16615        ),
16616        Error::WorkflowCancellationRequested(_) => (
16617            "WorkflowCancellationRequested",
16618            "durable_workflow::WorkflowCancellationRequested",
16619            json!({"reason": "cancelled"}),
16620        ),
16621        Error::CooperativeCancellationRequested(cancellation) => (
16622            "WorkflowCancellationRequested",
16623            "durable_workflow::CooperativeCancellationRequested",
16624            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
16625                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
16626        ),
16627        Error::CancellationScopeRequested(cancellation) => (
16628            "WorkflowCancellationRequested",
16629            "durable_workflow::CancellationScopeRequested",
16630            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
16631                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
16632                "cancellation":cancellation.context.to_value()}),
16633        ),
16634        Error::NonDeterministicReplay(_) => (
16635            "NonDeterministicReplay",
16636            "durable_workflow::Error",
16637            Value::Null,
16638        ),
16639        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
16640    };
16641    let non_retryable = match error {
16642        Error::ActivityFailed(failure) => failure.non_retryable,
16643        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16644        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16645        Error::SagaCompensationFailed(failure) => {
16646            workflow_error_non_retryable(&failure.compensation_failure)
16647        }
16648        Error::WorkflowCancellationRequested(_)
16649        | Error::CooperativeCancellationRequested(_)
16650        | Error::CancellationScopeRequested(_) => true,
16651        Error::NonDeterministicReplay(_) => true,
16652        _ => false,
16653    };
16654
16655    let mut command = json!({
16656        "type": "fail_workflow",
16657        "message": error.to_string(),
16658        "exception_type": exception_type,
16659        "exception_class": exception_class,
16660        "non_retryable": non_retryable,
16661        "exception": {
16662            "type": exception_type,
16663            "class": exception_class,
16664            "message": error.to_string(),
16665            "properties": properties,
16666        }
16667    });
16668
16669    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
16670        command["failed_step_sequence"] = json!(sequence);
16671        command["failed_activity_execution_id"] = json!(activity_execution_id);
16672    }
16673
16674    command
16675}
16676
16677fn workflow_error_type(error: &Error) -> &'static str {
16678    match error {
16679        Error::ActivityFailed(failure) => match failure.kind {
16680            ActivityFailureKind::Failed => "ActivityFailed",
16681            ActivityFailureKind::Cancelled => "ActivityCancelled",
16682            ActivityFailureKind::TimedOut => "ActivityTimedOut",
16683        },
16684        Error::ChildWorkflowFailed(failure) => match failure.kind {
16685            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16686            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16687            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16688        },
16689        Error::ParallelFailed(_) => "ParallelFailed",
16690        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
16691        Error::WorkflowCancellationRequested(_)
16692        | Error::CooperativeCancellationRequested(_)
16693        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
16694        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
16695        _ => "RustWorkflowError",
16696    }
16697}
16698
16699fn workflow_error_non_retryable(error: &Error) -> bool {
16700    match error {
16701        Error::ActivityFailed(failure) => failure.non_retryable,
16702        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16703        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16704        Error::SagaCompensationFailed(failure) => {
16705            workflow_error_non_retryable(&failure.compensation_failure)
16706        }
16707        Error::WorkflowCancellationRequested(_)
16708        | Error::CooperativeCancellationRequested(_)
16709        | Error::CancellationScopeRequested(_)
16710        | Error::NonDeterministicReplay(_) => true,
16711        _ => false,
16712    }
16713}
16714
16715fn workflow_task_integrity_error(error: &Error) -> bool {
16716    matches!(
16717        error,
16718        Error::NonDeterministicReplay(_)
16719            | Error::Protocol(_)
16720            | Error::CancellationScopeExecutionUnavailable
16721            | Error::MissingWorkflowCommandIdentity
16722            | Error::WorkflowStatePoisoned
16723    )
16724}
16725
16726fn decode_signal_event_arguments(
16727    event: &HistoryEvent,
16728    fallback_codec: &str,
16729) -> Result<Vec<AvroValue>> {
16730    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16731    validate_payload_codec(codec)?;
16732    let raw = signal_history_payload(&event.payload);
16733    let decoded = match raw.filter(|value| !value.is_null()) {
16734        Some(value) => decode_wire_avro_value(value, codec)?,
16735        None => AvroValue::Array(Vec::new()),
16736    };
16737    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16738        unreachable!("normalize_avro_arguments always returns an array");
16739    };
16740    Ok(arguments)
16741}
16742
16743fn decode_update_event_arguments(
16744    event: &HistoryEvent,
16745    fallback_codec: &str,
16746) -> Result<Vec<AvroValue>> {
16747    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16748    validate_payload_codec(codec)?;
16749    let decoded = match event
16750        .payload
16751        .get("arguments")
16752        .filter(|value| !value.is_null())
16753    {
16754        Some(value) => decode_wire_avro_value(value, codec)?,
16755        None => AvroValue::Array(Vec::new()),
16756    };
16757    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16758        unreachable!("normalize_avro_arguments always returns an array");
16759    };
16760    Ok(arguments)
16761}
16762
16763fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16764    let Some(export_events) = task
16765        .history_export
16766        .as_ref()
16767        .and_then(|export| export.get("history_events"))
16768        .and_then(Value::as_array)
16769    else {
16770        return Ok(());
16771    };
16772
16773    if export_events.len() > task.history_events.len() {
16774        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
16775    }
16776
16777    Ok(())
16778}
16779
16780fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16781    let Some(export) = task.history_export.as_ref() else {
16782        return Ok(());
16783    };
16784    let signals = export
16785        .get("signals")
16786        .and_then(Value::as_array)
16787        .cloned()
16788        .unwrap_or_default();
16789    let activities = export
16790        .get("activities")
16791        .and_then(Value::as_array)
16792        .cloned()
16793        .unwrap_or_default();
16794    let export_codec = export
16795        .get("payloads")
16796        .and_then(|payloads| payloads.get("codec"))
16797        .and_then(Value::as_str)
16798        .unwrap_or(&task.payload_codec)
16799        .to_string();
16800    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
16801
16802    for event in &mut task.history_events {
16803        if event.event_type == "ActivityCompleted" {
16804            let sequence = event
16805                .payload
16806                .get("sequence")
16807                .or_else(|| event.payload.get("workflow_sequence"))
16808                .and_then(value_as_u64);
16809            let Some(activity) = sequence.and_then(|sequence| {
16810                activities.iter().find(|activity| {
16811                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
16812                })
16813            }) else {
16814                continue;
16815            };
16816            let Some(payload) = event.payload.as_object_mut() else {
16817                continue;
16818            };
16819            if missing_payload(payload.get("result")) {
16820                if let Some(result) = activity
16821                    .get("result")
16822                    .filter(|value| !missing_payload(Some(value)))
16823                {
16824                    payload.insert("result".to_string(), result.clone());
16825                }
16826            }
16827            for field in ["payload_codec", "activity_type"] {
16828                if payload
16829                    .get(field)
16830                    .and_then(Value::as_str)
16831                    .unwrap_or_default()
16832                    .is_empty()
16833                {
16834                    if let Some(value) = activity.get(field) {
16835                        payload.insert(field.to_string(), value.clone());
16836                    }
16837                }
16838            }
16839            continue;
16840        }
16841
16842        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
16843            continue;
16844        }
16845        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
16846        let command_id = event
16847            .payload
16848            .get("workflow_command_id")
16849            .or_else(|| event.raw.get("workflow_command_id"))
16850            .and_then(Value::as_str);
16851        let signal_name = event
16852            .payload
16853            .get("signal_name")
16854            .and_then(Value::as_str)
16855            .unwrap_or_default()
16856            .to_string();
16857        let matched = signals
16858            .iter()
16859            .find(|signal| {
16860                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
16861            })
16862            .or_else(|| {
16863                signals.iter().find(|signal| {
16864                    command_id.is_some()
16865                        && signal.get("command_id").and_then(Value::as_str) == command_id
16866                })
16867            })
16868            .or_else(|| {
16869                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
16870                let signal = signals
16871                    .iter()
16872                    .filter(|signal| {
16873                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
16874                    })
16875                    .nth(*offset);
16876                if signal.is_some() {
16877                    *offset += 1;
16878                }
16879                signal
16880            });
16881        let Some(signal) = matched else {
16882            continue;
16883        };
16884        let signal_codec = signal
16885            .get("payload_codec")
16886            .and_then(Value::as_str)
16887            .unwrap_or(&export_codec);
16888        let Some(payload) = event.payload.as_object_mut() else {
16889            continue;
16890        };
16891        if missing_payload(payload.get("arguments")) {
16892            if let Some(arguments) = signal
16893                .get("arguments")
16894                .filter(|value| !missing_payload(Some(value)))
16895            {
16896                let envelope = match arguments {
16897                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
16898                    other => other.clone(),
16899                };
16900                payload.insert("arguments".to_string(), envelope);
16901            }
16902        }
16903        if payload
16904            .get("payload_codec")
16905            .and_then(Value::as_str)
16906            .unwrap_or_default()
16907            .is_empty()
16908        {
16909            payload.insert("payload_codec".to_string(), json!(signal_codec));
16910        }
16911    }
16912
16913    Ok(())
16914}
16915
16916fn missing_payload(value: Option<&Value>) -> bool {
16917    match value {
16918        None | Some(Value::Null) => true,
16919        Some(Value::String(value)) => value.is_empty(),
16920        Some(_) => false,
16921    }
16922}
16923
16924fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
16925    let export_signals = task
16926        .history_export
16927        .as_ref()
16928        .and_then(|export| export.get("signals"))
16929        .and_then(Value::as_array)
16930        .cloned()
16931        .unwrap_or_default();
16932    let export_codec = task
16933        .history_export
16934        .as_ref()
16935        .and_then(|export| export.get("payloads"))
16936        .and_then(|payloads| payloads.get("codec"))
16937        .and_then(Value::as_str)
16938        .unwrap_or(&task.payload_codec);
16939    let mut name_offsets: HashMap<String, usize> = HashMap::new();
16940    let mut signals = Vec::new();
16941
16942    for event in &task.history_events {
16943        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
16944            continue;
16945        }
16946
16947        let name = event
16948            .payload
16949            .get("signal_name")
16950            .and_then(Value::as_str)
16951            .unwrap_or_default();
16952        if name.is_empty() {
16953            continue;
16954        }
16955        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
16956        let command_id = event
16957            .payload
16958            .get("workflow_command_id")
16959            .or_else(|| event.raw.get("workflow_command_id"))
16960            .and_then(Value::as_str);
16961        let matched_export = export_signals
16962            .iter()
16963            .find(|candidate| {
16964                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
16965            })
16966            .or_else(|| {
16967                export_signals.iter().find(|candidate| {
16968                    command_id.is_some()
16969                        && candidate.get("command_id").and_then(Value::as_str) == command_id
16970                })
16971            })
16972            .or_else(|| {
16973                let offset = name_offsets.entry(name.to_string()).or_default();
16974                let candidate = export_signals
16975                    .iter()
16976                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
16977                    .nth(*offset);
16978                if candidate.is_some() {
16979                    *offset += 1;
16980                }
16981                candidate
16982            });
16983        let codec = event
16984            .payload
16985            .get("payload_codec")
16986            .and_then(Value::as_str)
16987            .or_else(|| {
16988                matched_export
16989                    .and_then(|signal| signal.get("payload_codec"))
16990                    .and_then(Value::as_str)
16991            })
16992            .unwrap_or(export_codec);
16993        let raw_arguments = signal_history_payload(&event.payload)
16994            .filter(|value| !value.is_null())
16995            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
16996        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
16997        let workflow_sequence = event
16998            .payload
16999            .get("workflow_sequence")
17000            .and_then(value_as_u64)
17001            .or_else(|| {
17002                matched_export
17003                    .and_then(|signal| signal.get("workflow_sequence"))
17004                    .and_then(value_as_u64)
17005            });
17006
17007        signals.push(QuerySignal {
17008            id: signal_id.map(str::to_string).or_else(|| {
17009                matched_export
17010                    .and_then(|signal| signal.get("id"))
17011                    .and_then(Value::as_str)
17012                    .map(str::to_string)
17013            }),
17014            name: name.to_string(),
17015            arguments,
17016            avro_arguments,
17017            workflow_sequence,
17018        });
17019    }
17020
17021    if signals.is_empty() {
17022        for signal in export_signals {
17023            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17024                continue;
17025            }
17026            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17027                continue;
17028            };
17029            let codec = signal
17030                .get("payload_codec")
17031                .and_then(Value::as_str)
17032                .unwrap_or(export_codec);
17033            let (arguments, avro_arguments) =
17034                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17035            signals.push(QuerySignal {
17036                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17037                name: name.to_string(),
17038                arguments,
17039                avro_arguments,
17040                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17041            });
17042        }
17043        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17044    }
17045
17046    Ok(signals)
17047}
17048
17049fn decode_query_signal_arguments(
17050    raw: Option<&Value>,
17051    codec: &str,
17052) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17053    validate_payload_codec(codec)?;
17054    let decoded = match raw.filter(|value| !value.is_null()) {
17055        Some(value) => decode_wire_avro_value(value, codec)?,
17056        None => AvroValue::Array(Vec::new()),
17057    };
17058    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17059        unreachable!("normalize_avro_arguments always returns an array");
17060    };
17061    let arguments = avro_arguments
17062        .iter()
17063        .cloned()
17064        .map(AvroValue::into_json)
17065        .collect::<Result<Vec<_>>>()?;
17066    Ok((arguments, avro_arguments))
17067}
17068
17069fn value_as_u64(value: &Value) -> Option<u64> {
17070    value
17071        .as_u64()
17072        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17073}
17074
17075#[cfg(test)]
17076mod tests {
17077    use super::*;
17078    mod activity_cancellation_policies;
17079    mod cancellation_scope_admission;
17080    mod cancellation_scope_authoring;
17081    mod cancellation_scope_history;
17082    mod cancellation_scope_opening;
17083    mod cancellation_scope_replay;
17084    mod child_workflow_policies;
17085    mod cooperative_cancellation;
17086    mod local_activity;
17087    mod runtime_payloads;
17088    mod runtime_uploads;
17089    mod worker_session;
17090    use std::{
17091        fs,
17092        io::{Read, Write},
17093        net::{SocketAddr, TcpListener, TcpStream},
17094        process::Command as ProcessCommand,
17095        sync::atomic::AtomicUsize,
17096        thread,
17097    };
17098
17099    #[derive(Clone, Copy, Debug)]
17100    enum InvalidTaskPayloadCodec {
17101        Missing,
17102        Null,
17103        NonString,
17104    }
17105
17106    impl InvalidTaskPayloadCodec {
17107        fn label(self) -> &'static str {
17108            match self {
17109                Self::Missing => "missing",
17110                Self::Null => "null",
17111                Self::NonString => "non-string",
17112            }
17113        }
17114
17115        fn apply(self, task: &mut Value) {
17116            let task = task.as_object_mut().expect("task fixture object");
17117            match self {
17118                Self::Missing => {
17119                    task.remove("payload_codec");
17120                }
17121                Self::Null => {
17122                    task.insert("payload_codec".to_string(), Value::Null);
17123                }
17124                Self::NonString => {
17125                    task.insert("payload_codec".to_string(), json!(42));
17126                }
17127            }
17128        }
17129    }
17130
17131    fn fixture_envelope(value: Value) -> Value {
17132        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
17133    }
17134
17135    fn fixture_blob(value: Value) -> String {
17136        encode_payload(&value, DEFAULT_CODEC)
17137            .expect("encode Avro test fixture")
17138            .blob
17139    }
17140
17141    #[test]
17142    fn client_builder_rejects_the_sdk_owned_api_suffix() {
17143        for base_url in [
17144            "http://127.0.0.1:8080/api",
17145            "http://localhost:8080/api/",
17146            "https://runtime.example.test/namespaces/orders/api",
17147        ] {
17148            let error = Client::builder(base_url)
17149                .build()
17150                .expect_err("SDK-owned /api suffix must be rejected during build");
17151
17152            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
17153            assert!(
17154                error.to_string().contains("SDK appends /api automatically"),
17155                "the validation error must explain how to fix the endpoint"
17156            );
17157        }
17158    }
17159
17160    #[test]
17161    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
17162        for (base_url, expected) in [
17163            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
17164            (
17165                "http://localhost:8080/durable-workflow/",
17166                "http://localhost:8080/durable-workflow",
17167            ),
17168            (
17169                "https://runtime.example.test/namespaces/orders",
17170                "https://runtime.example.test/namespaces/orders",
17171            ),
17172            (
17173                "https://runtime.example.test/gateway/api/namespaces/orders",
17174                "https://runtime.example.test/gateway/api/namespaces/orders",
17175            ),
17176            (
17177                "https://api.example.test/runtime/orders/",
17178                "https://api.example.test/runtime/orders",
17179            ),
17180        ] {
17181            let client = Client::builder(base_url)
17182                .build()
17183                .expect("Server and Cloud runtime base URL must remain valid");
17184
17185            assert_eq!(client.base_url, expected);
17186        }
17187    }
17188
17189    #[test]
17190    fn workflow_completion_uses_the_additive_command_protocol_floor() {
17191        assert_eq!(
17192            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
17193            WORKER_PROTOCOL_VERSION
17194        );
17195        assert_eq!(
17196            workflow_completion_protocol_version(&[json!({
17197                "type": "upsert_search_attributes",
17198                "attributes": {"OrderStatus": "waiting"},
17199            })]),
17200            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
17201        );
17202        assert_eq!(
17203            workflow_completion_protocol_version(&[json!({
17204                "type": "upsert_search_attributes",
17205                "attributes": {"OrderStatus": "waiting"},
17206                "attribute_types": {"OrderStatus": "keyword"},
17207            })]),
17208            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
17209        );
17210        assert_eq!(
17211            workflow_completion_protocol_version(&[
17212                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
17213                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17214            ]),
17215            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
17216        );
17217        assert_eq!(
17218            workflow_completion_protocol_version(&[
17219                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
17220                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17221            ]),
17222            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
17223        );
17224        assert_eq!(
17225            workflow_completion_protocol_version(&[json!({
17226                "type": "open_condition_wait",
17227                "condition_wait_occurrence_id": "rust:condition-wait:0",
17228                "condition_key": "ready",
17229            })]),
17230            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17231        );
17232        assert_eq!(
17233            workflow_completion_protocol_version_with_message_streams(
17234                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
17235                true,
17236            ),
17237            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
17238        );
17239        assert_eq!(
17240            workflow_completion_protocol_version_with_message_streams(
17241                &[json!({
17242                    "type": "open_condition_wait",
17243                    "condition_wait_occurrence_id": "rust:condition-wait:0",
17244                    "condition_key": "ready",
17245                })],
17246                true,
17247            ),
17248            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17249        );
17250    }
17251
17252    #[test]
17253    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
17254        let manifest = portable_worker_affinity_capability_manifest();
17255
17256        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
17257            assert_eq!(manifest[capability]["supported"], json!(false));
17258            assert_eq!(
17259                manifest[capability]["minimum_protocol_version"],
17260                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
17261            );
17262            assert!(manifest[capability]["reason"]
17263                .as_str()
17264                .is_some_and(|reason| !reason.is_empty()));
17265        }
17266    }
17267
17268    fn typed_fidelity_probe() -> AvroValue {
17269        AvroValue::Map(BTreeMap::from([
17270            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
17271            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
17272            (
17273                "numeric".to_string(),
17274                AvroValue::Map(BTreeMap::from([
17275                    ("0".to_string(), AvroValue::String("zero".to_string())),
17276                    ("1".to_string(), AvroValue::String("one".to_string())),
17277                ])),
17278            ),
17279            (
17280                "nested".to_string(),
17281                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
17282                    "enabled".to_string(),
17283                    AvroValue::Boolean(true),
17284                )]))]),
17285            ),
17286            (
17287                "projection_collisions".to_string(),
17288                AvroValue::Array(projection_collision_probe()),
17289            ),
17290        ]))
17291    }
17292
17293    fn projection_collision_probe() -> Vec<AvroValue> {
17294        vec![
17295            AvroValue::Map(BTreeMap::from([
17296                ("$type".to_string(), AvroValue::String("bytes".to_string())),
17297                (
17298                    "base64".to_string(),
17299                    AvroValue::String("ordinary user text".to_string()),
17300                ),
17301            ])),
17302            AvroValue::Map(BTreeMap::from([
17303                ("$type".to_string(), AvroValue::String("map".to_string())),
17304                (
17305                    "entries".to_string(),
17306                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
17307                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
17308                        (
17309                            "value".to_string(),
17310                            AvroValue::String("user map".to_string()),
17311                        ),
17312                    ]))]),
17313                ),
17314            ])),
17315        ]
17316    }
17317
17318    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17319    struct TypedContract {
17320        nested: TypedNested,
17321        mode: TypedMode,
17322        optional: Option<String>,
17323        absent: Option<String>,
17324        items: Vec<i64>,
17325        labels: BTreeMap<String, String>,
17326        bytes: serde_bytes::ByteBuf,
17327        signed: i64,
17328        finite: f64,
17329    }
17330
17331    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17332    struct TypedNested {
17333        enabled: bool,
17334    }
17335
17336    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17337    enum TypedMode {
17338        Detailed { label: String },
17339    }
17340
17341    fn typed_contract() -> TypedContract {
17342        TypedContract {
17343            nested: TypedNested { enabled: true },
17344            mode: TypedMode::Detailed {
17345                label: "compiler-checked".to_string(),
17346            },
17347            optional: Some("present".to_string()),
17348            absent: None,
17349            items: vec![i64::MIN, 0, i64::MAX],
17350            labels: BTreeMap::from([
17351                ("language".to_string(), "rust".to_string()),
17352                ("wire".to_string(), "avro".to_string()),
17353            ]),
17354            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
17355            signed: -9_223_372_036_854_775_000,
17356            finite: 12.5,
17357        }
17358    }
17359
17360    #[derive(Clone, Debug, Default, PartialEq)]
17361    struct ReplayCounterState {
17362        loaded: Option<String>,
17363        count: i64,
17364        finished: bool,
17365    }
17366
17367    fn replay_counter_worker() -> Worker {
17368        let client = Client::new("http://127.0.0.1:8080").expect("client");
17369        let mut worker = Worker::new(client, "rust-workers");
17370        worker.register_replayed_workflow(
17371            "replay-counter",
17372            ReplayCounterState::default,
17373            |ctx, _input, state| async move {
17374                let loaded = ctx.activity("load-counter", json!([])).await?;
17375                state.update(|current| {
17376                    current.loaded = loaded.as_str().map(str::to_string);
17377                })?;
17378                for _ in 0..2 {
17379                    let signal = ctx.wait_signal("increment").await?;
17380                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
17381                    state.update(|current| current.count += amount)?;
17382                }
17383                state.update(|current| current.finished = true)?;
17384                state.read(|current| Ok(json!(current.count)))?
17385            },
17386        );
17387        worker.register_replayed_query::<ReplayCounterState, _, _>(
17388            "replay-counter",
17389            "current",
17390            |_ctx, state, _args| async move {
17391                Ok(json!({
17392                    "loaded": state.loaded,
17393                    "count": state.count,
17394                    "finished": state.finished,
17395                }))
17396            },
17397        );
17398        worker.register_replayed_query::<ReplayCounterState, _, _>(
17399            "replay-counter",
17400            "detached-mutation",
17401            |_ctx, state, _args| async move {
17402                let mut detached = (*state).clone();
17403                detached.count = 999;
17404                Ok(json!(detached.count))
17405            },
17406        );
17407        worker.register_replayed_query::<ReplayCounterState, _, _>(
17408            "replay-counter",
17409            "failed-mutation",
17410            |_ctx, state, _args| async move {
17411                let mut detached = (*state).clone();
17412                detached.count = 999;
17413                Err(Error::WorkerLoop("query refused".to_string()))
17414            },
17415        );
17416        worker
17417    }
17418
17419    fn replay_counter_query(
17420        query_name: &str,
17421        history_events: Value,
17422        run_status: &str,
17423    ) -> QueryTask {
17424        let arguments = fixture_envelope(json!([]));
17425        serde_json::from_value(json!({
17426            "query_task_id": format!("query-{query_name}"),
17427            "workflow_type": "replay-counter",
17428            "query_name": query_name,
17429            "payload_codec": DEFAULT_CODEC,
17430            "workflow_arguments": arguments.clone(),
17431            "query_arguments": arguments,
17432            "history_events": history_events,
17433            "run_status": run_status,
17434        }))
17435        .expect("query task")
17436    }
17437
17438    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
17439        workflow_context_with_codec(history, DEFAULT_CODEC)
17440    }
17441
17442    fn workflow_context_with_codec(
17443        history: Vec<HistoryEvent>,
17444        payload_codec: &str,
17445    ) -> WorkflowContext {
17446        WorkflowContext {
17447            cancellation_scope_id: "root".into(),
17448            state: Arc::new(Mutex::new(
17449                WorkflowState::new_with_identity(
17450                    history,
17451                    None,
17452                    None,
17453                    "rust-workers".to_string(),
17454                    payload_codec.to_string(),
17455                    None,
17456                )
17457                .expect("valid workflow history"),
17458            )),
17459        }
17460    }
17461
17462    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
17463        HistoryEvent {
17464            event_type: event_type.to_string(),
17465            payload,
17466            raw: HashMap::new(),
17467        }
17468    }
17469
17470    fn parallel_path_entry(
17471        kind: &str,
17472        base: u64,
17473        size: usize,
17474        index: usize,
17475    ) -> ParallelGroupMetadata {
17476        parallel_group_entry(base, size, index, kind)
17477    }
17478
17479    fn parallel_history_event(
17480        event_type: &str,
17481        sequence: u64,
17482        identity_field: &str,
17483        identity: &str,
17484        path: Vec<ParallelGroupMetadata>,
17485        result: Option<Value>,
17486    ) -> HistoryEvent {
17487        let mut payload = serde_json::Map::from_iter([
17488            ("sequence".to_string(), json!(sequence)),
17489            (identity_field.to_string(), json!(identity)),
17490        ]);
17491        let inner = path.last().expect("parallel history path");
17492        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
17493        payload.insert("parallel_group_path".to_string(), json!(path));
17494        if let Some(result) = result {
17495            let field = if event_type == "ChildRunCompleted" {
17496                "result"
17497            } else {
17498                "result"
17499            };
17500            payload.insert(field.to_string(), fixture_envelope(result));
17501            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
17502        }
17503        history_event(event_type, Value::Object(payload))
17504    }
17505
17506    fn nested_parallel_operations() -> Vec<ParallelOperation> {
17507        vec![
17508            ParallelOperation::activity("first", json!([])),
17509            ParallelOperation::group(vec![
17510                ParallelOperation::child_workflow(
17511                    "second",
17512                    ChildWorkflowOptions::new("child-workers"),
17513                    json!([]),
17514                ),
17515                ParallelOperation::activity("third", json!([])),
17516            ]),
17517        ]
17518    }
17519
17520    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
17521        let outer = [
17522            parallel_path_entry("mixed", 1, 3, 0),
17523            parallel_path_entry("mixed", 1, 3, 1),
17524            parallel_path_entry("mixed", 1, 3, 2),
17525        ];
17526        [
17527            vec![outer[0].clone()],
17528            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
17529            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
17530        ]
17531    }
17532
17533    #[test]
17534    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
17535        let ctx = workflow_context(Vec::new());
17536        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17537        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17538
17539        assert!(matches!(
17540            call.as_mut().poll(&mut task_context),
17541            Poll::Pending
17542        ));
17543        let commands = ctx.take_commands().expect("parallel commands");
17544        assert_eq!(
17545            commands
17546                .iter()
17547                .map(|command| command["type"].as_str().unwrap_or_default())
17548                .collect::<Vec<_>>(),
17549            [
17550                "schedule_activity",
17551                "start_child_workflow",
17552                "schedule_activity"
17553            ]
17554        );
17555        let paths = nested_parallel_paths();
17556        for (command, path) in commands.iter().zip(paths) {
17557            assert_eq!(command["parallel_group_path"], json!(path));
17558            assert_eq!(
17559                command["parallel_group_id"],
17560                json!(path.last().expect("inner group").parallel_group_id)
17561            );
17562        }
17563    }
17564
17565    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
17566        let paths = nested_parallel_paths();
17567        let third = parallel_history_event(
17568            "ActivityCompleted",
17569            3,
17570            "activity_type",
17571            "third",
17572            paths[2].clone(),
17573            Some(json!("three")),
17574        );
17575        vec![
17576            parallel_history_event(
17577                "ActivityCompleted",
17578                1,
17579                "activity_type",
17580                "first",
17581                paths[0].clone(),
17582                Some(json!("one")),
17583            ),
17584            parallel_history_event(
17585                "ChildWorkflowScheduled",
17586                2,
17587                "child_workflow_type",
17588                "second",
17589                paths[1].clone(),
17590                None,
17591            ),
17592            parallel_history_event(
17593                "ChildRunCompleted",
17594                2,
17595                "child_workflow_type",
17596                "second",
17597                paths[1].clone(),
17598                Some(json!("two")),
17599            ),
17600            third.clone(),
17601            third,
17602        ]
17603    }
17604
17605    #[test]
17606    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
17607        for _restart_or_completed_replay in 0..2 {
17608            let ctx = workflow_context(completed_nested_parallel_history());
17609            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17610            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17611            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
17612                panic!("completed nested parallel history must replay");
17613            };
17614            assert_eq!(
17615                results,
17616                vec![
17617                    ParallelResult::Activity(json!("one")),
17618                    ParallelResult::Group(vec![
17619                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
17620                            parent: WorkflowIdentity {
17621                                workflow_id: None,
17622                                run_id: None,
17623                            },
17624                            child: WorkflowIdentity {
17625                                workflow_id: None,
17626                                run_id: None,
17627                            },
17628                            child_workflow_type: Some("second".to_string()),
17629                            result: json!("two"),
17630                        }),
17631                        ParallelResult::Activity(json!("three")),
17632                    ]),
17633                ]
17634            );
17635            assert!(ctx.take_commands().expect("commands").is_empty());
17636            ctx.ensure_history_consumed().expect("history consumed");
17637        }
17638    }
17639
17640    #[test]
17641    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
17642        let paths = nested_parallel_paths();
17643        let history = vec![
17644            parallel_history_event(
17645                "ActivityCompleted",
17646                1,
17647                "activity_type",
17648                "first",
17649                paths[0].clone(),
17650                Some(json!("one")),
17651            ),
17652            parallel_history_event(
17653                "ChildWorkflowScheduled",
17654                2,
17655                "child_workflow_type",
17656                "second",
17657                paths[1].clone(),
17658                None,
17659            ),
17660            parallel_history_event(
17661                "ChildRunFailed",
17662                2,
17663                "child_workflow_type",
17664                "second",
17665                paths[1].clone(),
17666                None,
17667            ),
17668            parallel_history_event(
17669                "ActivityCompleted",
17670                3,
17671                "activity_type",
17672                "third",
17673                paths[2].clone(),
17674                Some(json!("late")),
17675            ),
17676        ];
17677        let ctx = workflow_context(history);
17678        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17679        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17680        let outcome = call.as_mut().poll(&mut task_context);
17681        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
17682            panic!("one failed child must return a typed partial failure: {outcome:?}");
17683        };
17684        assert_eq!(failure.member_path, [1, 0]);
17685        assert_eq!(failure.group_id, "parallel-calls:1:3");
17686        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
17687        assert_eq!(
17688            failure
17689                .completed
17690                .iter()
17691                .map(|completion| completion.member_path.clone())
17692                .collect::<Vec<_>>(),
17693            [vec![0], vec![1, 1]]
17694        );
17695    }
17696
17697    #[test]
17698    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
17699        let paths = nested_parallel_paths();
17700        let history = vec![
17701            parallel_history_event(
17702                "ActivityScheduled",
17703                1,
17704                "activity_type",
17705                "first",
17706                paths[0].clone(),
17707                None,
17708            ),
17709            parallel_history_event(
17710                "ChildWorkflowScheduled",
17711                2,
17712                "child_workflow_type",
17713                "second",
17714                paths[1].clone(),
17715                None,
17716            ),
17717            parallel_history_event(
17718                "ActivityScheduled",
17719                3,
17720                "activity_type",
17721                "third",
17722                paths[2].clone(),
17723                None,
17724            ),
17725        ];
17726        for _restart in 0..2 {
17727            let ctx = workflow_context(history.clone());
17728            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17729            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17730            let outcome = call.as_mut().poll(&mut task_context);
17731            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
17732            assert!(ctx.take_commands().expect("commands").is_empty());
17733        }
17734    }
17735
17736    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
17737        vec![selection_group_entry(
17738            1,
17739            2,
17740            index,
17741            "activity",
17742            &SelectionMemberMetadata {
17743                key: SelectionKey::Name(key.to_string()),
17744                index,
17745                base_sequence: index as u64 + 1,
17746                size: 1,
17747                kind: "activity".to_string(),
17748            },
17749        )]
17750    }
17751
17752    fn selection_activity_event(
17753        event_type: &str,
17754        index: usize,
17755        key: &str,
17756        result: Option<Value>,
17757    ) -> HistoryEvent {
17758        let sequence = index as u64 + 1;
17759        let mut event = parallel_history_event(
17760            event_type,
17761            sequence,
17762            "activity_type",
17763            &format!("{key}-activity"),
17764            selection_path(index, key),
17765            result,
17766        );
17767        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
17768        event.raw.insert(
17769            "id".to_string(),
17770            json!(if event_type == "ActivityCompleted" {
17771                format!("event-{key}")
17772            } else {
17773                format!("{event_type}-{key}")
17774            }),
17775        );
17776        event
17777    }
17778
17779    fn selection_winner_marker() -> HistoryEvent {
17780        history_event(
17781            "SelectionResolved",
17782            json!({
17783                "selection_group_id": "select-calls:1:2",
17784                "selection_group_base_sequence": 1,
17785                "selection_group_size": 2,
17786                "member_key": "fast",
17787                "member_index": 1,
17788                "member_base_sequence": 2,
17789                "member_size": 1,
17790                "operation_kind": "activity",
17791                "operation_identity": "activity-fast",
17792                "outcome": "completed",
17793                "resolution_event_id": "event-fast",
17794                "resolution_event_type": "ActivityCompleted",
17795            }),
17796        )
17797    }
17798
17799    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
17800        ctx.select_keyed(vec![
17801            (
17802                "slow",
17803                ParallelOperation::activity_with_options(
17804                    "slow-activity",
17805                    ActivityOptions::new().task_queue("default"),
17806                    json!([]),
17807                ),
17808            ),
17809            (
17810                "fast",
17811                ParallelOperation::activity_with_options(
17812                    "fast-activity",
17813                    ActivityOptions::new().task_queue("default"),
17814                    json!([]),
17815                ),
17816            ),
17817        ])
17818    }
17819
17820    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
17821        let ctx = workflow_context(history);
17822        let mut call = Box::pin(keyed_activity_selection(&ctx));
17823        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17824        let selected = match call.as_mut().poll(&mut task_context) {
17825            Poll::Ready(Ok(selected)) => selected,
17826            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
17827            Poll::Pending => panic!("persisted selection winner must replay without pending"),
17828        };
17829        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
17830        assert_eq!(
17831            selected.value,
17832            Some(ParallelResult::Activity(json!("winner-value")))
17833        );
17834        let slow = selected
17835            .handle(&SelectionKey::Name("slow".to_string()))
17836            .expect("slow handle")
17837            .clone();
17838        let mut await_slow = Box::pin(slow.await_result());
17839        assert!(matches!(
17840            await_slow.as_mut().poll(&mut task_context),
17841            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
17842        ));
17843        assert!(ctx.take_commands().expect("commands").is_empty());
17844    }
17845
17846    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
17847
17848    fn canonical_selection_history() -> Vec<HistoryEvent> {
17849        const FIXTURE: &[u8] =
17850            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
17851        assert_eq!(
17852            format!("{:x}", Sha256::digest(FIXTURE)),
17853            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
17854        );
17855        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
17856
17857        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
17858    }
17859
17860    #[test]
17861    fn selection_fresh_process_entrypoint() {
17862        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
17863            return;
17864        };
17865        let persisted = fs::read(path).expect("persisted selection history");
17866        assert_eq!(
17867            format!("{:x}", Sha256::digest(&persisted)),
17868            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
17869        );
17870        let fixture: Value =
17871            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
17872        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
17873            .expect("valid persisted selection history");
17874
17875        assert_persisted_selection_replay(history);
17876    }
17877
17878    #[test]
17879    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
17880        let ctx = workflow_context(Vec::new());
17881        let mut call = Box::pin(keyed_activity_selection(&ctx));
17882        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17883
17884        assert!(matches!(
17885            call.as_mut().poll(&mut task_context),
17886            Poll::Pending
17887        ));
17888        let commands = ctx.take_commands().expect("selection commands");
17889        assert_eq!(commands.len(), 2);
17890        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
17891        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
17892        assert!(commands.iter().all(|command| {
17893            command["parallel_group_id"] == json!("select-calls:1:2")
17894                && command["parallel_group_mode"] == json!("select")
17895        }));
17896    }
17897
17898    #[test]
17899    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
17900        let ctx = workflow_context(Vec::new());
17901        let mut invalid = Box::pin(ctx.select_keyed(vec![(
17902            "",
17903            ParallelOperation::activity("invalid", json!([])),
17904        )]));
17905        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17906        assert!(matches!(
17907            invalid.as_mut().poll(&mut task_context),
17908            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
17909                reason: "selection_key_invalid",
17910                ..
17911            })))
17912        ));
17913
17914        for invalid_key in [json!(""), json!(-1)] {
17915            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
17916            event.payload["selection_member_key"] = invalid_key.clone();
17917            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
17918            assert!(matches!(
17919                WorkflowState::new_with_identity(
17920                    vec![event],
17921                    None,
17922                    None,
17923                    "rust-workers".to_string(),
17924                    DEFAULT_CODEC.to_string(),
17925                    None,
17926                ),
17927                Err(Error::NonDeterministicReplay(_))
17928            ));
17929        }
17930    }
17931
17932    #[test]
17933    fn selection_preserves_valid_named_and_numeric_keys() {
17934        let ctx = workflow_context(Vec::new());
17935        let mut selection = Box::pin(ctx.select_keyed(vec![
17936            (
17937                SelectionKey::Index(0),
17938                ParallelOperation::activity("numeric", json!([])),
17939            ),
17940            (
17941                SelectionKey::Name("named".to_string()),
17942                ParallelOperation::timer(Duration::from_secs(1)),
17943            ),
17944        ]));
17945        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17946
17947        assert!(matches!(
17948            selection.as_mut().poll(&mut task_context),
17949            Poll::Pending
17950        ));
17951        let commands = ctx.take_commands().expect("selection commands");
17952        assert_eq!(commands[0]["selection_member_key"], json!(0));
17953        assert_eq!(commands[1]["selection_member_key"], json!("named"));
17954    }
17955
17956    #[test]
17957    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
17958        let history = canonical_selection_history();
17959        assert_persisted_selection_replay(history.clone());
17960
17961        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
17962            .join("tests/fixtures/durable_selection_runtime_history.json");
17963        let output =
17964            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
17965                .args([
17966                    "--exact",
17967                    "tests::selection_fresh_process_entrypoint",
17968                    "--nocapture",
17969                ])
17970                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
17971                .output()
17972                .expect("run fresh selection replay process");
17973
17974        assert!(
17975            output.status.success(),
17976            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
17977            String::from_utf8_lossy(&output.stdout),
17978            String::from_utf8_lossy(&output.stderr),
17979        );
17980    }
17981
17982    #[test]
17983    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
17984        let mut history = canonical_selection_history();
17985        history.retain(|event| event.event_type != "SelectionResolved");
17986        let ctx = workflow_context(history);
17987        let mut selection = Box::pin(keyed_activity_selection(&ctx));
17988        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17989
17990        assert!(matches!(
17991            selection.as_mut().poll(&mut task_context),
17992            Poll::Pending
17993        ));
17994        assert!(ctx.take_commands().expect("commands").is_empty());
17995        assert!(
17996            ctx.matched_recorded_pending()
17997                .expect("selection pending state"),
17998            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
17999        );
18000    }
18001
18002    #[test]
18003    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18004        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18005            ("ConditionWaitSatisfied", true, None),
18006            ("ConditionWaitTimedOut", false, Some(0)),
18007        ] {
18008            let member = SelectionMemberMetadata {
18009                key: SelectionKey::Name("condition".to_string()),
18010                index: 0,
18011                base_sequence: 1,
18012                size: 1,
18013                kind: "condition".to_string(),
18014            };
18015            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18016            let mut payload = json!({
18017                "sequence": 1,
18018                "condition_wait_id": "condition-1",
18019                "condition_wait_occurrence_id": "rust:condition-wait:0",
18020                "condition_key": "ready",
18021                "condition_definition_fingerprint": "sha256:ready-v1",
18022                "parallel_group_path": path,
18023            });
18024            payload
18025                .as_object_mut()
18026                .expect("condition history payload")
18027                .extend(
18028                    serde_json::to_value(&path[0])
18029                        .expect("condition selection metadata")
18030                        .as_object()
18031                        .expect("condition selection metadata object")
18032                        .clone(),
18033                );
18034            if let Some(timeout_seconds) = timeout_seconds {
18035                payload["timeout_seconds"] = json!(timeout_seconds);
18036            }
18037            let history = vec![
18038                history_event("ConditionWaitOpened", payload.clone()),
18039                history_event(terminal_event, payload),
18040            ];
18041            let ctx = workflow_context(history);
18042            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18043            if timeout_seconds.is_some() {
18044                options = options.timeout(Duration::ZERO);
18045            }
18046            let mut selection = Box::pin(ctx.select_keyed(vec![(
18047                "condition",
18048                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18049            )]));
18050            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18051
18052            assert!(matches!(
18053                selection.as_mut().poll(&mut task_context),
18054                Poll::Pending
18055            ));
18056            assert!(ctx.take_commands().expect("commands").is_empty());
18057            assert!(
18058                ctx.matched_recorded_pending()
18059                    .expect("condition selection pending state"),
18060                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18061            );
18062        }
18063    }
18064
18065    #[test]
18066    fn selection_immediate_condition_members_open_a_durable_wait() {
18067        for predicate_satisfied in [true, false] {
18068            let ctx = workflow_context(Vec::new());
18069            let mut selection = Box::pin(ctx.select_keyed(vec![(
18070                "condition",
18071                ParallelOperation::condition(
18072                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18073                    move || Ok(predicate_satisfied),
18074                ),
18075            )]));
18076            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18077
18078            assert!(matches!(
18079                selection.as_mut().poll(&mut task_context),
18080                Poll::Pending
18081            ));
18082            let commands = ctx.take_commands().expect("condition selection command");
18083            assert_eq!(commands.len(), 1);
18084            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18085            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18086            assert_eq!(
18087                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18088                json!("select")
18089            );
18090        }
18091    }
18092
18093    #[test]
18094    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18095        let history = vec![
18096            selection_activity_event("ActivityScheduled", 0, "slow", None),
18097            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18098            selection_winner_marker(),
18099        ];
18100        let ctx = workflow_context(history.clone());
18101        let mut call = Box::pin(keyed_activity_selection(&ctx));
18102        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18103        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18104            panic!("winner must replay");
18105        };
18106        let slow = selected
18107            .handle(&SelectionKey::Name("slow".to_string()))
18108            .expect("slow handle")
18109            .clone();
18110        let mut cancel = Box::pin(slow.cancel());
18111        assert!(matches!(
18112            cancel.as_mut().poll(&mut task_context),
18113            Poll::Pending
18114        ));
18115        assert!(matches!(
18116            cancel.as_mut().poll(&mut task_context),
18117            Poll::Pending
18118        ));
18119        let commands = ctx.take_commands().expect("cancel command");
18120        assert_eq!(commands.len(), 1);
18121        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18122        assert_eq!(commands[0]["member_key"], json!("slow"));
18123
18124        let mut cancelled_history = history;
18125        cancelled_history.push(history_event(
18126            "SelectionOperationCancelled",
18127            json!({
18128                "selection_group_id": "select-calls:1:2",
18129                "member_key": "slow",
18130                "member_index": 0,
18131                "member_base_sequence": 1,
18132                "member_size": 1,
18133                "operation_kind": "activity",
18134                "operation_identity": "activity-slow",
18135                "cancelled_at": "2026-08-27T00:00:00Z",
18136            }),
18137        ));
18138        let replayed = workflow_context(cancelled_history);
18139        let mut call = Box::pin(keyed_activity_selection(&replayed));
18140        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18141            panic!("winner must replay after cancellation");
18142        };
18143        let slow = selected
18144            .handle(&SelectionKey::Name("slow".to_string()))
18145            .expect("slow handle")
18146            .clone();
18147        let mut cancel = Box::pin(slow.cancel());
18148        assert!(matches!(
18149            cancel.as_mut().poll(&mut task_context),
18150            Poll::Ready(Ok(()))
18151        ));
18152        assert!(replayed.take_commands().expect("commands").is_empty());
18153    }
18154
18155    #[test]
18156    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
18157        let base_history = vec![
18158            selection_activity_event("ActivityScheduled", 0, "slow", None),
18159            selection_activity_event("ActivityScheduled", 1, "fast", None),
18160            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18161            selection_winner_marker(),
18162        ];
18163        for (field, corrupt) in [
18164            ("member_key", json!("fast")),
18165            ("member_index", json!(1)),
18166            ("member_base_sequence", json!(3)),
18167            ("member_size", json!(2)),
18168            ("operation_kind", json!("timer")),
18169            ("operation_identity", json!("forged")),
18170        ] {
18171            let mut cancellation = json!({
18172                "selection_group_id": "select-calls:1:2",
18173                "member_key": "slow",
18174                "member_index": 0,
18175                "member_base_sequence": 1,
18176                "member_size": 1,
18177                "operation_kind": "activity",
18178                "operation_identity": "activity-slow",
18179            });
18180            cancellation[field] = corrupt;
18181            let mut history = base_history.clone();
18182            history.push(history_event("SelectionOperationCancelled", cancellation));
18183            let ctx = workflow_context(history);
18184            let mut selection = Box::pin(keyed_activity_selection(&ctx));
18185            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18186
18187            assert!(matches!(
18188                selection.as_mut().poll(&mut task_context),
18189                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18190            ));
18191        }
18192    }
18193
18194    #[test]
18195    fn selection_child_identity_prefers_the_durable_run_id() {
18196        let ctx = workflow_context(vec![history_event(
18197            "ChildWorkflowScheduled",
18198            json!({
18199                "sequence": 1,
18200                "child_workflow_type": "child",
18201                "child_workflow_instance_id": "child-instance",
18202                "child_workflow_run_id": "child-run",
18203            }),
18204        )]);
18205        let state = ctx.state.lock().expect("workflow state");
18206
18207        assert_eq!(
18208            selection_operation_identity(&state, "child", 1, 1),
18209            "child-run"
18210        );
18211    }
18212
18213    #[test]
18214    fn selection_activity_identity_requires_canonical_execution_id() {
18215        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
18216        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
18217        let mut fast_completed =
18218            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
18219        for event in [&mut fast_open, &mut fast_completed] {
18220            event
18221                .payload
18222                .as_object_mut()
18223                .expect("activity payload")
18224                .remove("activity_execution_id");
18225            event.payload["activity_id"] = json!("forged-activity-id");
18226        }
18227        let mut marker = selection_winner_marker();
18228        marker.payload["operation_identity"] = json!("forged-activity-id");
18229        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
18230        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18231        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18232
18233        assert!(matches!(
18234            selection.as_mut().poll(&mut task_context),
18235            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18236        ));
18237    }
18238
18239    #[test]
18240    fn selection_completion_before_cancellation_remains_awaitable() {
18241        let history = vec![
18242            selection_activity_event("ActivityScheduled", 0, "slow", None),
18243            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18244            selection_winner_marker(),
18245            selection_activity_event(
18246                "ActivityCompleted",
18247                0,
18248                "slow",
18249                Some(json!("completed-first")),
18250            ),
18251        ];
18252        let ctx = workflow_context(history);
18253        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18254        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18255        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18256            panic!("winner must replay");
18257        };
18258        let slow = selected
18259            .handle(&SelectionKey::Name("slow".to_string()))
18260            .expect("slow handle")
18261            .clone();
18262        let mut cancel = Box::pin(slow.cancel());
18263        assert!(matches!(
18264            cancel.as_mut().poll(&mut task_context),
18265            Poll::Ready(Ok(()))
18266        ));
18267        let mut await_slow = Box::pin(slow.await_result());
18268        assert!(matches!(
18269            await_slow.as_mut().poll(&mut task_context),
18270            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
18271        ));
18272        let commands = ctx.take_commands().expect("commands");
18273        assert!(commands.is_empty());
18274    }
18275
18276    #[test]
18277    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
18278        let nested_member = SelectionMemberMetadata {
18279            key: SelectionKey::Name("nested".to_string()),
18280            index: 0,
18281            base_sequence: 1,
18282            size: 2,
18283            kind: "group".to_string(),
18284        };
18285        let deadline_member = SelectionMemberMetadata {
18286            key: SelectionKey::Name("deadline".to_string()),
18287            index: 1,
18288            base_sequence: 3,
18289            size: 1,
18290            kind: "timer".to_string(),
18291        };
18292        let nested_paths = [
18293            vec![
18294                selection_group_entry(1, 3, 0, "mixed", &nested_member),
18295                parallel_group_entry(1, 2, 0, "activity"),
18296            ],
18297            vec![
18298                selection_group_entry(1, 3, 1, "mixed", &nested_member),
18299                parallel_group_entry(1, 2, 1, "activity"),
18300            ],
18301        ];
18302        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
18303        let mut timer_fired = parallel_history_event(
18304            "TimerFired",
18305            3,
18306            "timer_id",
18307            "timer-3",
18308            deadline_path.clone(),
18309            None,
18310        );
18311        timer_fired.payload["delay_seconds"] = json!(0);
18312        timer_fired
18313            .raw
18314            .insert("id".to_string(), json!("timer-fired"));
18315        let mut timer_scheduled = parallel_history_event(
18316            "TimerScheduled",
18317            3,
18318            "timer_id",
18319            "timer-3",
18320            deadline_path,
18321            None,
18322        );
18323        timer_scheduled.payload["delay_seconds"] = json!(0);
18324        let history = vec![
18325            parallel_history_event(
18326                "ActivityScheduled",
18327                1,
18328                "activity_type",
18329                "nested-first",
18330                nested_paths[0].clone(),
18331                None,
18332            ),
18333            parallel_history_event(
18334                "ActivityScheduled",
18335                2,
18336                "activity_type",
18337                "nested-second",
18338                nested_paths[1].clone(),
18339                None,
18340            ),
18341            timer_scheduled,
18342            timer_fired,
18343            history_event(
18344                "SelectionResolved",
18345                json!({
18346                    "selection_group_id": "select-calls:1:3",
18347                    "selection_group_base_sequence": 1,
18348                    "selection_group_size": 3,
18349                    "member_key": "deadline",
18350                    "member_index": 1,
18351                    "member_base_sequence": 3,
18352                    "member_size": 1,
18353                    "operation_kind": "timer",
18354                    "operation_identity": "timer-3",
18355                    "outcome": "completed",
18356                    "resolution_event_id": "timer-fired",
18357                    "resolution_event_type": "TimerFired",
18358                }),
18359            ),
18360            parallel_history_event(
18361                "ActivityFailed",
18362                2,
18363                "activity_type",
18364                "nested-second",
18365                nested_paths[1].clone(),
18366                None,
18367            ),
18368        ];
18369        let ctx = workflow_context(history);
18370        let mut selection = Box::pin(ctx.select_keyed(vec![
18371            (
18372                "nested",
18373                ParallelOperation::group(vec![
18374                    ParallelOperation::activity("nested-first", json!([])),
18375                    ParallelOperation::activity("nested-second", json!([])),
18376                ]),
18377            ),
18378            ("deadline", ParallelOperation::timer(Duration::ZERO)),
18379        ]));
18380        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18381        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18382            panic!("deadline winner must replay");
18383        };
18384        let nested = selected
18385            .handle(&SelectionKey::Name("nested".to_string()))
18386            .expect("nested handle")
18387            .clone();
18388        let mut cancel = Box::pin(nested.cancel());
18389        assert!(matches!(
18390            cancel.as_mut().poll(&mut task_context),
18391            Poll::Ready(Ok(()))
18392        ));
18393        let mut await_nested = Box::pin(nested.await_result());
18394
18395        assert!(matches!(
18396            await_nested.as_mut().poll(&mut task_context),
18397            Poll::Ready(Err(Error::ActivityFailed(_)))
18398        ));
18399        assert!(ctx.take_commands().expect("commands").is_empty());
18400    }
18401
18402    #[test]
18403    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
18404        let ctx = workflow_context(Vec::new());
18405        let mut call = Box::pin(ctx.select(vec![
18406            ParallelOperation::child_workflow(
18407                "child",
18408                ChildWorkflowOptions::new("children"),
18409                json!([]),
18410            ),
18411            ParallelOperation::timer(Duration::from_secs(30)),
18412            ParallelOperation::signal("approval"),
18413            ParallelOperation::condition(
18414                ConditionWaitOptions::new("ready", "sha256:ready"),
18415                || Ok(false),
18416            ),
18417            ParallelOperation::group(vec![
18418                ParallelOperation::activity("nested-one", json!([])),
18419                ParallelOperation::activity("nested-two", json!([])),
18420            ]),
18421        ]));
18422        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18423        assert!(matches!(
18424            call.as_mut().poll(&mut task_context),
18425            Poll::Pending
18426        ));
18427        let commands = ctx.take_commands().expect("selection commands");
18428        assert_eq!(
18429            commands
18430                .iter()
18431                .map(|command| command["type"].as_str().unwrap_or_default())
18432                .collect::<Vec<_>>(),
18433            [
18434                "start_child_workflow",
18435                "start_timer",
18436                "open_signal_wait",
18437                "open_condition_wait",
18438                "schedule_activity",
18439                "schedule_activity",
18440            ]
18441        );
18442        assert!(commands.iter().all(|command| {
18443            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
18444        }));
18445        assert_eq!(
18446            commands[4]["parallel_group_path"].as_array().map(Vec::len),
18447            Some(2)
18448        );
18449        assert_eq!(
18450            commands[4]["parallel_group_path"][0]["selection_member_kind"],
18451            json!("group")
18452        );
18453        assert_eq!(
18454            commands[5]["parallel_group_path"][0]["selection_member_kind"],
18455            json!("group")
18456        );
18457
18458        let one_leaf_ctx = workflow_context(Vec::new());
18459        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
18460            ParallelOperation::activity("nested-only", json!([])),
18461        ])]));
18462        assert!(matches!(
18463            one_leaf.as_mut().poll(&mut task_context),
18464            Poll::Pending
18465        ));
18466        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
18467        assert_eq!(one_leaf_commands.len(), 1);
18468        assert_eq!(
18469            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
18470            json!("group")
18471        );
18472        assert_eq!(
18473            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
18474            json!(1)
18475        );
18476    }
18477
18478    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
18479        let mut saga = ctx.saga();
18480        let outcome = async {
18481            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18482            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18483            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
18484            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
18485            ctx.activity("trip.charge", json!([])).await?;
18486            Ok(json!({"status": "booked"}))
18487        }
18488        .await;
18489        saga.finish(outcome).await
18490    }
18491
18492    fn saga_activity(
18493        event_type: &str,
18494        sequence: u64,
18495        activity_type: &str,
18496        result: Option<Value>,
18497    ) -> HistoryEvent {
18498        let mut payload = json!({
18499            "sequence": sequence,
18500            "activity_type": activity_type,
18501            "message": format!("{activity_type} failed"),
18502            "exception_type": "PlannedFailure",
18503            "non_retryable": true,
18504        });
18505        if let Some(result) = result {
18506            payload["result"] = fixture_envelope(result);
18507        }
18508        history_event(event_type, payload)
18509    }
18510
18511    #[test]
18512    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
18513        let completed_hotel_compensation = saga_activity(
18514            "ActivityCompleted",
18515            4,
18516            "trip.cancel-hotel",
18517            Some(Value::Null),
18518        );
18519        let history = vec![
18520            saga_activity(
18521                "ActivityCompleted",
18522                1,
18523                "trip.reserve-flight",
18524                Some(json!("flight-1")),
18525            ),
18526            saga_activity(
18527                "ActivityCompleted",
18528                2,
18529                "trip.reserve-hotel",
18530                Some(json!("hotel-1")),
18531            ),
18532            saga_activity("ActivityFailed", 3, "trip.charge", None),
18533            completed_hotel_compensation.clone(),
18534            completed_hotel_compensation,
18535        ];
18536
18537        for _restart in 0..2 {
18538            let ctx = workflow_context(history.clone());
18539            let mut future = Box::pin(trip_saga(ctx.clone()));
18540            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18541            assert!(matches!(
18542                future.as_mut().poll(&mut task_context),
18543                Poll::Pending
18544            ));
18545            let commands = ctx.take_commands().expect("compensation command");
18546            assert_eq!(commands.len(), 1);
18547            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18548        }
18549    }
18550
18551    #[test]
18552    fn saga_compensation_failure_preserves_both_typed_failures() {
18553        let history = vec![
18554            saga_activity(
18555                "ActivityCompleted",
18556                1,
18557                "trip.reserve-flight",
18558                Some(json!("flight-1")),
18559            ),
18560            saga_activity(
18561                "ActivityCompleted",
18562                2,
18563                "trip.reserve-hotel",
18564                Some(json!("hotel-1")),
18565            ),
18566            saga_activity("ActivityFailed", 3, "trip.charge", None),
18567            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
18568        ];
18569        let ctx = workflow_context(history);
18570        let mut future = Box::pin(trip_saga(ctx));
18571        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18572        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
18573            future.as_mut().poll(&mut task_context)
18574        else {
18575            panic!("compensation failure must remain structured");
18576        };
18577        assert!(matches!(
18578            *failure.initiating_failure,
18579            Error::ActivityFailed(_)
18580        ));
18581        assert!(matches!(
18582            *failure.compensation_failure,
18583            Error::ActivityFailed(_)
18584        ));
18585        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
18586        assert_eq!(failure.compensation_registration_order, 2);
18587    }
18588
18589    #[test]
18590    fn saga_compensates_cooperative_cancellation() {
18591        let ctx = workflow_context(vec![saga_activity(
18592            "ActivityCompleted",
18593            1,
18594            "trip.reserve-flight",
18595            Some(json!("flight-1")),
18596        )]);
18597        ctx.state.lock().expect("state").cancel_requested = true;
18598        let run = {
18599            let ctx = ctx.clone();
18600            async move {
18601                let mut saga = ctx.saga();
18602                let outcome = async {
18603                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18604                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18605                    ctx.throw_if_cancellation_requested()?;
18606                    Ok(json!("unexpected"))
18607                }
18608                .await;
18609                saga.finish(outcome).await
18610            }
18611        };
18612        let mut future = Box::pin(run);
18613        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18614        assert!(matches!(
18615            future.as_mut().poll(&mut task_context),
18616            Poll::Pending
18617        ));
18618        let commands = ctx.take_commands().expect("cancellation compensation");
18619        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18620    }
18621
18622    fn workflow_task(
18623        workflow_type: &str,
18624        history_events: Vec<HistoryEvent>,
18625        payload_codec: &str,
18626    ) -> WorkflowTask {
18627        WorkflowTask {
18628            task_id: format!("wft-{workflow_type}"),
18629            workflow_command_id: None,
18630            workflow_id: Some(format!("wf-{workflow_type}")),
18631            run_id: Some(format!("run-{workflow_type}")),
18632            workflow_type: workflow_type.to_string(),
18633            cancel_requested: false,
18634            payload_codec: payload_codec.to_string(),
18635            arguments: Some(
18636                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
18637            ),
18638            total_history_events: Some(history_events.len() as u64),
18639            history_size_bytes: None,
18640            continue_as_new_recommended: None,
18641            history_budget_pressure: None,
18642            history_events,
18643            next_history_page_token: None,
18644            workflow_task_attempt: 1,
18645            workflow_signal_id: None,
18646            signal_name: None,
18647            signal_arguments: None,
18648            workflow_update_id: None,
18649            update_name: None,
18650            lease_owner: Some("rust-worker".to_string()),
18651        }
18652    }
18653
18654    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18655    struct SideEffectProbe {
18656        request_id: String,
18657        attempt: u32,
18658    }
18659
18660    #[test]
18661    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
18662        let calls = AtomicUsize::new(0);
18663        let ctx = workflow_context(Vec::new());
18664        let value = ctx
18665            .side_effect(|| {
18666                calls.fetch_add(1, Ordering::SeqCst);
18667                SideEffectProbe {
18668                    request_id: "request-42".to_string(),
18669                    attempt: 3,
18670                }
18671            })
18672            .expect("first side effect");
18673        assert_eq!(value.attempt, 3);
18674        assert_eq!(calls.load(Ordering::SeqCst), 1);
18675        let commands = ctx.take_commands().expect("commands");
18676        assert_eq!(commands.len(), 1);
18677        assert_eq!(commands[0]["type"], "record_side_effect");
18678        assert_eq!(
18679            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18680            serde_json::to_value(&value).expect("value")
18681        );
18682
18683        let replay = workflow_context(vec![history_event(
18684            "SideEffectRecorded",
18685            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18686        )]);
18687        let replayed: SideEffectProbe = replay
18688            .side_effect(|| {
18689                calls.fetch_add(1, Ordering::SeqCst);
18690                panic!("committed side-effect callbacks must not run during replay")
18691            })
18692            .expect("replayed side effect");
18693        assert_eq!(replayed, value);
18694        assert_eq!(calls.load(Ordering::SeqCst), 1);
18695        assert!(replay.take_commands().expect("commands").is_empty());
18696        replay.ensure_history_consumed().expect("history consumed");
18697    }
18698
18699    #[test]
18700    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
18701        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18702        let value = ctx
18703            .side_effect(|| SideEffectProbe {
18704                request_id: "avro-request".to_string(),
18705                attempt: 1,
18706            })
18707            .expect("Avro side effect");
18708        let uuid = ctx.uuid_v4().expect("deterministic UUID");
18709        let commands = ctx.take_commands().expect("commands");
18710        assert_eq!(commands.len(), 2);
18711        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
18712        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
18713        assert_eq!(
18714            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18715            serde_json::to_value(&value).expect("value")
18716        );
18717
18718        let replay = workflow_context_with_codec(
18719            vec![
18720                history_event(
18721                    "SideEffectRecorded",
18722                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18723                ),
18724                history_event(
18725                    "SideEffectRecorded",
18726                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
18727                ),
18728            ],
18729            DEFAULT_CODEC,
18730        );
18731        let replayed: SideEffectProbe = replay
18732            .side_effect(|| panic!("Avro callback must not run"))
18733            .expect("replayed Avro value");
18734        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
18735        assert_eq!(replayed, value);
18736        assert_eq!(replayed_uuid, uuid);
18737        assert!(replay.take_commands().expect("commands").is_empty());
18738    }
18739
18740    #[test]
18741    fn typed_side_effect_replay_preserves_bytes_and_maps() {
18742        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18743        let value = ctx
18744            .side_effect_avro_value(typed_fidelity_probe)
18745            .expect("typed side effect");
18746        let commands = ctx.take_commands().expect("side-effect command");
18747        assert_eq!(
18748            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
18749                .expect("recorded side effect"),
18750            value
18751        );
18752
18753        let replay = workflow_context_with_codec(
18754            vec![history_event(
18755                "SideEffectRecorded",
18756                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18757            )],
18758            DEFAULT_CODEC,
18759        );
18760        assert_eq!(
18761            replay
18762                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
18763                .expect("replayed typed side effect"),
18764            value
18765        );
18766    }
18767
18768    #[test]
18769    fn ordered_side_effects_share_the_durable_command_stream() {
18770        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
18771        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
18772        let ctx = workflow_context(vec![
18773            history_event(
18774                "SideEffectRecorded",
18775                json!({"sequence": 1, "result": first}),
18776            ),
18777            history_event(
18778                "SideEffectRecorded",
18779                json!({"sequence": 2, "result": second}),
18780            ),
18781        ]);
18782        let first: String = ctx
18783            .side_effect(|| panic!("first callback must not run"))
18784            .expect("first replay");
18785        let second: i32 = ctx
18786            .side_effect(|| panic!("second callback must not run"))
18787            .expect("second replay");
18788        assert_eq!(first, "first");
18789        assert_eq!(second, 29);
18790        ctx.ensure_history_consumed().expect("ordered history");
18791
18792        let reordered = workflow_context(vec![history_event(
18793            "VersionMarkerRecorded",
18794            json!({
18795                "sequence": 1,
18796                "change_id": "before-side-effect",
18797                "version": 1,
18798                "min_supported": 1,
18799                "max_supported": 1,
18800            }),
18801        )]);
18802        let error = reordered
18803            .side_effect(|| "new".to_string())
18804            .expect_err("command reordering must fail");
18805        assert!(matches!(
18806            error,
18807            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18808                if reason == "recorded_command_mismatch"
18809        ));
18810    }
18811
18812    #[test]
18813    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
18814        let ctx = workflow_context(Vec::new());
18815        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
18816        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
18817        assert!(ctx.patched("new-search").expect("patch"));
18818        ctx.deprecate_patch("new-search").expect("deprecate patch");
18819        let commands = ctx.take_commands().expect("commands");
18820        assert_eq!(commands.len(), 2);
18821        assert_eq!(commands[0]["type"], "record_version_marker");
18822        assert_eq!(commands[0]["version"], 2);
18823        assert_eq!(commands[1]["change_id"], "new-search");
18824
18825        let replay = workflow_context(vec![history_event(
18826            "VersionMarkerRecorded",
18827            json!({
18828                "sequence": 1,
18829                "change_id": "checkout-v2",
18830                "version": 2,
18831                "min_supported": 1,
18832                "max_supported": 2,
18833            }),
18834        )]);
18835        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
18836        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
18837        assert!(replay.take_commands().expect("commands").is_empty());
18838        replay.ensure_history_consumed().expect("history consumed");
18839    }
18840
18841    #[test]
18842    fn version_markers_reject_incompatible_or_malformed_history() {
18843        let incompatible = workflow_context(vec![history_event(
18844            "VersionMarkerRecorded",
18845            json!({
18846                "sequence": 1,
18847                "change_id": "checkout-v2",
18848                "version": 1,
18849                "min_supported": 1,
18850                "max_supported": 2,
18851            }),
18852        )]);
18853        let error = incompatible
18854            .get_version("checkout-v2", 2, 3)
18855            .expect_err("old version is unsupported");
18856        assert!(matches!(
18857            error,
18858            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18859                if reason == "version_marker_incompatible_range"
18860        ));
18861
18862        for (history, reason) in [
18863            (
18864                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
18865                "side_effect_result_missing",
18866            ),
18867            (
18868                vec![history_event(
18869                    "SideEffectRecorded",
18870                    json!({
18871                        "sequence": 1,
18872                        "result": {"codec": "avro", "blob": "not-base64"},
18873                    }),
18874                )],
18875                "side_effect_payload_incompatible",
18876            ),
18877            (
18878                vec![history_event(
18879                    "SideEffectRecorded",
18880                    json!({"sequence": 1, "result": {"unwrapped": true}}),
18881                )],
18882                "side_effect_payload_malformed",
18883            ),
18884            (
18885                vec![history_event(
18886                    "VersionMarkerRecorded",
18887                    json!({
18888                        "sequence": 1,
18889                        "change_id": "change",
18890                        "version": 1,
18891                        "min_supported": 2,
18892                        "max_supported": 1,
18893                    }),
18894                )],
18895                "version_marker_history_range_invalid",
18896            ),
18897        ] {
18898            let error = WorkflowState::new(
18899                history,
18900                "rust-workers".to_string(),
18901                DEFAULT_CODEC.to_string(),
18902                None,
18903            )
18904            .expect_err("malformed history must fail");
18905            assert!(matches!(
18906                error,
18907                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
18908                    if actual == reason
18909            ));
18910        }
18911    }
18912
18913    #[test]
18914    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
18915        let history = vec![history_event(
18916            "SearchAttributesUpserted",
18917            json!({
18918                "sequence": 1,
18919                "attributes": {"customer_tier": "gold"},
18920                "attribute_types": {"customer_tier": "keyword"},
18921                "merged": {"customer_tier": "gold"}
18922            }),
18923        )];
18924
18925        let matching = workflow_context(history.clone());
18926        matching
18927            .upsert_search_attributes(
18928                SearchAttributeUpdate::new()
18929                    .keyword("customer_tier", "gold")
18930                    .expect("keyword update"),
18931            )
18932            .expect("matching typed update must replay");
18933        matching
18934            .ensure_history_consumed()
18935            .expect("history consumed");
18936
18937        let changed_type = workflow_context(history.clone());
18938        let error = changed_type
18939            .upsert_search_attributes(
18940                SearchAttributeUpdate::new()
18941                    .string("customer_tier", "gold")
18942                    .expect("string update"),
18943            )
18944            .expect_err("same JSON value with a different declaration must be nondeterministic");
18945        let Error::NonDeterministicReplay(failure) = error else {
18946            panic!("typed identity drift must be a replay failure");
18947        };
18948        assert_eq!(failure.reason, "search_attribute_type_mismatch");
18949        assert_eq!(failure.sequence, Some(1));
18950
18951        let changed_value = workflow_context(history);
18952        let error = changed_value
18953            .upsert_search_attributes(
18954                SearchAttributeUpdate::new()
18955                    .keyword("customer_tier", "platinum")
18956                    .expect("keyword update"),
18957            )
18958            .expect_err("changed values must be nondeterministic");
18959        let Error::NonDeterministicReplay(failure) = error else {
18960            panic!("value drift must be a replay failure");
18961        };
18962        assert_eq!(failure.reason, "search_attribute_value_mismatch");
18963    }
18964
18965    #[test]
18966    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
18967        let history = vec![history_event(
18968            "SearchAttributesUpserted",
18969            json!({
18970                "sequence": 1,
18971                "attributes": {"customer_tier": "gold"},
18972                "merged": {"customer_tier": "gold"}
18973            }),
18974        )];
18975
18976        for update in [
18977            SearchAttributeUpdate::new()
18978                .keyword("customer_tier", "gold")
18979                .expect("keyword update"),
18980            SearchAttributeUpdate::new()
18981                .string("customer_tier", "gold")
18982                .expect("string update"),
18983        ] {
18984            let restarted = workflow_context(history.clone());
18985            restarted
18986                .upsert_search_attributes(update)
18987                .expect("legacy history constrains values but has unknown type identity");
18988            restarted
18989                .ensure_history_consumed()
18990                .expect("history consumed");
18991        }
18992    }
18993
18994    #[test]
18995    fn search_attribute_command_emits_canonical_types() {
18996        let ctx = workflow_context(Vec::new());
18997        ctx.upsert_search_attributes(
18998            SearchAttributeUpdate::new()
18999                .keyword("customer_tier", "gold")
19000                .expect("keyword update")
19001                .int("attempts", 3)
19002                .expect("int update")
19003                .delete("obsolete")
19004                .expect("delete update"),
19005        )
19006        .expect("valid search attributes");
19007
19008        assert_eq!(
19009            ctx.take_commands().expect("commands"),
19010            vec![json!({
19011                "type": "upsert_search_attributes",
19012                "attributes": {
19013                    "attempts": 3,
19014                    "customer_tier": "gold",
19015                    "obsolete": null
19016                },
19017                "attribute_types": {
19018                    "attempts": "int",
19019                    "customer_tier": "keyword"
19020                }
19021            })]
19022        );
19023    }
19024
19025    #[test]
19026    fn duplicate_side_effects_and_version_markers_are_rejected() {
19027        let duplicate_side_effect = WorkflowState::new(
19028            vec![
19029                history_event(
19030                    "SideEffectRecorded",
19031                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
19032                ),
19033                history_event(
19034                    "SideEffectRecorded",
19035                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
19036                ),
19037            ],
19038            "rust-workers".to_string(),
19039            DEFAULT_CODEC.to_string(),
19040            None,
19041        )
19042        .expect_err("duplicate side effect");
19043        assert!(matches!(
19044            duplicate_side_effect,
19045            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19046                if reason == "duplicate_side_effect_record"
19047        ));
19048
19049        let marker = |sequence| {
19050            history_event(
19051                "VersionMarkerRecorded",
19052                json!({
19053                    "sequence": sequence,
19054                    "change_id": "same-change",
19055                    "version": 1,
19056                    "min_supported": 1,
19057                    "max_supported": 1,
19058                }),
19059            )
19060        };
19061        let duplicate_marker = WorkflowState::new(
19062            vec![marker(1), marker(3)],
19063            "rust-workers".to_string(),
19064            DEFAULT_CODEC.to_string(),
19065            None,
19066        )
19067        .expect_err("duplicate marker");
19068        assert!(matches!(
19069            duplicate_marker,
19070            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19071                if reason == "duplicate_version_marker"
19072        ));
19073    }
19074
19075    #[test]
19076    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
19077        let mut state = WorkflowState::new(
19078            Vec::new(),
19079            "rust-workers".to_string(),
19080            DEFAULT_CODEC.to_string(),
19081            None,
19082        )
19083        .expect("workflow state");
19084        state.workflow_command_identity = "command-7".to_string();
19085        let context = WorkflowContext {
19086            state: Arc::new(Mutex::new(state)),
19087            cancellation_scope_id: "root".into(),
19088        };
19089        let item =
19090            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
19091
19092        context
19093            .append_workflow_stream("output", &[item], Some(10))
19094            .expect("append command");
19095        context
19096            .error_workflow_stream("output", "producer failed", None)
19097            .expect("error command");
19098        let commands = context.take_commands().expect("commands");
19099
19100        assert_eq!(commands[0]["type"], "record_side_effect");
19101        assert_eq!(
19102            commands[0]["workflow_stream"]["command_identity"],
19103            "command-7"
19104        );
19105        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
19106        assert_eq!(
19107            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19108            "dw-stream:command-7:0:0"
19109        );
19110        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
19111
19112        let recorded = history_event(
19113            "SideEffectRecorded",
19114            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
19115        );
19116        let mut replay_state = WorkflowState::new(
19117            vec![recorded],
19118            "rust-workers".to_string(),
19119            DEFAULT_CODEC.to_string(),
19120            None,
19121        )
19122        .expect("replay state");
19123        replay_state.workflow_command_identity = "command-7".to_string();
19124        let replay_context = WorkflowContext {
19125            state: Arc::new(Mutex::new(replay_state)),
19126            cancellation_scope_id: "root".into(),
19127        };
19128        replay_context
19129            .append_workflow_stream(
19130                "output",
19131                &[WorkflowStreamAppendItem::from_reference(
19132                    "s3://bucket/item.avro",
19133                )],
19134                Some(10),
19135            )
19136            .expect("replayed append");
19137        assert!(replay_context
19138            .take_commands()
19139            .expect("replayed commands")
19140            .is_empty());
19141    }
19142
19143    #[test]
19144    fn workflow_stream_authoring_requires_server_durable_command_identity() {
19145        let context = workflow_context(Vec::new());
19146        let error = context
19147            .append_workflow_stream(
19148                "output",
19149                &[WorkflowStreamAppendItem::from_reference(
19150                    "s3://bucket/item.avro",
19151                )],
19152                None,
19153            )
19154            .expect_err("stream append without durable command identity must fail closed");
19155
19156        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
19157        assert!(context.take_commands().expect("commands").is_empty());
19158    }
19159
19160    #[test]
19161    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
19162        let client = Client::builder("http://localhost:8080").build().unwrap();
19163        let mut worker = Worker::new(client, "rust-workers");
19164        worker.register_workflow("streams.worker", |ctx, _| async move {
19165            ctx.append_workflow_stream(
19166                "output",
19167                &[WorkflowStreamAppendItem::new(json!("hello"))?],
19168                None,
19169            )?;
19170            ctx.close_workflow_stream("output", None)?;
19171            Ok(json!("done"))
19172        });
19173        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
19174            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
19175            task.workflow_command_id = command_id.clone();
19176            let expected_identity = command_id
19177                .as_deref()
19178                .filter(|id| !id.is_empty())
19179                .unwrap_or(&task.task_id)
19180                .to_string();
19181            let commands = worker
19182                .execute_workflow_task(task)
19183                .expect("ordinary worker stream output");
19184            assert_eq!(commands.len(), 3);
19185            assert_eq!(
19186                commands[0]["workflow_stream"]["command_identity"],
19187                expected_identity
19188            );
19189            assert_eq!(
19190                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19191                format!("dw-stream:{expected_identity}:0:0")
19192            );
19193            assert_eq!(
19194                commands[1]["workflow_stream"]["command_identity"],
19195                expected_identity
19196            );
19197            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
19198            let history = commands[..2]
19199                .iter()
19200                .enumerate()
19201                .map(|(index, command)| {
19202                    history_event(
19203                        "SideEffectRecorded",
19204                        json!({"sequence":index + 1,"result":command["result"]}),
19205                    )
19206                })
19207                .collect();
19208            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
19209            replay.task_id = "replacement-task".to_string();
19210            let replayed = worker
19211                .execute_workflow_task(replay)
19212                .expect("replacement worker consumes recorded stream effects");
19213            assert_eq!(replayed.len(), 1);
19214            assert_eq!(replayed[0]["type"], "complete_workflow");
19215        }
19216        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
19217        missing.task_id.clear();
19218        assert!(matches!(
19219            worker.execute_workflow_task(missing),
19220            Err(Error::MissingWorkflowCommandIdentity)
19221        ));
19222    }
19223
19224    #[test]
19225    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
19226        fn worker(calls: Arc<AtomicUsize>) -> Worker {
19227            let client = Client::new("http://127.0.0.1:8080").expect("client");
19228            let mut worker = Worker::new(client, "rust-workers");
19229            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
19230                let calls = Arc::clone(&calls);
19231                async move {
19232                    let captured = ctx.side_effect(|| {
19233                        calls.fetch_add(1, Ordering::SeqCst);
19234                        "captured-once".to_string()
19235                    })?;
19236                    let version = ctx.get_version("cold-restart", 1, 2)?;
19237                    Ok(json!({"captured": captured, "version": version}))
19238                }
19239            });
19240            worker
19241        }
19242
19243        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
19244            WorkflowTask {
19245                task_id: "wft-side-effect-version".to_string(),
19246                workflow_command_id: None,
19247                workflow_id: Some("wf-side-effect-version".to_string()),
19248                run_id: Some("run-side-effect-version".to_string()),
19249                workflow_type: "rust.side-effect-version".to_string(),
19250                cancel_requested: false,
19251                payload_codec: DEFAULT_CODEC.to_string(),
19252                arguments: Some(
19253                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
19254                ),
19255                history_events,
19256                total_history_events: None,
19257                history_size_bytes: None,
19258                continue_as_new_recommended: None,
19259                history_budget_pressure: None,
19260                next_history_page_token: None,
19261                workflow_task_attempt: 1,
19262                workflow_signal_id: None,
19263                signal_name: None,
19264                signal_arguments: None,
19265                workflow_update_id: None,
19266                update_name: None,
19267                lease_owner: Some("rust-worker".to_string()),
19268            }
19269        }
19270
19271        let calls = Arc::new(AtomicUsize::new(0));
19272        let initial = worker(Arc::clone(&calls))
19273            .execute_workflow_task(task(Vec::new()))
19274            .expect("initial execution");
19275        assert_eq!(
19276            initial
19277                .iter()
19278                .map(|command| &command["type"])
19279                .collect::<Vec<_>>(),
19280            vec![
19281                "record_side_effect",
19282                "record_version_marker",
19283                "complete_workflow"
19284            ]
19285        );
19286        assert_eq!(calls.load(Ordering::SeqCst), 1);
19287
19288        let restarted = worker(Arc::clone(&calls));
19289        let replayed = restarted
19290            .execute_workflow_task(task(vec![
19291                history_event(
19292                    "SideEffectRecorded",
19293                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
19294                ),
19295                history_event(
19296                    "VersionMarkerRecorded",
19297                    json!({
19298                        "sequence": 2,
19299                        "change_id": "cold-restart",
19300                        "version": 2,
19301                        "min_supported": 1,
19302                        "max_supported": 2,
19303                    }),
19304                ),
19305            ]))
19306            .expect("cold replay");
19307        assert_eq!(replayed.len(), 1);
19308        assert_eq!(replayed[0]["type"], "complete_workflow");
19309        assert_eq!(calls.load(Ordering::SeqCst), 1);
19310    }
19311
19312    #[test]
19313    fn side_effect_replay_rejects_changed_rust_value_type() {
19314        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
19315        let ctx = workflow_context(vec![history_event(
19316            "SideEffectRecorded",
19317            json!({"sequence": 1, "result": result}),
19318        )]);
19319        let error = ctx
19320            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
19321            .expect_err("changed type must fail replay");
19322        assert!(matches!(
19323            error,
19324            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19325                if reason == "side_effect_type_mismatch"
19326        ));
19327    }
19328
19329    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
19330        vec![
19331            history_event(
19332                "ActivityScheduled",
19333                json!({
19334                    "sequence": 1,
19335                    "activity_type": "flaky",
19336                    "activity_execution_id": "act-1",
19337                    "activity": {
19338                        "id": "act-1",
19339                        "sequence": 1,
19340                        "type": "flaky",
19341                        "queue": "critical-activities",
19342                        "execution_mode": null,
19343                        "retry_policy": {
19344                            "snapshot_version": 1,
19345                            "max_attempts": 3,
19346                            "backoff_seconds": [2, 4],
19347                            "start_to_close_timeout": 30,
19348                            "schedule_to_start_timeout": 5,
19349                            "schedule_to_close_timeout": 90,
19350                            "heartbeat_timeout": 10,
19351                            "non_retryable_error_types": ["PermanentError"]
19352                        }
19353                    }
19354                }),
19355            ),
19356            history_event(
19357                "ActivityStarted",
19358                json!({
19359                    "sequence": 1,
19360                    "activity_type": "flaky",
19361                    "activity_execution_id": "act-1",
19362                    "activity_attempt_id": "attempt-1",
19363                    "attempt_number": 1
19364                }),
19365            ),
19366            history_event(
19367                "ActivityRetryScheduled",
19368                json!({
19369                    "sequence": 1,
19370                    "activity_type": "flaky",
19371                    "activity_execution_id": "act-1",
19372                    "activity_attempt_id": "attempt-1",
19373                    "attempt_number": 1,
19374                    "retry_after_attempt": 1,
19375                    "retry_backoff_seconds": 2,
19376                    "failure_category": "activity",
19377                    "exception_type": "TransientError"
19378                }),
19379            ),
19380            history_event(
19381                "ActivityStarted",
19382                json!({
19383                    "sequence": 1,
19384                    "activity_type": "flaky",
19385                    "activity_execution_id": "act-1",
19386                    "activity_attempt_id": "attempt-2",
19387                    "attempt_number": 2
19388                }),
19389            ),
19390            history_event(
19391                "ActivityCompleted",
19392                json!({
19393                    "sequence": 1,
19394                    "activity_type": "flaky",
19395                    "activity_execution_id": "act-1",
19396                    "activity_attempt_id": "attempt-2",
19397                    "attempt_number": 2,
19398                    "payload_codec": DEFAULT_CODEC,
19399                    "result": fixture_envelope(json!({"status":"recovered"}))
19400                }),
19401            ),
19402        ]
19403    }
19404
19405    fn retry_activity_options() -> ActivityOptions {
19406        ActivityOptions::new()
19407            .task_queue("critical-activities")
19408            .retry_policy(
19409                ActivityRetryPolicy::new(3)
19410                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
19411                    .non_retryable_error_type("PermanentError"),
19412            )
19413            .start_to_close_timeout(Duration::from_secs(30))
19414            .schedule_to_start_timeout(Duration::from_secs(5))
19415            .schedule_to_close_timeout(Duration::from_secs(90))
19416            .heartbeat_timeout(Duration::from_secs(10))
19417    }
19418
19419    #[test]
19420    fn fixed_avro_value_round_trips_json_values() {
19421        let value = json!({"greeting": "hello", "count": 3, "ok": true});
19422        let envelope = PayloadEnvelope::avro(&value).expect("encode");
19423        assert_eq!(envelope.codec, DEFAULT_CODEC);
19424        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
19425    }
19426
19427    #[tokio::test]
19428    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
19429        let client = Client::new("http://127.0.0.1:8080").expect("client");
19430        let mut worker = Worker::new(client, "rust-workers");
19431        worker.register_typed_workflow(
19432            "typed.contract.workflow",
19433            |_ctx, input: TypedContract| async move { Ok(input) },
19434        );
19435        worker.register_typed_activity(
19436            "typed.contract.activity",
19437            |_ctx, input: TypedContract| async move { Ok(input) },
19438        );
19439
19440        let expected = typed_contract();
19441        let arguments = AvroValue::Array(vec![
19442            AvroValue::from_serialize(&expected).expect("typed request")
19443        ]);
19444        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
19445        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
19446        workflow.arguments = Some(envelope.clone());
19447        let commands = worker
19448            .execute_workflow_task(workflow)
19449            .expect("typed workflow task");
19450        let workflow_result: TypedContract =
19451            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19452                .expect("workflow result envelope")
19453                .deserialize()
19454                .expect("workflow result type");
19455        assert_eq!(workflow_result, expected);
19456
19457        let activity = ActivityTask {
19458            task_id: "typed-contract-activity".to_string(),
19459            activity_attempt_id: Some("typed-contract-attempt".to_string()),
19460            attempt_id: None,
19461            activity_type: "typed.contract.activity".to_string(),
19462            payload_codec: DEFAULT_CODEC.to_string(),
19463            arguments: Some(envelope),
19464            attempt_number: 1,
19465            lease_owner: Some("rust-worker".to_string()),
19466        };
19467        let activity_result: TypedContract = worker
19468            .execute_activity_task(activity)
19469            .await
19470            .expect("typed activity task")
19471            .deserialize()
19472            .expect("activity result type");
19473        assert_eq!(activity_result, expected);
19474    }
19475
19476    #[tokio::test]
19477    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
19478        let client = Client::new("http://127.0.0.1:8080").expect("client");
19479        let mut worker = Worker::new(client, "rust-workers");
19480        worker.register_typed_workflow(
19481            "typed.shape.workflow",
19482            |_ctx, input: TypedContract| async move { Ok(input) },
19483        );
19484        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
19485            Ok(f64::NAN)
19486        });
19487
19488        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
19489        workflow.arguments = Some(
19490            encode_typed_envelope(
19491                &AvroValue::Array(vec![
19492                    AvroValue::String("first".to_string()),
19493                    AvroValue::String("second".to_string()),
19494                ]),
19495                DEFAULT_CODEC,
19496            )
19497            .expect("malformed typed arguments"),
19498        );
19499        let commands = worker
19500            .execute_workflow_task(workflow)
19501            .expect("shape mismatch becomes a workflow failure");
19502        let message = commands[0]["message"].as_str().expect("failure message");
19503        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
19504        assert!(message.contains(type_name::<TypedContract>()));
19505        assert!(message.contains("task carried 2 arguments"));
19506
19507        let activity = ActivityTask {
19508            task_id: "typed-unsupported-activity".to_string(),
19509            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
19510            attempt_id: None,
19511            activity_type: "typed.unsupported.activity".to_string(),
19512            payload_codec: DEFAULT_CODEC.to_string(),
19513            arguments: Some(
19514                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19515                    .expect("unit arguments"),
19516            ),
19517            attempt_number: 1,
19518            lease_owner: Some("rust-worker".to_string()),
19519        };
19520        let Error::HandlerType {
19521            handler_kind,
19522            handler_name,
19523            value_kind,
19524            rust_type,
19525            message,
19526        } = worker
19527            .execute_activity_task(activity)
19528            .await
19529            .expect_err("non-finite handler output must fail")
19530        else {
19531            panic!("expected contextual handler type failure");
19532        };
19533        assert_eq!(handler_kind, HandlerKind::Activity);
19534        assert_eq!(handler_name, "typed.unsupported.activity");
19535        assert_eq!(value_kind, HandlerValueKind::Result);
19536        assert_eq!(rust_type, type_name::<f64>());
19537        assert!(message.contains("non_finite_float"));
19538    }
19539
19540    #[tokio::test]
19541    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
19542        #[derive(Clone, Default)]
19543        struct State {
19544            observed: Option<TypedContract>,
19545        }
19546
19547        let client = Client::new("http://127.0.0.1:8080").expect("client");
19548        let mut worker = Worker::new(client, "rust-workers");
19549        worker.register_typed_replayed_workflow(
19550            "typed.contract.replayed",
19551            State::default,
19552            |ctx, input: TypedContract, state| async move {
19553                let result: TypedContract =
19554                    ctx.activity_typed("typed.contract.activity", input).await?;
19555                state.update(|current| current.observed = Some(result.clone()))?;
19556                Ok(result)
19557            },
19558        );
19559        worker.register_replayed_query::<State, _, _>(
19560            "typed.contract.replayed",
19561            "observed",
19562            |_ctx, state, _args| async move {
19563                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
19564            },
19565        );
19566
19567        let expected = typed_contract();
19568        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
19569        let workflow_arguments =
19570            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
19571                .expect("workflow arguments");
19572        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
19573        let task = QueryTask {
19574            query_task_id: "typed-replay-query".to_string(),
19575            query_task_attempt: 1,
19576            lease_owner: Some("rust-worker".to_string()),
19577            workflow_id: Some("typed-replay".to_string()),
19578            run_id: Some("typed-replay-run".to_string()),
19579            workflow_type: "typed.contract.replayed".to_string(),
19580            query_name: "observed".to_string(),
19581            payload_codec: DEFAULT_CODEC.to_string(),
19582            workflow_arguments: Some(workflow_arguments),
19583            query_arguments: Some(
19584                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19585                    .expect("query arguments"),
19586            ),
19587            history_events: vec![
19588                history_event(
19589                    "ActivityScheduled",
19590                    json!({
19591                        "sequence": 1,
19592                        "activity_type": "typed.contract.activity"
19593                    }),
19594                ),
19595                history_event(
19596                    "ActivityCompleted",
19597                    json!({
19598                        "sequence": 1,
19599                        "activity_type": "typed.contract.activity",
19600                        "payload_codec": DEFAULT_CODEC,
19601                        "result": result
19602                    }),
19603                ),
19604            ],
19605            history_export: None,
19606            run_status: Some("completed".to_string()),
19607        };
19608
19609        assert_eq!(
19610            worker
19611                .execute_query_task(task)
19612                .await
19613                .expect("typed replay query")
19614                .deserialize::<i64>()
19615                .expect("query result"),
19616            expected.signed
19617        );
19618    }
19619
19620    #[tokio::test]
19621    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
19622        let client = Client::new("http://127.0.0.1:8080").expect("client");
19623        let mut worker = Worker::new(client, "rust-workers");
19624        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
19625        worker
19626            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
19627        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
19628            Ok(input)
19629        });
19630        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
19631            Ok(input)
19632        });
19633        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
19634            Ok(AvroValue::Array(
19635                ctx.wait_signal_avro_value("changed").await?,
19636            ))
19637        });
19638
19639        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
19640        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
19641
19642        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
19643        workflow.arguments = Some(envelope.clone());
19644        let commands = worker
19645            .execute_workflow_task(workflow)
19646            .expect("typed workflow task");
19647        assert_eq!(commands[0]["type"], "complete_workflow");
19648        assert_eq!(
19649            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19650                .expect("typed workflow result"),
19651            arguments
19652        );
19653
19654        let activity = ActivityTask {
19655            task_id: "activity-typed".to_string(),
19656            activity_attempt_id: Some("attempt-typed".to_string()),
19657            attempt_id: None,
19658            activity_type: "typed.activity".to_string(),
19659            payload_codec: DEFAULT_CODEC.to_string(),
19660            arguments: Some(envelope.clone()),
19661            attempt_number: 1,
19662            lease_owner: Some("rust-worker".to_string()),
19663        };
19664        assert_eq!(
19665            worker
19666                .execute_activity_task(activity)
19667                .await
19668                .expect("typed activity result"),
19669            arguments
19670        );
19671
19672        let query = QueryTask {
19673            query_task_id: "query-typed".to_string(),
19674            query_task_attempt: 1,
19675            lease_owner: Some("rust-worker".to_string()),
19676            workflow_id: Some("typed-1".to_string()),
19677            run_id: Some("run-typed".to_string()),
19678            workflow_type: "typed.echo".to_string(),
19679            query_name: "inspect".to_string(),
19680            payload_codec: DEFAULT_CODEC.to_string(),
19681            workflow_arguments: Some(
19682                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19683                    .expect("workflow input"),
19684            ),
19685            query_arguments: Some(envelope.clone()),
19686            history_events: Vec::new(),
19687            history_export: None,
19688            run_status: Some("running".to_string()),
19689        };
19690        assert_eq!(
19691            worker
19692                .execute_query_task(query)
19693                .await
19694                .expect("typed query result"),
19695            arguments
19696        );
19697
19698        let mut update = workflow_task(
19699            "typed.echo",
19700            vec![history_event(
19701                "UpdateAccepted",
19702                json!({
19703                    "update_id": "update-typed",
19704                    "update_name": "replace",
19705                    "arguments": envelope.clone(),
19706                }),
19707            )],
19708            DEFAULT_CODEC,
19709        );
19710        update.workflow_update_id = Some("update-typed".to_string());
19711        update.update_name = Some("replace".to_string());
19712        let commands = worker
19713            .execute_workflow_task(update)
19714            .expect("typed update task");
19715        assert_eq!(commands[0]["type"], "complete_update");
19716        assert_eq!(
19717            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19718                .expect("typed update result"),
19719            arguments
19720        );
19721
19722        let mut signal = workflow_task(
19723            "typed.signal",
19724            vec![history_event(
19725                "SignalReceived",
19726                json!({
19727                    "signal_id": "signal-typed",
19728                    "signal_name": "changed",
19729                    "arguments": envelope.clone(),
19730                }),
19731            )],
19732            DEFAULT_CODEC,
19733        );
19734        signal.workflow_signal_id = Some("signal-typed".to_string());
19735        signal.signal_name = Some("changed".to_string());
19736        signal.signal_arguments = Some(envelope);
19737        let commands = worker
19738            .execute_workflow_task(signal)
19739            .expect("typed signal resume");
19740        assert_eq!(
19741            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19742                .expect("typed signal result"),
19743            arguments
19744        );
19745    }
19746
19747    #[tokio::test]
19748    async fn typed_helpers_never_parse_json_inspection_projection() {
19749        let collision_values = projection_collision_probe();
19750        let expected = AvroValue::Array(collision_values.clone());
19751        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
19752
19753        let activity_context = workflow_context_with_codec(
19754            vec![history_event(
19755                "ActivityCompleted",
19756                json!({
19757                    "sequence": 1,
19758                    "activity_type": "collision.activity",
19759                    "payload_codec": DEFAULT_CODEC,
19760                    "result": envelope.clone(),
19761                }),
19762            )],
19763            DEFAULT_CODEC,
19764        );
19765        assert_eq!(
19766            activity_context
19767                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
19768                .await
19769                .expect("typed activity collision result"),
19770            expected
19771        );
19772
19773        let signal_context = workflow_context_with_codec(
19774            vec![
19775                history_event(
19776                    "SignalWaitOpened",
19777                    json!({"sequence": 1, "signal_name": "collision"}),
19778                ),
19779                history_event(
19780                    "SignalApplied",
19781                    json!({
19782                        "sequence": 1,
19783                        "signal_name": "collision",
19784                        "payload_codec": DEFAULT_CODEC,
19785                        "value": envelope.clone(),
19786                    }),
19787                ),
19788            ],
19789            DEFAULT_CODEC,
19790        );
19791        assert_eq!(
19792            signal_context
19793                .wait_signal_avro_value("collision")
19794                .await
19795                .expect("typed signal collision arguments"),
19796            collision_values
19797        );
19798
19799        let child_context = workflow_context_with_codec(
19800            vec![
19801                history_event(
19802                    "ChildWorkflowScheduled",
19803                    json!({
19804                        "sequence": 1,
19805                        "child_workflow_instance_id": "collision-child",
19806                        "child_workflow_run_id": "collision-run",
19807                        "child_workflow_type": "collision.child",
19808                    }),
19809                ),
19810                history_event(
19811                    "ChildRunCompleted",
19812                    json!({
19813                        "sequence": 1,
19814                        "child_workflow_instance_id": "collision-child",
19815                        "child_workflow_run_id": "collision-run",
19816                        "child_workflow_type": "collision.child",
19817                        "payload_codec": DEFAULT_CODEC,
19818                        "result": envelope,
19819                    }),
19820                ),
19821            ],
19822            DEFAULT_CODEC,
19823        );
19824        let child = child_context
19825            .start_child_workflow_avro_value(
19826                "collision.child",
19827                ChildWorkflowOptions::new("collision-workers"),
19828                AvroValue::Array(Vec::new()),
19829            )
19830            .await
19831            .expect("typed child collision result");
19832        assert_eq!(child.result, expected);
19833    }
19834
19835    #[tokio::test]
19836    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
19837        let client = Client::new("http://127.0.0.1:8080").expect("client");
19838        let mut worker = Worker::new(client, "rust-workers");
19839        worker.register_replayed_workflow_avro_value(
19840            "typed.replayed",
19841            || (),
19842            |_ctx, input, _state| async move { Ok(input) },
19843        );
19844        worker.register_replayed_query_avro_value::<(), _, _>(
19845            "typed.replayed",
19846            "inspect",
19847            |ctx, _state, args| async move {
19848                let mut signals = ctx.signals_avro_value("collision");
19849                let signal = signals
19850                    .pop()
19851                    .map(AvroValue::Array)
19852                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
19853                Ok(AvroValue::Array(vec![
19854                    ctx.workflow_input_avro_value().clone(),
19855                    signal,
19856                    args,
19857                ]))
19858            },
19859        );
19860        let arguments = AvroValue::Array(projection_collision_probe());
19861        let signal_arguments =
19862            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
19863        let task = QueryTask {
19864            query_task_id: "query-typed-replay".to_string(),
19865            query_task_attempt: 1,
19866            lease_owner: Some("rust-worker".to_string()),
19867            workflow_id: Some("typed-replay".to_string()),
19868            run_id: Some("run-typed-replay".to_string()),
19869            workflow_type: "typed.replayed".to_string(),
19870            query_name: "inspect".to_string(),
19871            payload_codec: DEFAULT_CODEC.to_string(),
19872            workflow_arguments: Some(
19873                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
19874            ),
19875            query_arguments: Some(
19876                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
19877            ),
19878            history_events: vec![history_event(
19879                "SignalReceived",
19880                json!({
19881                    "signal_id": "collision-signal",
19882                    "signal_name": "collision",
19883                    "workflow_sequence": 1,
19884                    "payload_codec": DEFAULT_CODEC,
19885                    "arguments": signal_arguments,
19886                }),
19887            )],
19888            history_export: None,
19889            run_status: Some("completed".to_string()),
19890        };
19891
19892        assert_eq!(
19893            worker
19894                .execute_query_task(task)
19895                .await
19896                .expect("typed replay query"),
19897            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
19898        );
19899    }
19900
19901    #[test]
19902    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
19903        let value = BTreeMap::from([(1_i32, "integer key")]);
19904        let error = PayloadEnvelope::avro(&value)
19905            .expect_err("integer map keys must fail")
19906            .to_string();
19907
19908        assert!(error.contains("invalid_map_key"));
19909    }
19910
19911    #[test]
19912    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
19913        let envelope = PayloadEnvelope {
19914            codec: "json".to_string(),
19915            blob: r#"{"greeting":"hello"}"#.to_string(),
19916        };
19917
19918        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
19919        let diagnostic = error.to_string();
19920        assert!(diagnostic.contains("unsupported_payload_codec"));
19921        assert!(diagnostic.contains("codec=\"avro\""));
19922        assert!(diagnostic.contains("HTTP document transport"));
19923    }
19924
19925    #[test]
19926    fn untagged_json_payload_value_fails_closed() {
19927        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
19928            .expect_err("untagged JSON payload values must fail");
19929        let diagnostic = error.to_string();
19930        assert!(diagnostic.contains("unsupported_payload_codec"));
19931        assert!(diagnostic.contains("untagged durable payload"));
19932        assert!(diagnostic.contains("HTTP document transport"));
19933    }
19934
19935    #[test]
19936    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
19937        let envelope = PayloadEnvelope {
19938            codec: DEFAULT_CODEC.to_string(),
19939            blob: BASE64.encode([0x01]),
19940        };
19941
19942        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
19943        assert!(error.to_string().contains("invalid_payload_framing"));
19944    }
19945
19946    #[tokio::test]
19947    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
19948        let server = MockWorkerServer::start();
19949        let client = Client::builder(server.base_url())
19950            .timeout(Duration::from_secs(2))
19951            .build()
19952            .expect("client");
19953        let invalid_commands = [
19954            json!({
19955                "type": "complete_workflow",
19956                "result": {"codec": "json", "blob": null}
19957            }),
19958            json!({
19959                "type": "schedule_activity",
19960                "arguments": {"codec": "yaml", "blob": "ignored"}
19961            }),
19962            json!({
19963                "type": "start_child_workflow",
19964                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
19965            }),
19966            json!({"type": "continue_as_new", "arguments": []}),
19967            json!({"type": "complete_update"}),
19968            json!({"type": "record_side_effect", "result": null}),
19969            json!({
19970                "type": "start_service_operation",
19971                "payload_codec": DEFAULT_CODEC,
19972                "request_payload": "raw-avro-bytes"
19973            }),
19974        ];
19975
19976        for command in invalid_commands {
19977            let error = client
19978                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
19979                .await
19980                .expect_err("invalid durable payload must fail locally");
19981            let diagnostic = error.to_string();
19982            assert!(
19983                diagnostic.contains("unsupported_payload_codec")
19984                    || diagnostic.contains("invalid_payload_envelope")
19985                    || diagnostic.contains("untagged durable payload"),
19986                "unexpected validation diagnostic: {diagnostic}"
19987            );
19988        }
19989
19990        assert_eq!(
19991            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
19992            0,
19993            "invalid command payloads must not reach HTTP transport"
19994        );
19995    }
19996
19997    #[test]
19998    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
19999        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
20000        let commands = [
20001            json!({"type": "complete_workflow", "result": envelope.clone()}),
20002            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
20003            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
20004            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
20005            json!({"type": "complete_update", "result": envelope.clone()}),
20006            json!({"type": "record_side_effect", "result": envelope.clone()}),
20007            json!({
20008                "type": "start_service_operation",
20009                "payload_codec": DEFAULT_CODEC,
20010                "request_payload": envelope.clone()
20011            }),
20012            json!({
20013                "type": "complete_workflow",
20014                "result": envelope,
20015                "metadata": {
20016                    "codec": "json",
20017                    "payload_codec": "customer-codec",
20018                    "result": {"codec": "yaml", "blob": null}
20019                }
20020            }),
20021        ];
20022
20023        validate_workflow_task_commands(&commands)
20024            .expect("customer metadata must not become a protocol codec declaration");
20025    }
20026
20027    #[test]
20028    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
20029        assert_eq!(
20030            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
20031            AvroValue::Array(Vec::new())
20032        );
20033        assert_eq!(
20034            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
20035            AvroValue::Array(Vec::new())
20036        );
20037
20038        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
20039        signal.signal_name = Some("empty-signal".to_string());
20040        signal.signal_arguments = None;
20041        let decoded = decode_resume_signal(&signal)
20042            .expect("valid Avro signal")
20043            .expect("named signal resumes the workflow");
20044        assert!(decoded.arguments.is_empty());
20045    }
20046
20047    #[tokio::test]
20048    async fn malformed_task_level_codecs_become_pre_handler_failures() {
20049        let client = Client::new("http://127.0.0.1:8080").expect("client");
20050        let mut worker = Worker::new(client, "rust-workers");
20051        let handler_calls = Arc::new(AtomicUsize::new(0));
20052
20053        let calls = Arc::clone(&handler_calls);
20054        worker.register_workflow("codec.workflow", move |_ctx, _args| {
20055            calls.fetch_add(1, Ordering::SeqCst);
20056            async move { Ok(Value::Null) }
20057        });
20058        let calls = Arc::clone(&handler_calls);
20059        worker.register_activity("codec.activity", move |_ctx, _args| {
20060            calls.fetch_add(1, Ordering::SeqCst);
20061            async move { Ok(Value::Null) }
20062        });
20063        let calls = Arc::clone(&handler_calls);
20064        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20065            calls.fetch_add(1, Ordering::SeqCst);
20066            async move { Ok(Value::Null) }
20067        });
20068
20069        let mut failures = Vec::new();
20070        for codec_case in [
20071            InvalidTaskPayloadCodec::Missing,
20072            InvalidTaskPayloadCodec::Null,
20073            InvalidTaskPayloadCodec::NonString,
20074        ] {
20075            let mut workflow = json!({
20076                "task_id": format!("workflow-{}", codec_case.label()),
20077                "workflow_type": "codec.workflow"
20078            });
20079            codec_case.apply(&mut workflow);
20080            match serde_json::from_value::<WorkflowTask>(workflow) {
20081                Ok(task) => match worker.execute_workflow_task(task) {
20082                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
20083                    outcome => failures.push(format!(
20084                        "workflow {} codec returned {outcome:?}",
20085                        codec_case.label()
20086                    )),
20087                },
20088                Err(error) => failures.push(format!(
20089                    "workflow {} codec failed transport deserialization: {error}",
20090                    codec_case.label()
20091                )),
20092            }
20093
20094            let mut activity = json!({
20095                "task_id": format!("activity-{}", codec_case.label()),
20096                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
20097                "activity_type": "codec.activity",
20098                "attempt_number": 1
20099            });
20100            codec_case.apply(&mut activity);
20101            match serde_json::from_value::<ActivityTask>(activity) {
20102                Ok(task) => match worker.execute_activity_task(task).await {
20103                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
20104                    outcome => failures.push(format!(
20105                        "activity {} codec returned {outcome:?}",
20106                        codec_case.label()
20107                    )),
20108                },
20109                Err(error) => failures.push(format!(
20110                    "activity {} codec failed transport deserialization: {error}",
20111                    codec_case.label()
20112                )),
20113            }
20114
20115            let mut query = json!({
20116                "query_task_id": format!("query-{}", codec_case.label()),
20117                "workflow_type": "codec.workflow",
20118                "query_name": "known"
20119            });
20120            codec_case.apply(&mut query);
20121            match serde_json::from_value::<QueryTask>(query) {
20122                Ok(task) => match worker.execute_query_task(task).await {
20123                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
20124                    outcome => failures.push(format!(
20125                        "query {} codec returned {outcome:?}",
20126                        codec_case.label()
20127                    )),
20128                },
20129                Err(error) => failures.push(format!(
20130                    "query {} codec failed transport deserialization: {error}",
20131                    codec_case.label()
20132                )),
20133            }
20134        }
20135
20136        assert!(failures.is_empty(), "{}", failures.join("\n"));
20137        assert_eq!(
20138            handler_calls.load(Ordering::SeqCst),
20139            0,
20140            "invalid task codecs must not invoke a handler"
20141        );
20142    }
20143
20144    #[tokio::test]
20145    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
20146        for codec_case in [
20147            InvalidTaskPayloadCodec::Missing,
20148            InvalidTaskPayloadCodec::Null,
20149            InvalidTaskPayloadCodec::NonString,
20150        ] {
20151            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
20152            let client = Client::builder(server.base_url())
20153                .timeout(Duration::from_secs(2))
20154                .build()
20155                .expect("client");
20156            let mut worker = Worker::new(client, "rust-workers")
20157                .worker_id("codec-worker")
20158                .poll_timeout(Duration::from_millis(10));
20159            let handler_calls = Arc::new(AtomicUsize::new(0));
20160
20161            let calls = Arc::clone(&handler_calls);
20162            worker.register_workflow("codec.workflow", move |_ctx, _args| {
20163                calls.fetch_add(1, Ordering::SeqCst);
20164                async move { Ok(Value::Null) }
20165            });
20166            let calls = Arc::clone(&handler_calls);
20167            worker.register_activity("codec.activity", move |_ctx, _args| {
20168                calls.fetch_add(1, Ordering::SeqCst);
20169                async move { Ok(Value::Null) }
20170            });
20171            let calls = Arc::clone(&handler_calls);
20172            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20173                calls.fetch_add(1, Ordering::SeqCst);
20174                async move { Ok(Value::Null) }
20175            });
20176
20177            assert_eq!(
20178                worker.run_once().await.expect("invalid tasks are settled"),
20179                3,
20180                "all {} codec tasks must be handled",
20181                codec_case.label()
20182            );
20183            assert_eq!(
20184                handler_calls.load(Ordering::SeqCst),
20185                0,
20186                "{} task codecs must fail before every handler",
20187                codec_case.label()
20188            );
20189
20190            for path in [
20191                "/api/worker/workflow-tasks/codec-workflow/fail",
20192                "/api/worker/activity-tasks/codec-activity/fail",
20193                "/api/worker/query-tasks/codec-query/fail",
20194            ] {
20195                let body = server.request_body(path);
20196                assert!(
20197                    body["failure"]["message"]
20198                        .as_str()
20199                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
20200                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
20201                    codec_case.label()
20202                );
20203            }
20204            assert_eq!(
20205                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
20206                    ["reason"],
20207                "query_payload_decode_failed"
20208            );
20209            for path in [
20210                "/api/worker/workflow-tasks/codec-workflow/complete",
20211                "/api/worker/activity-tasks/codec-activity/complete",
20212                "/api/worker/query-tasks/codec-query/complete",
20213            ] {
20214                assert_eq!(
20215                    server.request_count(path),
20216                    0,
20217                    "invalid {} codec task reached {path}",
20218                    codec_case.label()
20219                );
20220            }
20221        }
20222    }
20223
20224    #[tokio::test]
20225    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
20226        let client = Client::new("http://127.0.0.1:8080").expect("client");
20227        let mut worker = Worker::new(client, "rust-workers");
20228        let handler_calls = Arc::new(AtomicUsize::new(0));
20229
20230        let calls = Arc::clone(&handler_calls);
20231        worker.register_workflow("codec.workflow", move |_ctx, _args| {
20232            calls.fetch_add(1, Ordering::SeqCst);
20233            async move { Ok(Value::Null) }
20234        });
20235        let calls = Arc::clone(&handler_calls);
20236        worker.register_activity("codec.activity", move |_ctx, _args| {
20237            calls.fetch_add(1, Ordering::SeqCst);
20238            async move { Ok(Value::Null) }
20239        });
20240        let calls = Arc::clone(&handler_calls);
20241        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
20242            calls.fetch_add(1, Ordering::SeqCst);
20243            async move { Ok(Value::Null) }
20244        });
20245        let calls = Arc::clone(&handler_calls);
20246        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20247            calls.fetch_add(1, Ordering::SeqCst);
20248            async move { Ok(Value::Null) }
20249        });
20250
20251        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20252        workflow.payload_codec = "json".to_string();
20253        workflow.arguments = None;
20254        let error = worker
20255            .execute_workflow_task(workflow)
20256            .expect_err("task codec must be checked before workflow invocation");
20257        assert!(error.to_string().contains("unsupported_payload_codec"));
20258
20259        let activity = ActivityTask {
20260            task_id: "activity-invalid-codec".to_string(),
20261            activity_attempt_id: None,
20262            attempt_id: None,
20263            activity_type: "codec.activity".to_string(),
20264            payload_codec: "unknown".to_string(),
20265            arguments: None,
20266            attempt_number: 1,
20267            lease_owner: None,
20268        };
20269        let error = worker
20270            .execute_activity_task(activity)
20271            .await
20272            .expect_err("task codec must be checked before activity invocation");
20273        assert!(error.to_string().contains("unsupported_payload_codec"));
20274
20275        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20276        update.workflow_update_id = Some("update-invalid-codec".to_string());
20277        update.update_name = Some("known".to_string());
20278        update.history_events.push(history_event(
20279            "UpdateAccepted",
20280            json!({
20281                "update_id": "update-invalid-codec",
20282                "update_name": "known",
20283                "arguments": {"codec": "json", "blob": null}
20284            }),
20285        ));
20286        let error = worker
20287            .execute_workflow_task(update)
20288            .expect_err("nested update codec must be checked before handler lookup");
20289        assert!(error.to_string().contains("unsupported_payload_codec"));
20290
20291        let query: QueryTask = serde_json::from_value(json!({
20292            "query_task_id": "query-invalid-codec",
20293            "workflow_type": "codec.workflow",
20294            "query_name": "known",
20295            "payload_codec": DEFAULT_CODEC,
20296            "workflow_arguments": null,
20297            "query_arguments": null,
20298            "history_export": {
20299                "payloads": {"codec": DEFAULT_CODEC},
20300                "signals": [{
20301                    "name": "empty",
20302                    "payload_codec": "json",
20303                    "arguments": null
20304                }]
20305            }
20306        }))
20307        .expect("query task");
20308        let failure = worker
20309            .execute_query_task(query)
20310            .await
20311            .expect_err("exported signal 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
20315        let exported_history: QueryTask = serde_json::from_value(json!({
20316            "query_task_id": "query-invalid-history-codec",
20317            "workflow_type": "codec.workflow",
20318            "query_name": "known",
20319            "payload_codec": DEFAULT_CODEC,
20320            "history_export": {
20321                "payloads": {"codec": DEFAULT_CODEC},
20322                "history_events": [{
20323                    "type": "ActivityCompleted",
20324                    "payload": {"payload_codec": "unknown", "result": null}
20325                }]
20326            }
20327        }))
20328        .expect("query task");
20329        let failure = worker
20330            .execute_query_task(exported_history)
20331            .await
20332            .expect_err("exported history codec must be checked before query invocation");
20333        assert_eq!(failure.reason, "query_payload_decode_failed");
20334        assert!(failure.message.contains("unsupported_payload_codec"));
20335        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
20336
20337        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
20338        unknown_workflow.arguments = None;
20339        unknown_workflow.history_events.push(history_event(
20340            "SignalReceived",
20341            json!({
20342                "signal_name": "empty",
20343                "payload_codec": "json",
20344                "arguments": null
20345            }),
20346        ));
20347        let error = worker
20348            .execute_workflow_task(unknown_workflow)
20349            .expect_err("history codec must precede unknown workflow outcome");
20350        assert!(error.to_string().contains("unsupported_payload_codec"));
20351
20352        let unknown_activity = ActivityTask {
20353            task_id: "activity-unknown".to_string(),
20354            activity_attempt_id: None,
20355            attempt_id: None,
20356            activity_type: "missing".to_string(),
20357            payload_codec: "json".to_string(),
20358            arguments: None,
20359            attempt_number: 1,
20360            lease_owner: None,
20361        };
20362        let error = worker
20363            .execute_activity_task(unknown_activity)
20364            .await
20365            .expect_err("codec must precede unknown activity outcome");
20366        assert!(error.to_string().contains("unsupported_payload_codec"));
20367
20368        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20369        unknown_update.payload_codec = "json".to_string();
20370        unknown_update.arguments = None;
20371        unknown_update.workflow_update_id = Some("update-unknown".to_string());
20372        unknown_update.update_name = Some("missing".to_string());
20373        let error = worker
20374            .execute_workflow_task(unknown_update)
20375            .expect_err("codec must precede fail_update shortcut");
20376        assert!(error.to_string().contains("unsupported_payload_codec"));
20377
20378        let unknown_query: QueryTask = serde_json::from_value(json!({
20379            "query_task_id": "query-unknown",
20380            "workflow_type": "missing",
20381            "query_name": "missing",
20382            "payload_codec": "json",
20383            "workflow_arguments": null,
20384            "query_arguments": null
20385        }))
20386        .expect("query task");
20387        let failure = worker
20388            .execute_query_task(unknown_query)
20389            .await
20390            .expect_err("codec must precede unknown query outcome");
20391        assert_eq!(failure.reason, "query_payload_decode_failed");
20392        assert!(failure.message.contains("unsupported_payload_codec"));
20393    }
20394
20395    #[tokio::test]
20396    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
20397        let client = Client::new("http://127.0.0.1:8080").expect("client");
20398        let worker = Worker::new(client, "rust-workers");
20399
20400        for event_type in ["SignalReceived", "SignalApplied"] {
20401            for (payload_field, codec) in [
20402                ("value", "json"),
20403                ("input", "unknown"),
20404                ("arguments", "json"),
20405            ] {
20406                let payload = json!({
20407                    "signal_name": "empty",
20408                    payload_field: {"codec": codec, "blob": null}
20409                });
20410                let workflow = workflow_task(
20411                    "missing",
20412                    vec![history_event(event_type, payload.clone())],
20413                    DEFAULT_CODEC,
20414                );
20415                let error = worker
20416                    .execute_workflow_task(workflow)
20417                    .expect_err("signal payload codec must precede unknown workflow outcome");
20418                assert!(
20419                    error.to_string().contains("unsupported_payload_codec"),
20420                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
20421                );
20422
20423                let query: QueryTask = serde_json::from_value(json!({
20424                    "query_task_id": format!("query-{event_type}-{payload_field}"),
20425                    "workflow_type": "missing",
20426                    "query_name": "missing",
20427                    "payload_codec": DEFAULT_CODEC,
20428                    "workflow_arguments": null,
20429                    "query_arguments": null,
20430                    "history_events": [{
20431                        "event_type": event_type,
20432                        "payload": payload
20433                    }]
20434                }))
20435                .expect("query task");
20436                let failure = worker
20437                    .execute_query_task(query)
20438                    .await
20439                    .expect_err("signal payload codec must precede unknown query outcome");
20440                assert_eq!(
20441                    failure.reason, "query_payload_decode_failed",
20442                    "{event_type}.{payload_field} returned an unrelated query outcome"
20443                );
20444                assert!(
20445                    failure.message.contains("unsupported_payload_codec"),
20446                    "{event_type}.{payload_field} returned an unrelated query error: {}",
20447                    failure.message
20448                );
20449            }
20450        }
20451    }
20452
20453    #[test]
20454    fn workflow_context_schedules_activity_until_completion_is_in_history() {
20455        let ctx = WorkflowContext {
20456            cancellation_scope_id: "root".into(),
20457            state: Arc::new(Mutex::new(
20458                WorkflowState::new_with_identity(
20459                    Vec::new(),
20460                    Some("wf-parent".to_string()),
20461                    Some("run-parent".to_string()),
20462                    "rust-workers".to_string(),
20463                    DEFAULT_CODEC.to_string(),
20464                    None,
20465                )
20466                .expect("workflow state"),
20467            )),
20468        };
20469
20470        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
20471        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20472        assert!(matches!(
20473            call.as_mut().poll(&mut task_context),
20474            Poll::Pending
20475        ));
20476
20477        let commands = ctx.take_commands().expect("commands");
20478        assert_eq!(commands[0]["type"], "schedule_activity");
20479        assert_eq!(commands[0]["activity_type"], "hello.activity");
20480    }
20481
20482    #[test]
20483    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
20484        let ctx = workflow_context(Vec::new());
20485        let options = ActivityOptions::new()
20486            .task_queue("payments")
20487            .retry_policy(
20488                ActivityRetryPolicy::new(4)
20489                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
20490                    .non_retryable_error_type("ValidationError"),
20491            )
20492            .start_to_close_timeout(Duration::from_secs(120))
20493            .schedule_to_start_timeout(Duration::from_secs(10))
20494            .schedule_to_close_timeout(Duration::from_secs(300))
20495            .heartbeat_timeout(Duration::from_secs(15));
20496        let mut call = Box::pin(ctx.activity_with_options(
20497            "charge-card",
20498            options,
20499            json!([{"order_id": "o-1"}]),
20500        ));
20501        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20502
20503        assert!(matches!(
20504            call.as_mut().poll(&mut task_context),
20505            Poll::Pending
20506        ));
20507        assert!(matches!(
20508            call.as_mut().poll(&mut task_context),
20509            Poll::Pending
20510        ));
20511
20512        let commands = ctx.take_commands().expect("activity command");
20513        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
20514        assert_eq!(commands[0]["queue"], "payments");
20515        assert_eq!(
20516            commands[0]["retry_policy"],
20517            json!({
20518                "max_attempts": 4,
20519                "backoff_seconds": [1, 3, 9],
20520                "non_retryable_error_types": ["ValidationError"],
20521            })
20522        );
20523        assert_eq!(commands[0]["start_to_close_timeout"], 120);
20524        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
20525        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
20526        assert_eq!(commands[0]["heartbeat_timeout"], 15);
20527    }
20528
20529    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
20530        vec![
20531            history_event(
20532                "ActivityScheduled",
20533                json!({"sequence":1,"activity_type":"render",
20534                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
20535            ),
20536            history_event(
20537                "ActivityCompleted",
20538                json!({"sequence":1,"activity_type":"render",
20539                "payload_codec":DEFAULT_CODEC,
20540                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
20541            ),
20542        ]
20543    }
20544
20545    #[test]
20546    fn worker_session_activity_routes_to_session_queue_once() {
20547        let ctx = workflow_context(Vec::new());
20548        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20549        let mut call = Box::pin(
20550            ctx.activity("render", json!([]))
20551                .in_worker_session(session.clone()),
20552        );
20553        let mut cx = TaskContext::from_waker(noop_waker_ref());
20554        assert!(call.as_mut().poll(&mut cx).is_pending());
20555        assert!(call.as_mut().poll(&mut cx).is_pending());
20556        let commands = ctx.take_commands().unwrap();
20557        assert_eq!(commands.len(), 1);
20558        assert_eq!(commands[0]["queue"], "gpu-workers");
20559        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
20560    }
20561
20562    #[tokio::test]
20563    async fn worker_session_cold_replay_uses_recorded_avro_result() {
20564        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20565        for _replacement in 0..2 {
20566            let ctx = workflow_context(completed_worker_session_history(&session));
20567            let result: i64 = ctx
20568                .activity("render", json!([]))
20569                .in_worker_session(session.clone())
20570                .typed()
20571                .await
20572                .unwrap();
20573            assert_eq!(result, 42);
20574            assert!(ctx.take_commands().unwrap().is_empty());
20575        }
20576    }
20577
20578    #[test]
20579    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
20580        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20581        for changed in [
20582            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
20583            Some(original.clone().ttl_seconds(60)),
20584            Some(original.clone().requirements(["gpu:l4"])),
20585            None,
20586        ] {
20587            let ctx = workflow_context(completed_worker_session_history(&original));
20588            let mut call = ctx.activity_with_options(
20589                "render",
20590                ActivityOptions::new().task_queue("gpu-workers"),
20591                json!([]),
20592            );
20593            if let Some(changed) = changed {
20594                call = call.in_worker_session(changed);
20595            }
20596            let mut call = Box::pin(call);
20597            let mut cx = TaskContext::from_waker(noop_waker_ref());
20598            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20599                call.as_mut().poll(&mut cx)
20600            else {
20601                panic!("changed session must fail replay");
20602            };
20603            assert_eq!(failure.reason, "activity_worker_session_mismatch");
20604            assert!(ctx.take_commands().unwrap().is_empty());
20605        }
20606    }
20607
20608    #[test]
20609    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
20610        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20611        let ctx = workflow_context(Vec::new());
20612        let mut local = Box::pin(
20613            ctx.local_activity("render", json!([]))
20614                .in_worker_session(session.clone()),
20615        );
20616        let mut cx = TaskContext::from_waker(noop_waker_ref());
20617        assert!(matches!(
20618            local.as_mut().poll(&mut cx),
20619            Poll::Ready(Err(Error::WorkerLoop(_)))
20620        ));
20621        assert!(ctx.take_commands().unwrap().is_empty());
20622        let mut remote = Box::pin(
20623            ctx.activity_with_options(
20624                "render",
20625                ActivityOptions::new().task_queue("other"),
20626                json!([]),
20627            )
20628            .in_worker_session(session),
20629        );
20630        assert!(matches!(
20631            remote.as_mut().poll(&mut cx),
20632            Poll::Ready(Err(Error::WorkerLoop(_)))
20633        ));
20634        assert!(ctx.take_commands().unwrap().is_empty());
20635    }
20636
20637    #[test]
20638    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
20639        let ctx = workflow_context(Vec::new());
20640        let options = ActivityOptions::new().retry_policy(
20641            ActivityRetryPolicy::new(3)
20642                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
20643        );
20644        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
20645        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20646
20647        assert!(matches!(
20648            call.as_mut().poll(&mut task_context),
20649            Poll::Pending
20650        ));
20651        assert_eq!(
20652            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
20653            json!([1, 2])
20654        );
20655    }
20656
20657    #[test]
20658    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
20659        let cases = [
20660            (
20661                ActivityOptions::new().task_queue("  "),
20662                ActivityOptionsErrorKind::EmptyTaskQueue,
20663            ),
20664            (
20665                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
20666                ActivityOptionsErrorKind::EmptyRetryPolicy,
20667            ),
20668            (
20669                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
20670                ActivityOptionsErrorKind::InvalidMaxAttempts,
20671            ),
20672            (
20673                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
20674                    max_attempts: None,
20675                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
20676                    non_retryable_error_types: Vec::new(),
20677                }),
20678                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
20679            ),
20680            (
20681                ActivityOptions::new().retry_policy(
20682                    ActivityRetryPolicy::new(2)
20683                        .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
20684                ),
20685                ActivityOptionsErrorKind::TooManyBackoffIntervals,
20686            ),
20687            (
20688                ActivityOptions::new().retry_policy(
20689                    ActivityRetryPolicy::new(2).exponential_backoff(
20690                        Duration::from_secs(1),
20691                        0,
20692                        None,
20693                    ),
20694                ),
20695                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
20696            ),
20697            (
20698                ActivityOptions::new()
20699                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
20700                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
20701            ),
20702            (
20703                ActivityOptions::new().retry_policy(
20704                    ActivityRetryPolicy::new(10_002).exponential_backoff(
20705                        Duration::from_secs(1),
20706                        1,
20707                        None,
20708                    ),
20709                ),
20710                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
20711            ),
20712            (
20713                ActivityOptions::new().retry_policy(
20714                    ActivityRetryPolicy::new(2)
20715                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
20716                ),
20717                ActivityOptionsErrorKind::BackoffOverflow,
20718            ),
20719        ];
20720
20721        for (options, expected_kind) in cases {
20722            let ctx = workflow_context(Vec::new());
20723            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
20724            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20725            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
20726                call.as_mut().poll(&mut task_context)
20727            else {
20728                panic!("expected typed activity validation error");
20729            };
20730            assert_eq!(error.kind, expected_kind);
20731            assert!(ctx.take_commands().expect("commands").is_empty());
20732        }
20733    }
20734
20735    #[test]
20736    fn activity_options_validate_positive_and_ordered_timeouts() {
20737        let zero_timeout_cases = [
20738            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
20739            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
20740            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
20741            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
20742        ];
20743        for options in zero_timeout_cases {
20744            assert_eq!(
20745                options.validate().expect_err("zero timeout").kind,
20746                ActivityOptionsErrorKind::TimeoutNotPositive
20747            );
20748        }
20749
20750        let ordering_cases = [
20751            ActivityOptions::new()
20752                .heartbeat_timeout(Duration::from_secs(11))
20753                .start_to_close_timeout(Duration::from_secs(10)),
20754            ActivityOptions::new()
20755                .start_to_close_timeout(Duration::from_secs(31))
20756                .schedule_to_close_timeout(Duration::from_secs(30)),
20757            ActivityOptions::new()
20758                .schedule_to_start_timeout(Duration::from_secs(31))
20759                .schedule_to_close_timeout(Duration::from_secs(30)),
20760        ];
20761        for options in ordering_cases {
20762            assert_eq!(
20763                options.validate().expect_err("timeout order").kind,
20764                ActivityOptionsErrorKind::TimeoutOrder
20765            );
20766        }
20767
20768        assert_eq!(
20769            ActivityOptions::new()
20770                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
20771                .validate()
20772                .expect_err("protocol integer overflow")
20773                .kind,
20774            ActivityOptionsErrorKind::TimeoutOverflow
20775        );
20776    }
20777
20778    #[test]
20779    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
20780        let ctx = workflow_context(completed_retry_activity_history());
20781        let mut call =
20782            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20783        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20784
20785        assert!(matches!(
20786            call.as_mut().poll(&mut task_context),
20787            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20788        ));
20789        assert!(ctx.take_commands().expect("commands").is_empty());
20790        ctx.ensure_history_consumed().expect("history consumed");
20791    }
20792
20793    #[test]
20794    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
20795        let mut options = retry_activity_options();
20796        options
20797            .retry_policy
20798            .as_mut()
20799            .expect("retry policy")
20800            .non_retryable_error_types
20801            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
20802
20803        let new_ctx = workflow_context(Vec::new());
20804        let mut new_call =
20805            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
20806        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20807        assert!(matches!(
20808            new_call.as_mut().poll(&mut task_context),
20809            Poll::Pending
20810        ));
20811        let commands = new_ctx.take_commands().expect("commands");
20812        assert_eq!(commands.len(), 1);
20813        assert_eq!(
20814            commands[0]["retry_policy"]["non_retryable_error_types"],
20815            json!(["PermanentError"])
20816        );
20817
20818        let replay_ctx = workflow_context(completed_retry_activity_history());
20819        let mut replay_call =
20820            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
20821        assert!(matches!(
20822            replay_call.as_mut().poll(&mut task_context),
20823            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20824        ));
20825        assert!(replay_ctx.take_commands().expect("commands").is_empty());
20826        replay_ctx
20827            .ensure_history_consumed()
20828            .expect("history consumed");
20829    }
20830
20831    #[test]
20832    fn replayed_intermediate_retry_remains_pending_across_restarts() {
20833        let history = completed_retry_activity_history()
20834            .into_iter()
20835            .take(3)
20836            .collect::<Vec<_>>();
20837
20838        for _restart in 0..2 {
20839            let ctx = workflow_context(history.clone());
20840            let mut call =
20841                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20842            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20843            assert!(matches!(
20844                call.as_mut().poll(&mut task_context),
20845                Poll::Pending
20846            ));
20847            assert!(ctx.take_commands().expect("commands").is_empty());
20848        }
20849    }
20850
20851    #[test]
20852    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
20853        let mut changed_queue = retry_activity_options();
20854        changed_queue.task_queue = Some("different-queue".to_string());
20855
20856        let mut changed_max_attempts = retry_activity_options();
20857        let retry_policy = changed_max_attempts
20858            .retry_policy
20859            .as_mut()
20860            .expect("retry policy");
20861        retry_policy.max_attempts = Some(4);
20862
20863        let mut changed_backoff = retry_activity_options();
20864        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
20865        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
20866            Duration::from_secs(3),
20867            Duration::from_secs(4),
20868        ]));
20869
20870        let mut changed_non_retryable_types = retry_activity_options();
20871        let retry_policy = changed_non_retryable_types
20872            .retry_policy
20873            .as_mut()
20874            .expect("retry policy");
20875        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
20876
20877        let mut changed_start_to_close = retry_activity_options();
20878        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
20879        let mut changed_schedule_to_start = retry_activity_options();
20880        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
20881        let mut changed_schedule_to_close = retry_activity_options();
20882        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
20883        let mut changed_heartbeat = retry_activity_options();
20884        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
20885
20886        let cases = [
20887            (changed_queue, "activity_task_queue_mismatch"),
20888            (changed_max_attempts, "activity_retry_policy_mismatch"),
20889            (changed_backoff, "activity_retry_policy_mismatch"),
20890            (
20891                changed_non_retryable_types,
20892                "activity_retry_policy_mismatch",
20893            ),
20894            (changed_start_to_close, "activity_retry_policy_mismatch"),
20895            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
20896            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
20897            (changed_heartbeat, "activity_retry_policy_mismatch"),
20898        ];
20899
20900        for (options, expected_reason) in cases {
20901            let ctx = workflow_context(completed_retry_activity_history());
20902            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
20903            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20904            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20905                call.as_mut().poll(&mut task_context)
20906            else {
20907                panic!("changed activity options must fail replay");
20908            };
20909            assert_eq!(failure.reason, expected_reason);
20910            assert_eq!(failure.sequence, Some(1));
20911            assert!(ctx.take_commands().expect("commands").is_empty());
20912        }
20913    }
20914
20915    #[test]
20916    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
20917        let cases = [
20918            (
20919                "execution_mode",
20920                json!("local"),
20921                "activity_execution_mode_mismatch",
20922            ),
20923            (
20924                "snapshot_version",
20925                json!(2),
20926                "activity_retry_policy_mismatch",
20927            ),
20928        ];
20929
20930        for (field, value, expected_reason) in cases {
20931            let mut history = completed_retry_activity_history();
20932            let activity = history[0].payload["activity"]
20933                .as_object_mut()
20934                .expect("activity snapshot");
20935            if field == "execution_mode" {
20936                activity.insert(field.to_string(), value);
20937            } else {
20938                activity["retry_policy"]
20939                    .as_object_mut()
20940                    .expect("retry snapshot")
20941                    .insert(field.to_string(), value);
20942            }
20943
20944            let ctx = workflow_context(history);
20945            let mut call =
20946                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20947            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20948            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20949                call.as_mut().poll(&mut task_context)
20950            else {
20951                panic!("changed {field} must fail replay");
20952            };
20953            assert_eq!(failure.reason, expected_reason);
20954            assert_eq!(failure.sequence, Some(1));
20955            assert!(ctx.take_commands().expect("commands").is_empty());
20956        }
20957    }
20958
20959    #[test]
20960    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
20961        for (nested, field, value, terminal_only) in [
20962            (false, "execution_mode", json!("local"), false),
20963            (false, "local_activity", json!(true), false),
20964            (true, "local_activity", json!(true), false),
20965            (false, "local_activity", json!(true), true),
20966        ] {
20967            let mut history = completed_retry_activity_history();
20968            history[0]
20969                .payload
20970                .as_object_mut()
20971                .unwrap()
20972                .remove("activity");
20973            let event = if terminal_only {
20974                history.last_mut().unwrap()
20975            } else {
20976                &mut history[0]
20977            };
20978            if nested {
20979                event.payload["activity"] = json!({(field): value});
20980            } else {
20981                event.payload[field] = value;
20982            }
20983            let ctx = workflow_context(history);
20984            let mut call =
20985                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20986            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20987            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20988                call.as_mut().poll(&mut task_context)
20989            else {
20990                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
20991            };
20992            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
20993            assert_eq!(failure.sequence, Some(1));
20994            assert!(ctx.take_commands().expect("commands").is_empty());
20995        }
20996    }
20997
20998    #[test]
20999    fn activity_history_rejects_conflicting_local_execution_markers() {
21000        let mut history = completed_retry_activity_history();
21001        history.last_mut().unwrap().payload["local_activity"] = json!(true);
21002        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
21003            .expect_err("remote schedule cannot become a local completion");
21004        assert!(
21005            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
21006            if reason == "activity_execution_mode_conflict")
21007        );
21008    }
21009
21010    #[test]
21011    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
21012        let mut history = completed_retry_activity_history();
21013        let activity = history[0].payload["activity"]
21014            .as_object_mut()
21015            .expect("activity snapshot");
21016        activity.remove("execution_mode");
21017        activity.remove("retry_policy");
21018
21019        let mut current = retry_activity_options();
21020        current.start_to_close_timeout = Some(Duration::from_secs(45));
21021        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
21022        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
21023        current.heartbeat_timeout = Some(Duration::from_secs(12));
21024
21025        let ctx = workflow_context(history);
21026        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
21027        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21028        assert!(matches!(
21029            call.as_mut().poll(&mut task_context),
21030            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21031        ));
21032        assert!(ctx.take_commands().expect("commands").is_empty());
21033        ctx.ensure_history_consumed().expect("history consumed");
21034    }
21035
21036    #[test]
21037    fn terminal_activity_failed_after_start_returns_typed_failure() {
21038        let history = vec![
21039            history_event(
21040                "ActivityScheduled",
21041                json!({
21042                    "sequence": 1,
21043                    "activity_type": "flaky",
21044                    "activity_execution_id": "act-terminal",
21045                    "activity": {
21046                        "id": "act-terminal",
21047                        "sequence": 1,
21048                        "type": "flaky",
21049                        "queue": "critical-activities",
21050                        "retry_policy": {
21051                            "snapshot_version": 1,
21052                            "max_attempts": 3,
21053                            "backoff_seconds": [2, 4],
21054                            "non_retryable_error_types": ["PermanentError"]
21055                        }
21056                    }
21057                }),
21058            ),
21059            history_event(
21060                "ActivityStarted",
21061                json!({
21062                    "sequence": 1,
21063                    "activity_type": "flaky",
21064                    "activity_execution_id": "act-terminal",
21065                    "activity_attempt_id": "attempt-1",
21066                    "attempt_number": 1
21067                }),
21068            ),
21069            history_event(
21070                "ActivityFailed",
21071                json!({
21072                    "sequence": 1,
21073                    "activity_type": "flaky",
21074                    "activity_execution_id": "act-terminal",
21075                    "activity_attempt_id": "attempt-1",
21076                    "attempt_number": 1,
21077                    "failure_id": "failure-terminal",
21078                    "failure_category": "activity",
21079                    "exception_type": "PermanentError",
21080                    "message": "cannot retry",
21081                    "non_retryable": true
21082                }),
21083            ),
21084        ];
21085        let ctx = workflow_context(history);
21086        let mut call =
21087            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21088        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21089
21090        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21091            call.as_mut().poll(&mut task_context)
21092        else {
21093            panic!("terminal ActivityFailed must settle the activity future");
21094        };
21095        assert_eq!(failure.kind, ActivityFailureKind::Failed);
21096        assert_eq!(
21097            failure.activity_execution_id.as_deref(),
21098            Some("act-terminal")
21099        );
21100        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
21101        assert!(failure.non_retryable);
21102        assert!(ctx.take_commands().expect("commands").is_empty());
21103        ctx.ensure_history_consumed().expect("history consumed");
21104    }
21105
21106    #[test]
21107    fn activity_terminal_events_return_machine_readable_failures() {
21108        let cases = [
21109            (
21110                "ActivityFailed",
21111                json!({
21112                    "sequence": 1,
21113                    "activity_type": "charge-card",
21114                    "activity_execution_id": "act-1",
21115                    "activity_attempt_id": "attempt-2",
21116                    "attempt_number": 2,
21117                    "failure_id": "failure-1",
21118                    "failure_category": "activity",
21119                    "exception_type": "PaymentDeclined",
21120                    "exception_class": "payments.PaymentDeclined",
21121                    "message": "card declined",
21122                    "non_retryable": true
21123                }),
21124                ActivityFailureKind::Failed,
21125                "activity",
21126            ),
21127            (
21128                "ActivityCancelled",
21129                json!({
21130                    "sequence": 1,
21131                    "activity_type": "charge-card",
21132                    "activity_execution_id": "act-1",
21133                    "activity_attempt_id": "attempt-1"
21134                }),
21135                ActivityFailureKind::Cancelled,
21136                "cancelled",
21137            ),
21138        ];
21139
21140        for (event_type, payload, expected_kind, expected_reason) in cases {
21141            let ctx = workflow_context(vec![history_event(event_type, payload)]);
21142            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
21143            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21144            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21145                call.as_mut().poll(&mut task_context)
21146            else {
21147                panic!("expected terminal activity failure");
21148            };
21149            assert_eq!(failure.kind, expected_kind);
21150            assert_eq!(failure.reason, expected_reason);
21151            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
21152            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
21153        }
21154    }
21155
21156    #[test]
21157    fn every_activity_timeout_class_is_typed() {
21158        for timeout_kind in [
21159            "start_to_close",
21160            "schedule_to_start",
21161            "schedule_to_close",
21162            "heartbeat",
21163        ] {
21164            let ctx = workflow_context(vec![history_event(
21165                "ActivityTimedOut",
21166                json!({
21167                    "sequence": 1,
21168                    "activity_type": "slow",
21169                    "activity_execution_id": "act-timeout",
21170                    "activity_attempt_id": "attempt-timeout",
21171                    "failure_category": "timeout",
21172                    "timeout_kind": timeout_kind,
21173                    "message": "deadline expired"
21174                }),
21175            )]);
21176            let mut call = Box::pin(ctx.activity("slow", json!([])));
21177            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21178            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21179                call.as_mut().poll(&mut task_context)
21180            else {
21181                panic!("expected timeout failure");
21182            };
21183            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
21184            assert_eq!(failure.reason, timeout_kind);
21185            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
21186            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
21187        }
21188    }
21189
21190    #[test]
21191    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
21192        let ctx = workflow_context(Vec::new());
21193        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
21194        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21195
21196        assert!(matches!(
21197            sleep.as_mut().poll(&mut task_context),
21198            Poll::Pending
21199        ));
21200        assert!(matches!(
21201            sleep.as_mut().poll(&mut task_context),
21202            Poll::Pending
21203        ));
21204
21205        let commands = ctx.take_commands().expect("timer command");
21206        assert_eq!(
21207            commands,
21208            vec![json!({
21209                "type": "start_timer",
21210                "delay_seconds": 2,
21211            })]
21212        );
21213    }
21214
21215    #[test]
21216    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
21217        let history = vec![
21218            history_event(
21219                "TimerScheduled",
21220                json!({
21221                    "sequence": 1,
21222                    "timer_id": "timer-1",
21223                    "delay_seconds": 5,
21224                    "fire_at": "2026-07-11T12:00:05Z",
21225                }),
21226            ),
21227            history_event(
21228                "TimerFired",
21229                json!({
21230                    "sequence": 1,
21231                    "timer_id": "timer-1",
21232                    "delay_seconds": 5,
21233                    "fire_at": "2026-07-11T12:00:05Z",
21234                    "fired_at": "2026-07-11T12:00:05Z",
21235                }),
21236            ),
21237        ];
21238
21239        for _restart in 0..2 {
21240            let ctx = workflow_context(history.clone());
21241            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
21242            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21243            assert!(matches!(
21244                sleep.as_mut().poll(&mut task_context),
21245                Poll::Ready(Ok(()))
21246            ));
21247            assert!(ctx.take_commands().expect("commands").is_empty());
21248            ctx.ensure_history_consumed().expect("history consumed");
21249        }
21250    }
21251
21252    #[test]
21253    fn workflow_sleep_rejects_changed_delay_during_replay() {
21254        let ctx = workflow_context(vec![
21255            history_event(
21256                "TimerScheduled",
21257                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21258            ),
21259            history_event(
21260                "TimerFired",
21261                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21262            ),
21263        ]);
21264        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
21265        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21266
21267        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21268            sleep.as_mut().poll(&mut task_context)
21269        else {
21270            panic!("changed timer delay must be rejected");
21271        };
21272        assert_eq!(failure.reason, "timer_delay_mismatch");
21273        assert_eq!(failure.sequence, Some(1));
21274    }
21275
21276    #[test]
21277    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
21278        let ctx = workflow_context(Vec::new());
21279        let mut wait = Box::pin(
21280            ctx.wait_condition(
21281                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
21282                    .timeout(Duration::from_millis(60_001)),
21283                || Ok(false),
21284            ),
21285        );
21286        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21287
21288        assert!(matches!(
21289            wait.as_mut().poll(&mut task_context),
21290            Poll::Pending
21291        ));
21292        assert!(matches!(
21293            wait.as_mut().poll(&mut task_context),
21294            Poll::Pending
21295        ));
21296        assert_eq!(
21297            ctx.take_commands().expect("condition command"),
21298            vec![json!({
21299                "type": "open_condition_wait",
21300                "condition_wait_occurrence_id": "rust:condition-wait:0",
21301                "condition_key": "approval.ready",
21302                "condition_definition_fingerprint": "sha256:approval-v1",
21303                "timeout_seconds": 61,
21304            })]
21305        );
21306    }
21307
21308    #[test]
21309    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
21310        let ctx = workflow_context(Vec::new());
21311        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
21312        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21313        assert!(matches!(
21314            satisfied.as_mut().poll(&mut task_context),
21315            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21316        ));
21317
21318        let mut timed_out = Box::pin(wait_condition!(
21319            ctx,
21320            "no-wait",
21321            timeout: Duration::ZERO,
21322            || Ok(false),
21323        ));
21324        assert!(matches!(
21325            timed_out.as_mut().poll(&mut task_context),
21326            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
21327        ));
21328        assert!(ctx.take_commands().expect("commands").is_empty());
21329    }
21330
21331    #[test]
21332    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
21333        let signal_history = vec![
21334            history_event(
21335                "ConditionWaitOpened",
21336                json!({
21337                    "sequence": 4,
21338                    "condition_wait_id": "condition:4",
21339                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21340                    "condition_key": "approval",
21341                    "condition_definition_fingerprint": "sha256:approval-v1",
21342                    "timeout_seconds": 30,
21343                }),
21344            ),
21345            history_event(
21346                "SignalReceived",
21347                json!({
21348                    "workflow_sequence": 4,
21349                    "signal_name": "approve",
21350                    "arguments": fixture_envelope(json!(["Ada"])),
21351                }),
21352            ),
21353        ];
21354        for _worker_before_or_after_restart in 0..2 {
21355            let ctx = workflow_context(signal_history.clone());
21356            let predicate_ctx = ctx.clone();
21357            let mut wait = Box::pin(
21358                ctx.wait_condition(
21359                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
21360                        .timeout(Duration::from_secs(30)),
21361                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
21362                ),
21363            );
21364            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21365            assert!(matches!(
21366                wait.as_mut().poll(&mut task_context),
21367                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21368            ));
21369            assert!(ctx.take_commands().expect("commands").is_empty());
21370            ctx.ensure_history_consumed().expect("condition consumed");
21371        }
21372
21373        let update_history = vec![
21374            history_event(
21375                "ConditionWaitOpened",
21376                json!({
21377                    "sequence": 7,
21378                    "condition_wait_id": "condition:7",
21379                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21380                    "condition_key": "update-approval",
21381                    "condition_definition_fingerprint": "sha256:update-approval-v1",
21382                }),
21383            ),
21384            history_event(
21385                "UpdateApplied",
21386                json!({
21387                    "sequence": 7,
21388                    "update_id": "update-1",
21389                    "update_name": "approve",
21390                    "arguments": fixture_envelope(json!([true])),
21391                }),
21392            ),
21393        ];
21394        let ctx = workflow_context(update_history);
21395        let predicate_ctx = ctx.clone();
21396        let mut wait = Box::pin(ctx.wait_condition(
21397            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
21398            move || {
21399                Ok(predicate_ctx
21400                    .updates("approve")?
21401                    .first()
21402                    .and_then(|arguments| arguments.first())
21403                    .and_then(Value::as_bool)
21404                    == Some(true))
21405            },
21406        ));
21407        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21408        assert!(matches!(
21409            wait.as_mut().poll(&mut task_context),
21410            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21411        ));
21412        assert!(ctx.take_commands().expect("commands").is_empty());
21413        ctx.ensure_history_consumed().expect("condition consumed");
21414    }
21415
21416    #[test]
21417    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
21418        let open_history = vec![
21419            history_event(
21420                "ConditionWaitOpened",
21421                json!({
21422                    "sequence": 3,
21423                    "condition_wait_id": "condition:3",
21424                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21425                    "condition_key": "two-votes",
21426                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21427                    "timeout_seconds": 120,
21428                }),
21429            ),
21430            history_event(
21431                "SignalReceived",
21432                json!({
21433                    "workflow_sequence": 3,
21434                    "signal_name": "vote",
21435                    "arguments": fixture_envelope(json!(["first"])),
21436                }),
21437            ),
21438        ];
21439        for _worker_before_or_after_restart in 0..2 {
21440            let ctx = workflow_context(open_history.clone());
21441            let predicate_ctx = ctx.clone();
21442            let mut wait = Box::pin(
21443                ctx.wait_condition(
21444                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21445                        .timeout(Duration::from_secs(120)),
21446                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
21447                ),
21448            );
21449            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21450            assert!(matches!(
21451                wait.as_mut().poll(&mut task_context),
21452                Poll::Pending
21453            ));
21454            assert_eq!(
21455                ctx.take_commands().expect("reopened condition"),
21456                vec![json!({
21457                    "type": "open_condition_wait",
21458                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21459                    "condition_key": "two-votes",
21460                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21461                    "timeout_seconds": 120,
21462                })]
21463            );
21464        }
21465
21466        let satisfied_ctx = workflow_context(vec![
21467            history_event(
21468                "ConditionWaitOpened",
21469                json!({
21470                    "sequence": 5,
21471                    "condition_wait_id": "condition:5",
21472                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21473                    "condition_key": "approval",
21474                    "condition_definition_fingerprint": "sha256:approval-v1",
21475                }),
21476            ),
21477            history_event(
21478                "ConditionWaitSatisfied",
21479                json!({
21480                    "sequence": 5,
21481                    "condition_wait_id": "condition:5",
21482                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21483                    "condition_key": "approval",
21484                    "condition_definition_fingerprint": "sha256:approval-v1",
21485                }),
21486            ),
21487        ]);
21488        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
21489            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
21490            || Ok(false),
21491        ));
21492        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21493        assert!(matches!(
21494            satisfied.as_mut().poll(&mut task_context),
21495            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21496        ));
21497
21498        let timed_out_ctx = workflow_context(vec![
21499            history_event(
21500                "ConditionWaitOpened",
21501                json!({
21502                    "sequence": 8,
21503                    "condition_wait_id": "condition:8",
21504                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21505                    "condition_key": "approval-timeout",
21506                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
21507                    "timeout_seconds": 5,
21508                }),
21509            ),
21510            history_event(
21511                "TimerScheduled",
21512                json!({
21513                    "sequence": 9,
21514                    "timer_id": "condition-timer:9",
21515                    "timer_kind": "condition_timeout",
21516                    "condition_wait_id": "condition:8",
21517                    "delay_seconds": 5,
21518                }),
21519            ),
21520            history_event(
21521                "TimerFired",
21522                json!({
21523                    "sequence": 9,
21524                    "timer_id": "condition-timer:9",
21525                    "timer_kind": "condition_timeout",
21526                    "condition_wait_id": "condition:8",
21527                    "delay_seconds": 5,
21528                }),
21529            ),
21530        ]);
21531        let mut timed_out = Box::pin(
21532            timed_out_ctx.wait_condition(
21533                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
21534                    .timeout(Duration::from_secs(5)),
21535                || Ok(true),
21536            ),
21537        );
21538        assert!(matches!(
21539            timed_out.as_mut().poll(&mut task_context),
21540            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
21541        ));
21542    }
21543
21544    #[test]
21545    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
21546        let ctx = workflow_context(reopened_selection_condition_history());
21547        {
21548            let state = ctx.state.lock().unwrap();
21549            assert!(matches!(
21550                selection_member_recorded_command(&state, 2),
21551                Some(RecordedCommand::ConditionWait {
21552                    sequence: 3,
21553                    result: None,
21554                    ..
21555                })
21556            ));
21557        }
21558        let mut selected = Box::pin(ctx.select_keyed(vec![
21559            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
21560            (
21561                "votes",
21562                ParallelOperation::condition(
21563                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
21564                    || Ok(true),
21565                ),
21566            ),
21567        ]));
21568        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21569        assert!(selected.as_mut().poll(&mut task_context).is_pending());
21570        assert!(
21571            ctx.take_commands().unwrap().is_empty(),
21572            "true predicate must not reopen the recorded wait"
21573        );
21574        ctx.ensure_history_consumed()
21575            .expect("physical reopens are consumed while canonical selection is pending");
21576    }
21577
21578    #[test]
21579    fn reopened_selection_condition_replays_its_latest_physical_winner() {
21580        for (terminal_type, acknowledge_timeout) in [
21581            ("ConditionWaitSatisfied", false),
21582            ("ConditionWaitTimedOut", false),
21583            ("TimerFired", false),
21584            ("TimerFired", true),
21585        ] {
21586            let mut history = reopened_selection_condition_history();
21587            let original_identity = history[1].payload["condition_wait_id"].clone();
21588            let uses_timer = terminal_type == "TimerFired";
21589            let mut resolution_payload = history[3].payload.clone();
21590            if uses_timer {
21591                for event in &mut history[1..] {
21592                    event.payload["timeout_seconds"] = json!(3);
21593                }
21594                resolution_payload = history[3].payload.clone();
21595                resolution_payload["timer_kind"] = json!("condition_timeout");
21596                resolution_payload["timer_id"] = json!("condition-timeout-3");
21597                resolution_payload["delay_seconds"] = json!(3);
21598                history.push(history_event("TimerScheduled", resolution_payload.clone()));
21599            }
21600            let mut resolution = history_event(terminal_type, resolution_payload.clone());
21601            resolution
21602                .raw
21603                .insert("id".into(), json!("latest-condition-resolution"));
21604            history.push(resolution);
21605            history.push(history_event(
21606                "SelectionResolved",
21607                json!({
21608                    "selection_group_id": "select-calls:1:2",
21609                    "selection_group_base_sequence": 1,
21610                    "selection_group_size": 2,
21611                    "member_key": "votes",
21612                    "member_index": 1,
21613                    "member_base_sequence": 2,
21614                    "member_size": 1,
21615                    "operation_kind": "condition",
21616                    "operation_identity": original_identity,
21617                    "outcome": "completed",
21618                    "resolution_event_id": "latest-condition-resolution",
21619                    "resolution_event_type": terminal_type,
21620                }),
21621            ));
21622            if acknowledge_timeout {
21623                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
21624            }
21625            let ctx = workflow_context(history);
21626            let mut selected = Box::pin(ctx.select_keyed(vec![
21627                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
21628                (
21629                    "votes",
21630                    ParallelOperation::condition(
21631                        if uses_timer {
21632                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21633                                .timeout(Duration::from_secs(3))
21634                        } else {
21635                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21636                        },
21637                        || Ok(true),
21638                    ),
21639                ),
21640            ]));
21641            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21642            match selected.as_mut().poll(&mut task_context) {
21643                Poll::Ready(Ok(result)) => {
21644                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
21645                    let expected = if terminal_type == "ConditionWaitSatisfied" {
21646                        ConditionWaitResult::Satisfied
21647                    } else {
21648                        ConditionWaitResult::TimedOut
21649                    };
21650                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
21651                }
21652                other => panic!("latest physical winner must replay: {other:?}"),
21653            }
21654            assert!(ctx.take_commands().unwrap().is_empty());
21655            ctx.ensure_history_consumed()
21656                .expect("winner history consumed");
21657        }
21658    }
21659
21660    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
21661        let fixture: Value = serde_json::from_str(include_str!(
21662            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
21663        ))
21664        .expect("grouped condition fixture");
21665        fixture["history"]
21666            .as_array()
21667            .unwrap()
21668            .iter()
21669            .map(|event| {
21670                let mut payload = event["payload"].clone();
21671                let index = payload["parallel_group_index"].as_u64().unwrap();
21672                payload["parallel_group_id"] = json!("select-calls:1:2");
21673                payload["parallel_group_mode"] = json!("select");
21674                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
21675                payload["selection_member_index"] = json!(index);
21676                payload["selection_member_base_sequence"] = json!(index + 1);
21677                payload["selection_member_size"] = json!(1);
21678                payload["selection_member_kind"] =
21679                    json!(if index == 0 { "timer" } else { "condition" });
21680                history_event(event["event_type"].as_str().unwrap(), payload)
21681            })
21682            .collect()
21683    }
21684
21685    #[test]
21686    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
21687        let fixture: Value = serde_json::from_str(include_str!(
21688            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
21689        ))
21690        .expect("grouped condition fixture");
21691        let original = fixture["history"].as_array().expect("fixture history");
21692        let decode = |events: &[Value]| {
21693            let history = events
21694                .iter()
21695                .map(|event| {
21696                    history_event(
21697                        event["event_type"].as_str().unwrap(),
21698                        event["payload"].clone(),
21699                    )
21700                })
21701                .collect::<Vec<_>>();
21702            recorded_commands(
21703                &history,
21704                DEFAULT_CODEC,
21705                WorkflowIdentity {
21706                    workflow_id: None,
21707                    run_id: None,
21708                },
21709            )
21710        };
21711        assert!(decode(original).is_ok());
21712        for field in [
21713            "condition_wait_occurrence_id",
21714            "condition_key",
21715            "condition_definition_fingerprint",
21716            "timeout_seconds",
21717            "parallel_group_id",
21718            "parallel_group_size",
21719            "parallel_group_index",
21720        ] {
21721            let mut changed = original.clone();
21722            changed[3]["payload"][field] = match field {
21723                "timeout_seconds" | "parallel_group_size" => json!(30),
21724                "parallel_group_index" => json!(0),
21725                _ => json!("changed"),
21726            };
21727            assert!(
21728                decode(&changed).is_err(),
21729                "reopen must reject changed {field}"
21730            );
21731        }
21732        let mut unsettled = original.clone();
21733        unsettled.remove(2);
21734        assert!(
21735            decode(&unsettled).is_err(),
21736            "physical predecessor must be resolved"
21737        );
21738        let mut timed_out = original.clone();
21739        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
21740        assert!(decode(&timed_out).is_err(), "timeout is terminal");
21741        let mut late_resolution = original.clone();
21742        late_resolution.swap(2, 3);
21743        assert!(
21744            decode(&late_resolution).is_err(),
21745            "later history cannot authorize a reopen"
21746        );
21747    }
21748
21749    #[test]
21750    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
21751        let history = vec![
21752            history_event(
21753                "ConditionWaitOpened",
21754                json!({
21755                    "sequence": 3,
21756                    "condition_wait_id": "condition:3",
21757                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21758                    "condition_key": "two-votes",
21759                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21760                }),
21761            ),
21762            history_event(
21763                "SignalReceived",
21764                json!({
21765                    "workflow_sequence": 3,
21766                    "signal_name": "vote",
21767                    "arguments": fixture_envelope(json!(["first"])),
21768                }),
21769            ),
21770            history_event(
21771                "ConditionWaitSatisfied",
21772                json!({
21773                    "sequence": 3,
21774                    "condition_wait_id": "condition:3",
21775                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21776                    "condition_key": "two-votes",
21777                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21778                }),
21779            ),
21780            history_event(
21781                "ConditionWaitOpened",
21782                json!({
21783                    "sequence": 5,
21784                    "condition_wait_id": "condition:5",
21785                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21786                    "condition_key": "two-votes",
21787                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21788                }),
21789            ),
21790            history_event(
21791                "SignalReceived",
21792                json!({
21793                    "workflow_sequence": 5,
21794                    "signal_name": "vote",
21795                    "arguments": fixture_envelope(json!(["second"])),
21796                }),
21797            ),
21798            history_event(
21799                "ConditionWaitSatisfied",
21800                json!({
21801                    "sequence": 5,
21802                    "condition_wait_id": "condition:5",
21803                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21804                    "condition_key": "two-votes",
21805                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21806                }),
21807            ),
21808        ];
21809        for _cold_worker_or_restart in 0..2 {
21810            let ctx = workflow_context(history.clone());
21811            let predicate_ctx = ctx.clone();
21812            let mut wait = Box::pin(ctx.wait_condition(
21813                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
21814                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
21815            ));
21816            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21817
21818            assert!(matches!(
21819                wait.as_mut().poll(&mut task_context),
21820                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21821            ));
21822            assert!(ctx.take_commands().expect("commands").is_empty());
21823            ctx.ensure_history_consumed()
21824                .expect("every physical wait-open is consumed");
21825        }
21826    }
21827
21828    #[test]
21829    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
21830        let history = vec![
21831            history_event(
21832                "ConditionWaitOpened",
21833                json!({
21834                    "sequence": 3,
21835                    "condition_wait_id": "condition:3",
21836                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21837                    "condition_key": "approved",
21838                    "condition_definition_fingerprint": "sha256:approved-v1",
21839                }),
21840            ),
21841            history_event(
21842                "UpdateApplied",
21843                json!({
21844                    "sequence": 3,
21845                    "update_id": "update-1",
21846                    "update_name": "approve",
21847                    "arguments": fixture_envelope(json!([false])),
21848                }),
21849            ),
21850            history_event(
21851                "ConditionWaitOpened",
21852                json!({
21853                    "sequence": 5,
21854                    "condition_wait_id": "condition:5",
21855                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21856                    "condition_key": "approved",
21857                    "condition_definition_fingerprint": "sha256:approved-v1",
21858                }),
21859            ),
21860            history_event(
21861                "UpdateApplied",
21862                json!({
21863                    "sequence": 5,
21864                    "update_id": "update-2",
21865                    "update_name": "approve",
21866                    "arguments": fixture_envelope(json!([true])),
21867                }),
21868            ),
21869        ];
21870
21871        for _cold_worker_or_restart in 0..2 {
21872            let ctx = workflow_context(history.clone());
21873            let predicate_ctx = ctx.clone();
21874            let mut wait = Box::pin(ctx.wait_condition(
21875                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
21876                move || {
21877                    Ok(predicate_ctx
21878                        .updates("approve")?
21879                        .last()
21880                        .and_then(|arguments| arguments.first())
21881                        .and_then(Value::as_bool)
21882                        == Some(true))
21883                },
21884            ));
21885            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21886
21887            assert!(matches!(
21888                wait.as_mut().poll(&mut task_context),
21889                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21890            ));
21891            assert!(ctx.take_commands().expect("commands").is_empty());
21892            ctx.ensure_history_consumed()
21893                .expect("every update-driven reopen is consumed");
21894        }
21895    }
21896
21897    #[test]
21898    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
21899        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
21900            ("shared", "sha256:first", "shared", "sha256:second"),
21901            ("first", "sha256:shared", "second", "sha256:shared"),
21902            ("shared", "sha256:shared", "shared", "sha256:shared"),
21903            ("first", "sha256:first", "second", "sha256:second"),
21904        ] {
21905            let history = vec![
21906                history_event(
21907                    "ConditionWaitOpened",
21908                    json!({
21909                        "sequence": 3,
21910                        "condition_wait_id": "condition:3",
21911                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21912                        "condition_key": first_key,
21913                        "condition_definition_fingerprint": first_fingerprint,
21914                    }),
21915                ),
21916                history_event(
21917                    "ConditionWaitSatisfied",
21918                    json!({
21919                        "sequence": 3,
21920                        "condition_wait_id": "condition:3",
21921                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21922                        "condition_key": first_key,
21923                        "condition_definition_fingerprint": first_fingerprint,
21924                    }),
21925                ),
21926                history_event(
21927                    "ConditionWaitOpened",
21928                    json!({
21929                        "sequence": 4,
21930                        "condition_wait_id": "condition:4",
21931                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21932                        "condition_key": second_key,
21933                        "condition_definition_fingerprint": second_fingerprint,
21934                    }),
21935                ),
21936                history_event(
21937                    "ConditionWaitSatisfied",
21938                    json!({
21939                        "sequence": 4,
21940                        "condition_wait_id": "condition:4",
21941                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21942                        "condition_key": second_key,
21943                        "condition_definition_fingerprint": second_fingerprint,
21944                    }),
21945                ),
21946            ];
21947            for _cold_worker_or_restart in 0..2 {
21948                let ctx = workflow_context(history.clone());
21949                let mut task_context = TaskContext::from_waker(noop_waker_ref());
21950                let mut first = Box::pin(ctx.wait_condition(
21951                    ConditionWaitOptions::new(first_key, first_fingerprint),
21952                    || Ok(false),
21953                ));
21954                assert!(matches!(
21955                    first.as_mut().poll(&mut task_context),
21956                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21957                ));
21958
21959                let mut second = Box::pin(ctx.wait_condition(
21960                    ConditionWaitOptions::new(second_key, second_fingerprint),
21961                    || Ok(false),
21962                ));
21963                assert!(matches!(
21964                    second.as_mut().poll(&mut task_context),
21965                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21966                ));
21967                assert!(ctx.take_commands().expect("commands").is_empty());
21968                ctx.ensure_history_consumed()
21969                    .expect("each authored wait consumes one occurrence");
21970            }
21971        }
21972    }
21973
21974    #[test]
21975    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
21976        fn worker() -> Worker {
21977            let client = Client::new("http://127.0.0.1:8080").expect("client");
21978            let mut worker = Worker::new(client, "rust-workers");
21979            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
21980                let mut outcomes = Vec::new();
21981                for _ in 0..2 {
21982                    outcomes.push(
21983                        ctx.wait_condition(
21984                            ConditionWaitOptions::new("shared", "sha256:shared"),
21985                            || Ok(false),
21986                        )
21987                        .await?,
21988                    );
21989                }
21990                Ok(json!(outcomes))
21991            });
21992            worker
21993        }
21994
21995        let task = workflow_task(
21996            "rust.condition-loop",
21997            vec![
21998                history_event(
21999                    "ConditionWaitOpened",
22000                    json!({
22001                        "sequence": 1,
22002                        "condition_wait_id": "condition:1",
22003                        "condition_wait_occurrence_id": "rust:condition-wait:0",
22004                        "condition_key": "shared",
22005                        "condition_definition_fingerprint": "sha256:shared",
22006                    }),
22007                ),
22008                history_event(
22009                    "ConditionWaitSatisfied",
22010                    json!({
22011                        "sequence": 1,
22012                        "condition_wait_id": "condition:1",
22013                        "condition_wait_occurrence_id": "rust:condition-wait:0",
22014                        "condition_key": "shared",
22015                        "condition_definition_fingerprint": "sha256:shared",
22016                    }),
22017                ),
22018                history_event(
22019                    "ConditionWaitOpened",
22020                    json!({
22021                        "sequence": 2,
22022                        "condition_wait_id": "condition:2",
22023                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22024                        "condition_key": "shared",
22025                        "condition_definition_fingerprint": "sha256:shared",
22026                    }),
22027                ),
22028                history_event(
22029                    "ConditionWaitSatisfied",
22030                    json!({
22031                        "sequence": 2,
22032                        "condition_wait_id": "condition:2",
22033                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22034                        "condition_key": "shared",
22035                        "condition_definition_fingerprint": "sha256:shared",
22036                    }),
22037                ),
22038            ],
22039            DEFAULT_CODEC,
22040        );
22041
22042        for _cold_worker_or_restart in 0..2 {
22043            let commands = worker()
22044                .execute_workflow_task(task.clone())
22045                .expect("adjacent loop waits replay deterministically");
22046            assert_eq!(commands.len(), 1);
22047            assert_eq!(commands[0]["type"], "complete_workflow");
22048            assert_eq!(
22049                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
22050                json!(["satisfied", "satisfied"])
22051            );
22052        }
22053    }
22054
22055    #[test]
22056    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
22057        let history = vec![history_event(
22058            "ConditionWaitOpened",
22059            json!({
22060                "sequence": 12,
22061                "condition_wait_id": "condition:12",
22062                "condition_wait_occurrence_id": "rust:condition-wait:0",
22063                "condition_key": "approval",
22064                "condition_definition_fingerprint": "sha256:approval-v1",
22065                "timeout_seconds": 30,
22066            }),
22067        )];
22068        for (options, expected_reason) in [
22069            (
22070                ConditionWaitOptions::new("changed", "sha256:approval-v1")
22071                    .timeout(Duration::from_secs(30)),
22072                "condition_wait_key_mismatch",
22073            ),
22074            (
22075                ConditionWaitOptions::new("approval", "sha256:approval-v2")
22076                    .timeout(Duration::from_secs(30)),
22077                "condition_wait_predicate_mismatch",
22078            ),
22079            (
22080                ConditionWaitOptions::new("approval", "sha256:approval-v1")
22081                    .timeout(Duration::from_secs(29)),
22082                "condition_wait_timeout_mismatch",
22083            ),
22084        ] {
22085            let ctx = workflow_context(history.clone());
22086            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
22087            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22088            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22089                wait.as_mut().poll(&mut task_context)
22090            else {
22091                panic!("changed condition definition must fail replay");
22092            };
22093            assert_eq!(failure.reason, expected_reason);
22094            assert_eq!(failure.sequence, Some(12));
22095        }
22096    }
22097
22098    #[test]
22099    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
22100        let error = WorkflowState::new(
22101            vec![history_event(
22102                "ConditionWaitOpened",
22103                json!({
22104                    "sequence": 12,
22105                    "condition_wait_id": "condition:12",
22106                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22107                    "condition_key": "approval",
22108                }),
22109            )],
22110            "rust-workers".to_string(),
22111            DEFAULT_CODEC.to_string(),
22112            None,
22113        )
22114        .expect_err("condition history without a predicate fingerprint must fail");
22115
22116        assert!(matches!(
22117            error,
22118            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22119                if reason == "condition_wait_predicate_fingerprint_missing"
22120        ));
22121    }
22122
22123    #[test]
22124    fn condition_wait_history_requires_authored_occurrence_identity() {
22125        let error = WorkflowState::new(
22126            vec![history_event(
22127                "ConditionWaitOpened",
22128                json!({
22129                    "sequence": 12,
22130                    "condition_wait_id": "condition:12",
22131                    "condition_key": "approval",
22132                    "condition_definition_fingerprint": "sha256:approval-v1",
22133                }),
22134            )],
22135            "rust-workers".to_string(),
22136            DEFAULT_CODEC.to_string(),
22137            None,
22138        )
22139        .expect_err("condition history without occurrence identity must fail");
22140
22141        assert!(matches!(
22142            error,
22143            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22144                if reason == "condition_wait_occurrence_id_missing"
22145        ));
22146    }
22147
22148    #[test]
22149    fn typed_search_attribute_updates_validate_emit_and_replay() {
22150        let update = SearchAttributeUpdate::new()
22151            .keyword("OrderStatus", " waiting ")
22152            .expect("keyword")
22153            .int("Attempt", 3)
22154            .expect("int")
22155            .bool("Escalated", false)
22156            .expect("bool")
22157            .keyword_list("Regions", ["us-east", "eu-west"])
22158            .expect("list")
22159            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
22160            .expect("datetime")
22161            .delete("LegacyStatus")
22162            .expect("delete");
22163        let ctx = workflow_context(Vec::new());
22164        ctx.upsert_search_attributes(update.clone())
22165            .expect("typed update");
22166        assert_eq!(
22167            ctx.take_commands().expect("search-attribute command"),
22168            vec![json!({
22169                "type": "upsert_search_attributes",
22170                "attributes": {
22171                    "Attempt": 3,
22172                    "Escalated": false,
22173                    "LegacyStatus": null,
22174                    "OrderStatus": "waiting",
22175                    "Regions": ["us-east", "eu-west"],
22176                    "UpdatedAt": "2026-08-22T04:00:00Z",
22177                },
22178                "attribute_types": {
22179                    "Attempt": "int",
22180                    "Escalated": "bool",
22181                    "OrderStatus": "keyword",
22182                    "Regions": "keyword_list",
22183                    "UpdatedAt": "datetime",
22184                },
22185            })]
22186        );
22187
22188        let replay = workflow_context(vec![history_event(
22189            "SearchAttributesUpserted",
22190            json!({
22191                "sequence": 6,
22192                "attributes": {
22193                    "Attempt": 3,
22194                    "Escalated": false,
22195                    "LegacyStatus": null,
22196                    "OrderStatus": "waiting",
22197                    "Regions": ["us-east", "eu-west"],
22198                    "UpdatedAt": "2026-08-22T04:00:00Z",
22199                },
22200                "attribute_types": {
22201                    "Attempt": "int",
22202                    "Escalated": "bool",
22203                    "OrderStatus": "keyword",
22204                    "Regions": "keyword_list",
22205                    "UpdatedAt": "datetime",
22206                },
22207                "merged": {},
22208            }),
22209        )]);
22210        replay
22211            .upsert_search_attributes(update)
22212            .expect("matching update replays");
22213        assert!(replay.take_commands().expect("commands").is_empty());
22214        replay.ensure_history_consumed().expect("history consumed");
22215
22216        let type_drift = workflow_context(vec![history_event(
22217            "SearchAttributesUpserted",
22218            json!({
22219                "sequence": 7,
22220                "attributes": {"OrderStatus": "waiting"},
22221                "attribute_types": {"OrderStatus": "keyword"},
22222                "merged": {"OrderStatus": "waiting"},
22223            }),
22224        )]);
22225        let error = type_drift
22226            .upsert_search_attributes(
22227                SearchAttributeUpdate::new()
22228                    .string("OrderStatus", "waiting")
22229                    .expect("string update"),
22230            )
22231            .expect_err("same JSON value with a changed type must fail replay");
22232        assert!(matches!(
22233            error,
22234            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22235                if reason == "search_attribute_type_mismatch"
22236        ));
22237
22238        let malformed_types = WorkflowState::new(
22239            vec![history_event(
22240                "SearchAttributesUpserted",
22241                json!({
22242                    "sequence": 8,
22243                    "attributes": {"OrderStatus": "waiting"},
22244                    "attribute_types": {"OrderStatus": "unsupported"},
22245                    "merged": {"OrderStatus": "waiting"},
22246                }),
22247            )],
22248            "rust-workers".to_string(),
22249            DEFAULT_CODEC.to_string(),
22250            None,
22251        )
22252        .expect_err("unsupported search-attribute type metadata must fail");
22253        assert!(matches!(
22254            malformed_types,
22255            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22256                if reason == "search_attribute_types_malformed"
22257        ));
22258
22259        assert!(matches!(
22260            SearchAttributeUpdate::new().keyword("bad key", "value"),
22261            Err(SearchAttributeUpdateError::InvalidKey(_))
22262        ));
22263        assert!(matches!(
22264            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
22265            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
22266        ));
22267        assert!(matches!(
22268            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
22269            Err(SearchAttributeUpdateError::ValueTooLong { .. })
22270        ));
22271        assert!(matches!(
22272            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
22273            Err(SearchAttributeUpdateError::InvalidDateTime(_))
22274        ));
22275        assert!(matches!(
22276            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
22277            Err(Error::InvalidSearchAttributeUpdate(
22278                SearchAttributeUpdateError::Empty
22279            ))
22280        ));
22281    }
22282
22283    #[test]
22284    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
22285        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
22286        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
22287
22288        assert!(SearchAttributeUpdate::new()
22289            .string("AsciiDescription", ascii)
22290            .is_ok());
22291        assert!(SearchAttributeUpdate::new()
22292            .string("Utf8Description", utf8)
22293            .is_ok());
22294        assert!(matches!(
22295            SearchAttributeUpdate::new().string(
22296                "TooLongDescription",
22297                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
22298            ),
22299            Err(SearchAttributeUpdateError::ValueTooLong {
22300                kind: "string",
22301                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
22302                ..
22303            })
22304        ));
22305    }
22306
22307    #[test]
22308    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
22309        let lone_fire = WorkflowState::new(
22310            vec![history_event(
22311                "TimerFired",
22312                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22313            )],
22314            "rust-workers".to_string(),
22315            DEFAULT_CODEC.to_string(),
22316            None,
22317        )
22318        .expect_err("TimerFired requires TimerScheduled");
22319        assert!(matches!(
22320            lone_fire,
22321            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22322                if reason == "timer_schedule_missing_or_duplicate"
22323        ));
22324
22325        let wrong_identity = WorkflowState::new(
22326            vec![
22327                history_event(
22328                    "TimerScheduled",
22329                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22330                ),
22331                history_event(
22332                    "TimerFired",
22333                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
22334                ),
22335            ],
22336            "rust-workers".to_string(),
22337            DEFAULT_CODEC.to_string(),
22338            None,
22339        )
22340        .expect_err("fire must match scheduled timer identity");
22341        assert!(matches!(
22342            wrong_identity,
22343            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22344                if reason == "timer_identity_mismatch"
22345        ));
22346
22347        let duplicate_fire = WorkflowState::new(
22348            vec![
22349                history_event(
22350                    "TimerScheduled",
22351                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22352                ),
22353                history_event(
22354                    "TimerFired",
22355                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22356                ),
22357                history_event(
22358                    "TimerFired",
22359                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22360                ),
22361            ],
22362            "rust-workers".to_string(),
22363            DEFAULT_CODEC.to_string(),
22364            None,
22365        )
22366        .expect_err("a durable timer cannot fire twice");
22367        assert!(matches!(
22368            duplicate_fire,
22369            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22370                if reason == "duplicate_timer_fire"
22371        ));
22372
22373        let wrong_fired_delay = WorkflowState::new(
22374            vec![
22375                history_event(
22376                    "TimerScheduled",
22377                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22378                ),
22379                history_event(
22380                    "TimerFired",
22381                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
22382                ),
22383            ],
22384            "rust-workers".to_string(),
22385            DEFAULT_CODEC.to_string(),
22386            None,
22387        )
22388        .expect_err("timer schedule and fire delays must agree");
22389        assert!(matches!(
22390            wrong_fired_delay,
22391            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22392                if reason == "timer_history_delay_mismatch"
22393        ));
22394    }
22395
22396    #[test]
22397    fn replay_rejects_activity_moved_before_recorded_timer() {
22398        let ctx = workflow_context(vec![
22399            history_event(
22400                "TimerScheduled",
22401                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22402            ),
22403            history_event(
22404                "TimerFired",
22405                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22406            ),
22407            history_event(
22408                "ActivityCompleted",
22409                json!({
22410                    "sequence": 2,
22411                    "activity_type": "after-timer",
22412                    "payload_codec": DEFAULT_CODEC,
22413                    "result": fixture_envelope(json!("done")),
22414                }),
22415            ),
22416        ]);
22417        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
22418        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22419
22420        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22421            activity.as_mut().poll(&mut task_context)
22422        else {
22423            panic!("reordered durable command must be rejected");
22424        };
22425        assert_eq!(failure.reason, "recorded_command_mismatch");
22426        assert_eq!(failure.sequence, Some(1));
22427        assert_eq!(failure.expected.as_deref(), Some("timer"));
22428        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
22429    }
22430
22431    #[test]
22432    fn workflow_context_emits_a_typed_named_signal_wait() {
22433        let ctx = workflow_context(Vec::new());
22434        let mut signal = Box::pin(ctx.wait_signal("finish"));
22435        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22436
22437        assert!(matches!(
22438            signal.as_mut().poll(&mut task_context),
22439            Poll::Pending
22440        ));
22441        assert_eq!(
22442            ctx.take_commands().expect("signal-wait command"),
22443            vec![json!({
22444                "type": "open_signal_wait",
22445                "signal_name": "finish",
22446            })]
22447        );
22448    }
22449
22450    #[test]
22451    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
22452        let ctx = workflow_context(Vec::new());
22453        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
22454        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22455
22456        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
22457        else {
22458            panic!("runtime-reserved signal should be rejected");
22459        };
22460        assert!(message.contains("reserved by the workflow runtime"));
22461        assert!(ctx.take_commands().expect("commands").is_empty());
22462    }
22463
22464    #[tokio::test]
22465    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
22466        let client = Client::builder("http://127.0.0.1:9")
22467            .build()
22468            .expect("client");
22469        let error = client
22470            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
22471            .await
22472            .expect_err("runtime-reserved signal should be rejected before transport");
22473
22474        assert!(
22475            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
22476        );
22477    }
22478
22479    #[test]
22480    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
22481        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22482            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22483                value.to_string(),
22484            )]))
22485            .expect("message payload");
22486            json!({
22487                "schema": MESSAGE_STREAM_SCHEMA,
22488                "stream_name": "orders",
22489                "message_id": message_id,
22490                "position": position,
22491                "payload_envelope": payload,
22492            })
22493        }
22494
22495        fn opened(sequence: u64) -> HistoryEvent {
22496            history_event(
22497                "SignalWaitOpened",
22498                json!({
22499                    "sequence": sequence,
22500                    "signal_name": MESSAGE_STREAM_SIGNAL,
22501                }),
22502            )
22503        }
22504
22505        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22506            history_event(
22507                "SignalApplied",
22508                json!({
22509                    "sequence": sequence,
22510                    "signal_name": MESSAGE_STREAM_SIGNAL,
22511                    "value": fixture_envelope(json!([delivery])),
22512                }),
22513            )
22514        }
22515
22516        fn received(delivery: Value) -> HistoryEvent {
22517            history_event(
22518                "SignalReceived",
22519                json!({
22520                    "signal_name": MESSAGE_STREAM_SIGNAL,
22521                    "arguments": fixture_envelope(json!([delivery])),
22522                    "payload_codec": DEFAULT_CODEC,
22523                }),
22524            )
22525        }
22526
22527        let client = Client::new("http://127.0.0.1:8080").expect("client");
22528        let mut worker = Worker::new(client, "rust-workers");
22529        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
22530            let messages = ctx.message_stream("orders")?.receive(2).await?;
22531            Ok(json!(messages
22532                .into_iter()
22533                .map(|message| message.message_id)
22534                .collect::<Vec<_>>()))
22535        });
22536
22537        let first = delivery("message-1", 1, "one");
22538        let second = delivery("message-2", 2, "two");
22539        let batch = worker
22540            .execute_workflow_task_decision(workflow_task(
22541                "rust.message-stream-batch",
22542                vec![
22543                    opened(1),
22544                    received(first.clone()),
22545                    applied(1, first.clone()),
22546                    received(first.clone()),
22547                    received(second),
22548                ],
22549                DEFAULT_CODEC,
22550            ))
22551            .expect("worker task consumes the available batch");
22552
22553        assert_eq!(batch.commands.len(), 1);
22554        assert_eq!(batch.commands[0]["type"], "complete_workflow");
22555        assert_eq!(
22556            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
22557                .expect("workflow result"),
22558            json!(["message-1", "message-2"])
22559        );
22560        assert_eq!(
22561            batch.message_stream_cursors,
22562            vec![json!({"stream_name": "orders", "through_position": 2})]
22563        );
22564        assert!(batch.message_stream_waits.is_empty());
22565
22566        let partial = worker
22567            .execute_workflow_task_decision(workflow_task(
22568                "rust.message-stream-batch",
22569                vec![opened(1), received(first.clone()), applied(1, first)],
22570                DEFAULT_CODEC,
22571            ))
22572            .expect("worker task returns without waiting for a missing second item");
22573        assert_eq!(partial.commands.len(), 1);
22574        assert_eq!(partial.commands[0]["type"], "complete_workflow");
22575        assert_eq!(
22576            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
22577                .expect("workflow result"),
22578            json!(["message-1"])
22579        );
22580        assert_eq!(
22581            partial.message_stream_cursors,
22582            vec![json!({"stream_name": "orders", "through_position": 1})]
22583        );
22584        assert!(partial.message_stream_waits.is_empty());
22585    }
22586
22587    #[test]
22588    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
22589        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22590            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22591                value.to_string(),
22592            )]))
22593            .expect("message payload");
22594            json!({
22595                "schema": MESSAGE_STREAM_SCHEMA,
22596                "stream_name": "orders",
22597                "message_id": message_id,
22598                "position": position,
22599                "payload_envelope": payload,
22600            })
22601        }
22602
22603        fn opened(sequence: u64) -> HistoryEvent {
22604            history_event(
22605                "SignalWaitOpened",
22606                json!({
22607                    "sequence": sequence,
22608                    "signal_name": MESSAGE_STREAM_SIGNAL,
22609                }),
22610            )
22611        }
22612
22613        fn received(delivery: Value) -> HistoryEvent {
22614            history_event(
22615                "SignalReceived",
22616                json!({
22617                    "signal_name": MESSAGE_STREAM_SIGNAL,
22618                    "arguments": fixture_envelope(json!([delivery])),
22619                    "payload_codec": DEFAULT_CODEC,
22620                }),
22621            )
22622        }
22623
22624        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22625            history_event(
22626                "SignalApplied",
22627                json!({
22628                    "sequence": sequence,
22629                    "signal_name": MESSAGE_STREAM_SIGNAL,
22630                    "value": fixture_envelope(json!([delivery])),
22631                }),
22632            )
22633        }
22634
22635        let client = Client::new("http://127.0.0.1:8080").expect("client");
22636        let mut worker = Worker::new(client, "rust-workers");
22637        worker.register_workflow(
22638            "rust.message-stream-partial-batches",
22639            |ctx, _input| async move {
22640                let stream = ctx.message_stream("orders")?;
22641                let first = stream.receive(10).await?;
22642                let second = stream.receive(10).await?;
22643                Ok(json!([
22644                    first
22645                        .into_iter()
22646                        .map(|message| message.message_id)
22647                        .collect::<Vec<_>>(),
22648                    second
22649                        .into_iter()
22650                        .map(|message| message.message_id)
22651                        .collect::<Vec<_>>(),
22652                ]))
22653            },
22654        );
22655
22656        let first = delivery("message-1", 1, "one");
22657        let second = delivery("message-2", 2, "two");
22658        let decision = worker
22659            .execute_workflow_task_decision(workflow_task(
22660                "rust.message-stream-partial-batches",
22661                vec![
22662                    opened(1),
22663                    received(first.clone()),
22664                    applied(1, first),
22665                    opened(2),
22666                    received(second.clone()),
22667                    applied(2, second),
22668                ],
22669                DEFAULT_CODEC,
22670            ))
22671            .expect("cold replay preserves both authored receive boundaries");
22672
22673        assert_eq!(decision.commands.len(), 1);
22674        assert_eq!(decision.commands[0]["type"], "complete_workflow");
22675        assert_eq!(
22676            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
22677                .expect("workflow result"),
22678            json!([["message-1"], ["message-2"]])
22679        );
22680        assert_eq!(
22681            decision.message_stream_cursors,
22682            vec![json!({"stream_name": "orders", "through_position": 2})]
22683        );
22684        assert!(decision.message_stream_waits.is_empty());
22685    }
22686
22687    #[test]
22688    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
22689        let ctx = workflow_context(Vec::new());
22690        let stream = ctx.message_stream("orders").expect("message stream");
22691        let mut receive = Box::pin(stream.receive(10));
22692        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22693
22694        assert!(matches!(
22695            receive.as_mut().poll(&mut task_context),
22696            Poll::Pending
22697        ));
22698        assert_eq!(
22699            ctx.take_commands().expect("message-stream wait command"),
22700            vec![json!({
22701                "type": "open_signal_wait",
22702                "signal_name": MESSAGE_STREAM_SIGNAL,
22703            })]
22704        );
22705        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
22706        assert!(cursors.is_empty());
22707        assert_eq!(
22708            waits,
22709            vec![json!({"stream_name": "orders", "after_position": 0})]
22710        );
22711    }
22712
22713    #[test]
22714    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
22715        let ctx = workflow_context(vec![history_event(
22716            "SignalReceived",
22717            json!({
22718                "signal_name": MESSAGE_STREAM_SIGNAL,
22719                "arguments": fixture_envelope(json!([{
22720                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
22721                    "stream_name": "orders",
22722                    "through_position": 2,
22723                }])),
22724                "payload_codec": DEFAULT_CODEC,
22725            }),
22726        )]);
22727        let stream = ctx.message_stream("orders").expect("message stream");
22728        let mut receive = Box::pin(stream.receive(10));
22729        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22730
22731        assert!(matches!(
22732            receive.as_mut().poll(&mut task_context),
22733            Poll::Pending
22734        ));
22735        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
22736        assert_eq!(
22737            cursors,
22738            vec![json!({"stream_name": "orders", "through_position": 2})]
22739        );
22740        assert_eq!(
22741            waits,
22742            vec![json!({"stream_name": "orders", "after_position": 2})]
22743        );
22744    }
22745
22746    #[test]
22747    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
22748        let mut empty_map = BTreeMap::new();
22749        let mut nested = BTreeMap::new();
22750        nested.insert(
22751            "value".to_string(),
22752            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
22753        );
22754        let values = vec![
22755            AvroValue::Bytes(vec![0, 255]),
22756            AvroValue::Long(1),
22757            AvroValue::Double(1.0),
22758            AvroValue::Array(Vec::new()),
22759            AvroValue::Map(std::mem::take(&mut empty_map)),
22760            AvroValue::Map(nested),
22761        ];
22762        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
22763        let transport = vec![json!({
22764            "schema": MESSAGE_STREAM_SCHEMA,
22765            "stream_name": "orders",
22766            "message_id": "message-1",
22767            "position": 1,
22768            "payload_envelope": payload,
22769        })];
22770
22771        for _ in 0..2 {
22772            let Some(MessageStreamDelivery::Message(message)) =
22773                decode_message_stream_delivery(transport.clone()).expect("delivery")
22774            else {
22775                panic!("message delivery expected");
22776            };
22777            assert_eq!(message.arguments, values);
22778            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
22779            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
22780        }
22781    }
22782
22783    #[test]
22784    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
22785        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22786            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22787                value.to_string(),
22788            )]))
22789            .expect("message payload");
22790            json!({
22791                "schema": MESSAGE_STREAM_SCHEMA,
22792                "stream_name": "orders",
22793                "message_id": message_id,
22794                "position": position,
22795                "payload_envelope": payload,
22796            })
22797        }
22798
22799        fn opened(sequence: u64) -> HistoryEvent {
22800            history_event(
22801                "SignalWaitOpened",
22802                json!({
22803                    "sequence": sequence,
22804                    "signal_name": MESSAGE_STREAM_SIGNAL,
22805                }),
22806            )
22807        }
22808
22809        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22810            history_event(
22811                "SignalApplied",
22812                json!({
22813                    "sequence": sequence,
22814                    "signal_name": MESSAGE_STREAM_SIGNAL,
22815                    "value": fixture_envelope(json!([delivery])),
22816                }),
22817            )
22818        }
22819
22820        fn worker() -> Worker {
22821            let client = Client::new("http://127.0.0.1:8080").expect("client");
22822            let mut worker = Worker::new(client, "rust-workers");
22823            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
22824                let stream = ctx.message_stream("orders")?;
22825                let first = stream.receive_one().await?;
22826                let second = stream.receive_one().await?;
22827                Ok(json!([first.message_id, second.message_id]))
22828            });
22829            worker
22830        }
22831
22832        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
22833            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
22834            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
22835            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
22836            task
22837        }
22838
22839        let waiting = worker()
22840            .execute_workflow_task_decision(workflow_task(
22841                "rust.message-stream",
22842                Vec::new(),
22843                DEFAULT_CODEC,
22844            ))
22845            .expect("first worker opens the stream wait");
22846        assert_eq!(
22847            waiting.commands,
22848            vec![json!({
22849                "type": "open_signal_wait",
22850                "signal_name": MESSAGE_STREAM_SIGNAL,
22851            })]
22852        );
22853        assert!(waiting.message_stream_cursors.is_empty());
22854        assert_eq!(
22855            waiting.message_stream_waits,
22856            vec![json!({"stream_name": "orders", "after_position": 0})]
22857        );
22858
22859        let first_delivery = delivery("message-1", 1, "one");
22860        let first_arrival = worker()
22861            .execute_workflow_task_decision(task_with_resume(
22862                vec![opened(1)],
22863                first_delivery.clone(),
22864            ))
22865            .expect("replacement worker consumes the first arrival");
22866        assert_eq!(
22867            first_arrival.commands,
22868            vec![json!({
22869                "type": "open_signal_wait",
22870                "signal_name": MESSAGE_STREAM_SIGNAL,
22871            })]
22872        );
22873        assert_eq!(
22874            first_arrival.message_stream_cursors,
22875            vec![json!({"stream_name": "orders", "through_position": 1})]
22876        );
22877        assert_eq!(
22878            first_arrival.message_stream_waits,
22879            vec![json!({"stream_name": "orders", "after_position": 1})]
22880        );
22881
22882        let second_delivery = delivery("message-2", 2, "two");
22883        let first_applied = applied(1, first_delivery);
22884        let completed = worker()
22885            .execute_workflow_task_decision(task_with_resume(
22886                vec![opened(1), first_applied.clone(), opened(2)],
22887                second_delivery.clone(),
22888            ))
22889            .expect("next replacement worker consumes the second arrival");
22890        assert_eq!(completed.commands.len(), 1);
22891        assert_eq!(completed.commands[0]["type"], "complete_workflow");
22892        assert_eq!(
22893            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
22894                .expect("workflow result"),
22895            json!(["message-1", "message-2"])
22896        );
22897        assert_eq!(
22898            completed.message_stream_cursors,
22899            vec![json!({"stream_name": "orders", "through_position": 2})]
22900        );
22901        assert!(completed.message_stream_waits.is_empty());
22902
22903        let replay_history = vec![
22904            opened(1),
22905            first_applied,
22906            opened(2),
22907            applied(2, second_delivery),
22908        ];
22909        for _cold_worker_or_restart in 0..2 {
22910            let replayed = worker()
22911                .execute_workflow_task_decision(workflow_task(
22912                    "rust.message-stream",
22913                    replay_history.clone(),
22914                    DEFAULT_CODEC,
22915                ))
22916                .expect("cold worker replays each logical message exactly once");
22917            assert_eq!(replayed.commands.len(), 1);
22918            assert_eq!(
22919                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
22920                    .expect("replayed workflow result"),
22921                json!(["message-1", "message-2"])
22922            );
22923            assert_eq!(
22924                replayed.message_stream_cursors,
22925                vec![json!({"stream_name": "orders", "through_position": 2})]
22926            );
22927            assert!(replayed.message_stream_waits.is_empty());
22928        }
22929    }
22930
22931    #[test]
22932    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
22933        assert!(!worker_protocol_supports_message_streams("1.14"));
22934        assert!(worker_protocol_supports_message_streams("1.15"));
22935        assert!(worker_protocol_supports_message_streams("1.16"));
22936        assert!(worker_protocol_supports_message_streams(
22937            WORKER_PROTOCOL_VERSION
22938        ));
22939        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
22940    }
22941
22942    #[test]
22943    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
22944        let ctx = workflow_context(vec![
22945            history_event(
22946                "ConditionWaitOpened",
22947                json!({
22948                    "sequence": 1,
22949                    "condition_wait_id": "condition:1",
22950                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22951                    "condition_key": "signal:finish",
22952                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
22953                }),
22954            ),
22955            history_event(
22956                "ConditionWaitSatisfied",
22957                json!({
22958                    "sequence": 1,
22959                    "condition_wait_id": "condition:1",
22960                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22961                    "condition_key": "signal:finish",
22962                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
22963                }),
22964            ),
22965            history_event(
22966                "SignalReceived",
22967                json!({"signal_name": "finish", "arguments": []}),
22968            ),
22969        ]);
22970        let mut signal = Box::pin(ctx.wait_signal("finish"));
22971        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22972
22973        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22974            signal.as_mut().poll(&mut task_context)
22975        else {
22976            panic!("condition history must not resolve as a typed signal wait");
22977        };
22978        assert_eq!(failure.reason, "recorded_command_mismatch");
22979        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
22980    }
22981
22982    #[test]
22983    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
22984        let signal_then_timer = vec![
22985            history_event(
22986                "SignalWaitOpened",
22987                json!({"sequence": 1, "signal_name": "go"}),
22988            ),
22989            history_event(
22990                "SignalApplied",
22991                json!({
22992                    "sequence": 1,
22993                    "signal_name": "go",
22994                    "value": fixture_envelope(json!(["now"])),
22995                }),
22996            ),
22997            history_event(
22998                "TimerScheduled",
22999                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
23000            ),
23001            history_event(
23002                "TimerFired",
23003                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
23004            ),
23005        ];
23006
23007        let ctx = workflow_context(signal_then_timer.clone());
23008        let mut signal = Box::pin(ctx.wait_signal("go"));
23009        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23010        assert!(matches!(
23011            signal.as_mut().poll(&mut task_context),
23012            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
23013        ));
23014        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
23015        assert!(matches!(
23016            timer.as_mut().poll(&mut task_context),
23017            Poll::Ready(Ok(()))
23018        ));
23019        ctx.ensure_history_consumed()
23020            .expect("signal and timer history consumed in order");
23021
23022        let reordered = workflow_context(signal_then_timer);
23023        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
23024        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23025            timer_first.as_mut().poll(&mut task_context)
23026        else {
23027            panic!("timer cannot consume signal-wait-first history");
23028        };
23029        assert_eq!(failure.reason, "recorded_command_mismatch");
23030        assert_eq!(failure.sequence, Some(1));
23031        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
23032
23033        let timer_then_signal = vec![
23034            history_event(
23035                "TimerScheduled",
23036                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23037            ),
23038            history_event(
23039                "TimerFired",
23040                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23041            ),
23042            history_event(
23043                "SignalWaitOpened",
23044                json!({"sequence": 2, "signal_name": "go"}),
23045            ),
23046            history_event(
23047                "SignalApplied",
23048                json!({
23049                    "sequence": 2,
23050                    "signal_name": "go",
23051                    "value": fixture_envelope(json!([])),
23052                }),
23053            ),
23054        ];
23055        let reordered = workflow_context(timer_then_signal);
23056        let mut signal_first = Box::pin(reordered.wait_signal("go"));
23057        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23058            signal_first.as_mut().poll(&mut task_context)
23059        else {
23060            panic!("signal wait cannot consume timer-first history");
23061        };
23062        assert_eq!(failure.reason, "recorded_command_mismatch");
23063        assert_eq!(failure.sequence, Some(1));
23064        assert_eq!(failure.expected.as_deref(), Some("timer"));
23065    }
23066
23067    #[test]
23068    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
23069        let duplicate_timer = WorkflowState::new(
23070            vec![
23071                history_event(
23072                    "TimerScheduled",
23073                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23074                ),
23075                history_event(
23076                    "TimerScheduled",
23077                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23078                ),
23079            ],
23080            "rust-workers".to_string(),
23081            DEFAULT_CODEC.to_string(),
23082            None,
23083        )
23084        .expect_err("one workflow sequence cannot schedule two timers");
23085        assert!(matches!(
23086            duplicate_timer,
23087            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23088                if reason == "timer_schedule_missing_or_duplicate"
23089        ));
23090
23091        let colliding_kinds = WorkflowState::new(
23092            vec![
23093                history_event(
23094                    "TimerScheduled",
23095                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23096                ),
23097                history_event(
23098                    "ActivityCompleted",
23099                    json!({"sequence": 1, "activity_type": "same-sequence"}),
23100                ),
23101            ],
23102            "rust-workers".to_string(),
23103            DEFAULT_CODEC.to_string(),
23104            None,
23105        )
23106        .expect_err("one workflow sequence cannot identify two command kinds");
23107        assert!(matches!(
23108            colliding_kinds,
23109            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23110                if reason == "durable_command_sequence_collision"
23111        ));
23112
23113        let duplicate_signal_wait = WorkflowState::new(
23114            vec![
23115                history_event(
23116                    "SignalWaitOpened",
23117                    json!({"sequence": 1, "signal_name": "go"}),
23118                ),
23119                history_event(
23120                    "SignalWaitOpened",
23121                    json!({"sequence": 1, "signal_name": "go"}),
23122                ),
23123            ],
23124            "rust-workers".to_string(),
23125            DEFAULT_CODEC.to_string(),
23126            None,
23127        )
23128        .expect_err("one workflow sequence cannot open two signal waits");
23129        assert!(matches!(
23130            duplicate_signal_wait,
23131            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23132                if reason == "signal_wait_open_missing_or_duplicate"
23133        ));
23134    }
23135
23136    #[test]
23137    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
23138        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
23139            .expect("side-effect result");
23140        let ctx = workflow_context(vec![history_event(
23141            "SideEffectRecorded",
23142            json!({"sequence": 99, "result": result}),
23143        )]);
23144
23145        let replayed: Value = ctx
23146            .side_effect(|| panic!("recorded side effect must not run"))
23147            .expect("positive global workflow sequence is valid");
23148        assert_eq!(replayed, json!({"captured": true}));
23149        ctx.ensure_history_consumed().expect("history consumed");
23150    }
23151
23152    #[test]
23153    fn workflow_history_rejects_zero_and_descending_command_sequences() {
23154        let result =
23155            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
23156        let zero = WorkflowState::new(
23157            vec![history_event(
23158                "SideEffectRecorded",
23159                json!({"sequence": 0, "result": result.clone()}),
23160            )],
23161            "rust-workers".to_string(),
23162            DEFAULT_CODEC.to_string(),
23163            None,
23164        )
23165        .expect_err("durable command sequences must be positive");
23166        assert!(matches!(
23167            zero,
23168            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23169                if reason == "durable_command_sequence_invalid"
23170        ));
23171
23172        let descending = WorkflowState::new(
23173            vec![
23174                history_event(
23175                    "SideEffectRecorded",
23176                    json!({"sequence": 3, "result": result}),
23177                ),
23178                history_event(
23179                    "VersionMarkerRecorded",
23180                    json!({
23181                        "sequence": 2,
23182                        "change_id": "descending-marker",
23183                        "version": 1,
23184                        "min_supported": 1,
23185                        "max_supported": 1,
23186                    }),
23187                ),
23188            ],
23189            "rust-workers".to_string(),
23190            DEFAULT_CODEC.to_string(),
23191            None,
23192        )
23193        .expect_err("new durable commands must remain strictly ordered");
23194        let Error::NonDeterministicReplay(failure) = descending else {
23195            panic!("expected typed replay failure");
23196        };
23197        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
23198        assert_eq!(failure.sequence, Some(2));
23199        assert_eq!(
23200            failure.expected.as_deref(),
23201            Some("workflow sequence greater than 3")
23202        );
23203        assert_eq!(failure.actual.as_deref(), Some("2"));
23204    }
23205
23206    #[test]
23207    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
23208        fn worker() -> Worker {
23209            let client = Client::new("http://127.0.0.1:8080").expect("client");
23210            let mut worker = Worker::new(client, "rust-workers");
23211            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
23212                ctx.wait_signal("finish").await?;
23213                let marker: String =
23214                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
23215                assert_eq!(marker, "after-finish");
23216                Ok(json!("finished"))
23217            });
23218            worker
23219        }
23220
23221        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
23222            .expect("side-effect result");
23223        let task = workflow_task(
23224            "rust.finish-after-gaps",
23225            vec![
23226                history_event(
23227                    "SignalWaitOpened",
23228                    json!({"sequence": 1, "signal_name": "finish"}),
23229                ),
23230                history_event(
23231                    "SignalReceived",
23232                    json!({
23233                        "signal_id": "increment-3",
23234                        "signal_name": "increment",
23235                        "workflow_sequence": 2,
23236                        "payload_codec": DEFAULT_CODEC,
23237                        "arguments": fixture_envelope(json!([3])),
23238                    }),
23239                ),
23240                history_event(
23241                    "SignalReceived",
23242                    json!({
23243                        "signal_id": "increment-5",
23244                        "signal_name": "increment",
23245                        "workflow_sequence": 3,
23246                        "payload_codec": DEFAULT_CODEC,
23247                        "arguments": fixture_envelope(json!([5])),
23248                    }),
23249                ),
23250                history_event(
23251                    "SignalReceived",
23252                    json!({
23253                        "signal_id": "finish",
23254                        "signal_name": "finish",
23255                        "workflow_sequence": 4,
23256                        "payload_codec": DEFAULT_CODEC,
23257                        "arguments": fixture_envelope(json!([])),
23258                    }),
23259                ),
23260                history_event(
23261                    "SignalApplied",
23262                    json!({
23263                        "sequence": 1,
23264                        "signal_id": "finish",
23265                        "signal_name": "finish",
23266                        "payload_codec": DEFAULT_CODEC,
23267                        "value": fixture_envelope(json!([])),
23268                    }),
23269                ),
23270                history_event(
23271                    "SideEffectRecorded",
23272                    json!({"sequence": 5, "result": marker}),
23273                ),
23274            ],
23275            DEFAULT_CODEC,
23276        );
23277
23278        for _original_or_cold_worker in 0..2 {
23279            let commands = worker()
23280                .execute_workflow_task(task.clone())
23281                .expect("signal gaps preserve deterministic replay");
23282            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
23283            assert_eq!(commands[0]["type"], "complete_workflow");
23284            assert_eq!(
23285                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23286                json!("finished")
23287            );
23288        }
23289    }
23290
23291    #[test]
23292    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
23293        let ctx = workflow_context(Vec::new());
23294        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
23295        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23296        assert!(matches!(
23297            sleep.as_mut().poll(&mut task_context),
23298            Poll::Ready(Err(Error::TimerDurationOverflow))
23299        ));
23300        assert!(ctx.take_commands().expect("commands").is_empty());
23301    }
23302
23303    #[test]
23304    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
23305        let entries = AvroValue::Map(BTreeMap::from([
23306            ("text".to_string(), AvroValue::String("same".to_string())),
23307            (
23308                "nested".to_string(),
23309                AvroValue::Map(BTreeMap::from([
23310                    ("beta".to_string(), AvroValue::Long(2)),
23311                    ("alpha".to_string(), AvroValue::Long(1)),
23312                ])),
23313            ),
23314            ("long".to_string(), AvroValue::Long(7)),
23315            ("double".to_string(), AvroValue::Double(7.0)),
23316            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
23317        ]));
23318        let ctx = workflow_context(Vec::new());
23319        ctx.upsert_memo(entries.clone()).expect("valid memo update");
23320        let commands = ctx.take_commands().expect("commands");
23321
23322        assert_eq!(commands.len(), 1);
23323        assert_eq!(commands[0]["type"], "upsert_memo");
23324        let server_entries = json!({
23325            "codec": "avro",
23326            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
23327        });
23328        assert_eq!(
23329            commands[0]["entries"]
23330                .as_object()
23331                .expect("entries envelope")
23332                .keys()
23333                .collect::<Vec<_>>(),
23334            vec!["blob", "codec"]
23335        );
23336        assert_eq!(commands[0]["entries"], server_entries);
23337        let wire_entries =
23338            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
23339        assert_eq!(wire_entries, entries);
23340
23341        let history = vec![history_event(
23342            "MemoUpserted",
23343            json!({
23344                "sequence": 1,
23345                "entries": server_entries.clone(),
23346                "merged": server_entries,
23347            }),
23348        )];
23349        let replay = workflow_context(history.clone());
23350        replay
23351            .upsert_memo(entries.clone())
23352            .expect("matching replay identity");
23353        assert!(replay.take_commands().expect("replay commands").is_empty());
23354
23355        let changed_types = AvroValue::Map(BTreeMap::from([
23356            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
23357            (
23358                "nested".to_string(),
23359                AvroValue::Map(BTreeMap::from([
23360                    ("alpha".to_string(), AvroValue::Long(1)),
23361                    ("beta".to_string(), AvroValue::Long(2)),
23362                ])),
23363            ),
23364            ("long".to_string(), AvroValue::Double(7.0)),
23365            ("double".to_string(), AvroValue::Long(7)),
23366            ("binary".to_string(), AvroValue::String("same".to_string())),
23367        ]));
23368        let error = workflow_context(history)
23369            .upsert_memo(changed_types)
23370            .expect_err("memo replay identity must preserve Avro value types");
23371        assert!(matches!(
23372            error,
23373            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23374        ));
23375    }
23376
23377    #[test]
23378    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
23379        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
23380            .expect("memo envelope");
23381        let replay = workflow_context(vec![history_event(
23382            "MemoUpserted",
23383            json!({
23384                "sequence": 1,
23385                "entries": original.clone(),
23386                "merged": original
23387            }),
23388        )]);
23389        let error = replay
23390            .upsert_memo(json!({"stage": "changed"}))
23391            .expect_err("changed memo update must fail replay");
23392        assert!(matches!(
23393            error,
23394            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23395        ));
23396
23397        let invalid = workflow_context(Vec::new())
23398            .upsert_memo(
23399                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
23400            )
23401            .expect_err("oversized key");
23402        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
23403    }
23404
23405    #[test]
23406    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
23407        let negative_zero = AvroValue::Map(BTreeMap::from([(
23408            "reading".to_string(),
23409            AvroValue::Double(-0.0),
23410        )]));
23411        let negative_zero_envelope =
23412            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
23413        let history = vec![history_event(
23414            "MemoUpserted",
23415            json!({
23416                "sequence": 1,
23417                "entries": negative_zero_envelope.clone(),
23418                "merged": negative_zero_envelope,
23419            }),
23420        )];
23421
23422        workflow_context(history.clone())
23423            .upsert_memo(negative_zero)
23424            .expect("matching negative-zero history identity");
23425
23426        let error = workflow_context(history)
23427            .upsert_memo(AvroValue::Map(BTreeMap::from([(
23428                "reading".to_string(),
23429                AvroValue::Double(0.0),
23430            )])))
23431            .expect_err("positive zero must not consume negative-zero memo history");
23432        assert!(matches!(
23433            error,
23434            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23435        ));
23436    }
23437
23438    #[test]
23439    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
23440        let supported = json!({
23441            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
23442            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
23443        });
23444        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
23445        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
23446            "workflow_memo_updates": {"supported": false},
23447            "supported_workflow_task_commands": ["upsert_memo"]
23448        }))));
23449        assert!(commands_use_workflow_memo_updates(&[json!({
23450            "type": "upsert_memo",
23451            "entries": {"stage": "processing"}
23452        })]));
23453    }
23454
23455    #[test]
23456    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
23457        let client = Client::new("http://127.0.0.1:8080").expect("client");
23458        let mut worker = Worker::new(client, "rust-workers");
23459        worker.register_workflow("rust.timer", |ctx, _input| async move {
23460            ctx.sleep(Duration::from_secs(5)).await?;
23461            ctx.activity("after-timer", json!([])).await
23462        });
23463
23464        let task = |history_events| WorkflowTask {
23465            task_id: "wft-rust-timer-1".to_string(),
23466            workflow_command_id: None,
23467            workflow_id: Some("wf-rust-timer".to_string()),
23468            run_id: Some("run-rust-timer".to_string()),
23469            workflow_type: "rust.timer".to_string(),
23470            cancel_requested: false,
23471            payload_codec: DEFAULT_CODEC.to_string(),
23472            arguments: Some(
23473                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23474            ),
23475            history_events,
23476            total_history_events: None,
23477            history_size_bytes: None,
23478            continue_as_new_recommended: None,
23479            history_budget_pressure: None,
23480            next_history_page_token: None,
23481            workflow_task_attempt: 1,
23482            workflow_signal_id: None,
23483            signal_name: None,
23484            signal_arguments: None,
23485            workflow_update_id: None,
23486            update_name: None,
23487            lease_owner: Some("rust-worker".to_string()),
23488        };
23489
23490        let initial = worker
23491            .execute_workflow_task(task(Vec::new()))
23492            .expect("initial timer task");
23493        assert_eq!(
23494            initial,
23495            vec![json!({"type": "start_timer", "delay_seconds": 5})]
23496        );
23497
23498        let activity_result =
23499            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
23500        let replayed = worker
23501            .execute_workflow_task(task(vec![
23502                history_event(
23503                    "TimerScheduled",
23504                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23505                ),
23506                history_event(
23507                    "TimerFired",
23508                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23509                ),
23510                history_event(
23511                    "ActivityCompleted",
23512                    json!({
23513                        "sequence": 2,
23514                        "activity_type": "after-timer",
23515                        "payload_codec": DEFAULT_CODEC,
23516                        "result": activity_result,
23517                    }),
23518                ),
23519            ]))
23520            .expect("replayed workflow task");
23521        assert_eq!(replayed.len(), 1);
23522        assert_eq!(replayed[0]["type"], "complete_workflow");
23523        assert_eq!(
23524            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
23525            json!("done")
23526        );
23527    }
23528
23529    #[test]
23530    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
23531        let client = Client::new("http://127.0.0.1:8080").expect("client");
23532        let mut worker = Worker::new(client, "rust-workers");
23533        worker.register_workflow("rust.continue", |ctx, _input| async move {
23534            ctx.continue_as_new_with_options(
23535                ContinueAsNewOptions::new()
23536                    .workflow_type("rust.next")
23537                    .task_queue("next-workers"),
23538                json!([2, {"cursor": "next"}]),
23539            )
23540        });
23541
23542        let commands = worker
23543            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
23544            .expect("continue-as-new command");
23545
23546        assert_eq!(commands.len(), 1);
23547        assert_eq!(commands[0]["type"], "continue_as_new");
23548        assert_eq!(commands[0]["workflow_type"], "rust.next");
23549        assert_eq!(commands[0]["queue"], "next-workers");
23550        assert_eq!(
23551            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
23552                .expect("continue-as-new arguments"),
23553            json!([2, {"cursor": "next"}])
23554        );
23555    }
23556
23557    #[test]
23558    fn continue_as_new_preserves_typed_arguments() {
23559        let client = Client::new("http://127.0.0.1:8080").expect("client");
23560        let mut worker = Worker::new(client, "rust-workers");
23561        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
23562            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
23563            unreachable!("continue-as-new returns a control-flow error")
23564        });
23565
23566        let commands = worker
23567            .execute_workflow_task(workflow_task(
23568                "rust.typed-continue",
23569                Vec::new(),
23570                DEFAULT_CODEC,
23571            ))
23572            .expect("typed continue-as-new command");
23573
23574        assert_eq!(commands[0]["type"], "continue_as_new");
23575        assert_eq!(
23576            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
23577                .expect("typed continue arguments"),
23578            AvroValue::Array(vec![typed_fidelity_probe()])
23579        );
23580    }
23581
23582    #[test]
23583    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
23584        let client = Client::new("http://127.0.0.1:8080").expect("client");
23585        let mut worker = Worker::new(client, "rust-workers");
23586        worker.register_workflow("rust.continue", |ctx, _input| async move {
23587            ctx.continue_as_new(json!([2]))
23588        });
23589        let task = workflow_task(
23590            "rust.continue",
23591            vec![history_event(
23592                "WorkflowContinuedAsNew",
23593                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
23594            )],
23595            DEFAULT_CODEC,
23596        );
23597
23598        for _worker_restart_or_redelivery in 0..2 {
23599            let commands = worker
23600                .execute_workflow_task(task.clone())
23601                .expect("recorded transition replays");
23602            assert!(
23603                commands.is_empty(),
23604                "replay must not emit another successor"
23605            );
23606        }
23607    }
23608
23609    #[test]
23610    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
23611        let ctx = workflow_context(Vec::new());
23612        let error = ctx
23613            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
23614            .expect_err("blank queue must be rejected");
23615
23616        let Error::InvalidContinueAsNewOptions(error) = error else {
23617            panic!("expected typed continue-as-new validation error");
23618        };
23619        assert_eq!(error.field, "task_queue");
23620        assert!(ctx.take_commands().expect("commands").is_empty());
23621    }
23622
23623    #[test]
23624    fn workflow_context_exposes_server_history_budget() {
23625        let client = Client::new("http://127.0.0.1:8080").expect("client");
23626        let mut worker = Worker::new(client, "rust-workers");
23627        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
23628            let budget = ctx.history_budget()?;
23629            Ok(json!({
23630                "events": budget.event_count,
23631                "bytes": budget.size_bytes,
23632                "recommended": budget.continue_as_new_recommended,
23633                "pressure": budget.pressure,
23634            }))
23635        });
23636        let task: WorkflowTask = serde_json::from_value(json!({
23637            "task_id": "task-history-budget",
23638            "workflow_type": "rust.history-budget",
23639            "payload_codec": DEFAULT_CODEC,
23640            "history_events": [],
23641            "total_history_events": 480,
23642            "history_size_bytes": 1_048_576,
23643            "continue_as_new_recommended": true,
23644            "history_budget_pressure": "continue_as_new_recommended",
23645        }))
23646        .expect("published workflow task");
23647
23648        let commands = worker
23649            .execute_workflow_task(task)
23650            .expect("history-budget workflow");
23651        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
23652        assert_eq!(result["events"], 480);
23653        assert_eq!(result["bytes"], 1_048_576);
23654        assert_eq!(result["recommended"], true);
23655        assert_eq!(result["pressure"], "continue_as_new_recommended");
23656    }
23657
23658    #[test]
23659    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
23660        let client = Client::new("http://127.0.0.1:8080").expect("client");
23661        let mut worker = Worker::new(client, "rust-workers");
23662        worker.register_workflow("rust.failing", |_ctx, _input| async move {
23663            Err(Error::Codec("rust_conformance_failure".to_string()))
23664        });
23665        let task = WorkflowTask {
23666            task_id: "wft-rust-failing-1".to_string(),
23667            workflow_command_id: None,
23668            workflow_id: Some("wf-rust-failing".to_string()),
23669            run_id: Some("run-rust-failing".to_string()),
23670            workflow_type: "rust.failing".to_string(),
23671            cancel_requested: false,
23672            payload_codec: DEFAULT_CODEC.to_string(),
23673            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
23674            history_events: Vec::new(),
23675            total_history_events: Some(0),
23676            history_size_bytes: None,
23677            continue_as_new_recommended: None,
23678            history_budget_pressure: None,
23679            next_history_page_token: None,
23680            workflow_task_attempt: 1,
23681            workflow_signal_id: None,
23682            signal_name: None,
23683            signal_arguments: None,
23684            workflow_update_id: None,
23685            update_name: None,
23686            lease_owner: Some("rust-worker".to_string()),
23687        };
23688
23689        let commands = worker
23690            .execute_workflow_task(task)
23691            .expect("handler failure becomes a workflow command");
23692
23693        assert_eq!(commands.len(), 1);
23694        assert_eq!(commands[0]["type"], "fail_workflow");
23695        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
23696        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
23697        assert_eq!(commands[0]["non_retryable"], false);
23698        assert_eq!(
23699            commands[0]["message"],
23700            "codec error: rust_conformance_failure"
23701        );
23702        assert_eq!(
23703            commands[0]["exception"]["message"],
23704            "codec error: rust_conformance_failure"
23705        );
23706    }
23707
23708    #[test]
23709    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
23710        let client = Client::new("http://127.0.0.1:8080").expect("client");
23711        let mut worker = Worker::new(client, "rust-workers");
23712        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
23713            let _: String = ctx.side_effect(|| "captured".to_string())?;
23714            Err(Error::WorkerLoop("application failure".to_string()))
23715        });
23716
23717        let commands = worker
23718            .execute_workflow_task(workflow_task(
23719                "rust.failing-after-side-effect",
23720                Vec::new(),
23721                DEFAULT_CODEC,
23722            ))
23723            .expect("ordinary failure remains a workflow decision");
23724
23725        assert_eq!(commands.len(), 2);
23726        assert_eq!(commands[0]["type"], "record_side_effect");
23727        assert_eq!(commands[1]["type"], "fail_workflow");
23728    }
23729
23730    #[test]
23731    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
23732        let client = Client::new("http://127.0.0.1:8080").expect("client");
23733        let mut worker = Worker::new(client, "rust-workers");
23734        worker.register_workflow("rust.redrive", |ctx, _input| async move {
23735            ctx.activity("greet", json!([])).await?;
23736            Ok(Value::Null)
23737        });
23738        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
23739            match ctx.activity("greet", json!([])).await {
23740                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
23741                result => result,
23742            }
23743        });
23744
23745        let failed = history_event(
23746            "ActivityFailed",
23747            json!({
23748                "sequence": 1,
23749                "activity_type": "greet",
23750                "activity_execution_id": "activity-1",
23751                "message": "failed"
23752            }),
23753        );
23754        let commands = worker
23755            .execute_workflow_task(workflow_task(
23756                "rust.redrive",
23757                vec![failed.clone()],
23758                DEFAULT_CODEC,
23759            ))
23760            .expect("recorded failure becomes a workflow command");
23761        assert_eq!(commands[0]["type"], "fail_workflow");
23762        assert_eq!(commands[0]["failed_step_sequence"], 1);
23763        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
23764
23765        let translated = worker
23766            .execute_workflow_task(workflow_task(
23767                "rust.redrive-translated",
23768                vec![failed],
23769                DEFAULT_CODEC,
23770            ))
23771            .expect("translated failure becomes a workflow command");
23772        assert_eq!(translated[0]["type"], "fail_workflow");
23773        assert!(translated[0].get("failed_step_sequence").is_none());
23774        assert!(translated[0].get("failed_activity_execution_id").is_none());
23775
23776        let without_identity = worker
23777            .execute_workflow_task(workflow_task(
23778                "rust.redrive",
23779                vec![history_event(
23780                    "ActivityFailed",
23781                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
23782                )],
23783                DEFAULT_CODEC,
23784            ))
23785            .expect("incomplete identity still fails the workflow");
23786        assert!(without_identity[0].get("failed_step_sequence").is_none());
23787
23788        let timed_out = worker
23789            .execute_workflow_task(workflow_task(
23790                "rust.redrive",
23791                vec![history_event(
23792                    "ActivityTimedOut",
23793                    json!({
23794                        "sequence": 1,
23795                        "activity_type": "greet",
23796                        "activity_execution_id": "activity-timeout",
23797                    }),
23798                )],
23799                DEFAULT_CODEC,
23800            ))
23801            .expect("timeout still fails the workflow");
23802        assert!(timed_out[0].get("failed_step_sequence").is_none());
23803    }
23804
23805    #[test]
23806    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
23807        let client = Client::new("http://127.0.0.1:8080").expect("client");
23808        let mut worker = Worker::new(client, "rust-workers");
23809        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
23810            let first = ctx.activity("first", json!([])).await?;
23811            let second = ctx.activity("second", json!([first.clone()])).await?;
23812            Ok(json!({"first": first, "second": second}))
23813        });
23814        let first = history_event(
23815            "ActivityCompleted",
23816            json!({
23817                "sequence": 1,
23818                "activity_type": "first",
23819                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
23820                "payload_codec": DEFAULT_CODEC,
23821                "reused_from_run_id": "failed-run",
23822                "reused_activity_execution_id": "original-first",
23823            }),
23824        );
23825
23826        let retry = worker
23827            .execute_workflow_task(workflow_task(
23828                "rust.redrive-successor",
23829                vec![first.clone()],
23830                DEFAULT_CODEC,
23831            ))
23832            .expect("reused result replays before failed step");
23833        assert_eq!(retry.len(), 1);
23834        assert_eq!(retry[0]["type"], "schedule_activity");
23835        assert_eq!(retry[0]["activity_type"], "second");
23836        assert_eq!(
23837            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
23838            json!(["recorded"]),
23839        );
23840
23841        let second = history_event(
23842            "ActivityCompleted",
23843            json!({
23844                "sequence": 2,
23845                "activity_type": "second",
23846                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
23847                "payload_codec": DEFAULT_CODEC,
23848            }),
23849        );
23850        let completed = worker
23851            .execute_workflow_task(workflow_task(
23852                "rust.redrive-successor",
23853                vec![first, second],
23854                DEFAULT_CODEC,
23855            ))
23856            .expect("retried step completes the successor");
23857        assert_eq!(completed.len(), 1);
23858        assert_eq!(completed[0]["type"], "complete_workflow");
23859        assert_eq!(
23860            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
23861            json!({"first": "recorded", "second": "retried"}),
23862        );
23863    }
23864
23865    #[test]
23866    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
23867        let client = Client::new("http://127.0.0.1:8080").expect("client");
23868        let mut worker = Worker::new(client, "rust-workers");
23869        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
23870            Err(Error::WorkerLoop("application failure".to_string()))
23871        });
23872        let result =
23873            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
23874
23875        let error = worker
23876            .execute_workflow_task(workflow_task(
23877                "rust.removed-side-effect",
23878                vec![history_event(
23879                    "SideEffectRecorded",
23880                    json!({"sequence": 1, "result": result}),
23881                )],
23882                DEFAULT_CODEC,
23883            ))
23884            .expect_err("removed committed history must not become fail_workflow");
23885
23886        let Error::NonDeterministicReplay(failure) = error else {
23887            panic!("expected typed replay failure");
23888        };
23889        assert_eq!(failure.reason, "recorded_commands_unconsumed");
23890        assert_eq!(failure.sequence, Some(1));
23891        assert_eq!(failure.expected.as_deref(), Some("side effect"));
23892    }
23893
23894    #[test]
23895    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
23896        let client = Client::new("http://127.0.0.1:8080").expect("client");
23897        let mut worker = Worker::new(client, "rust-workers");
23898        worker.register_workflow(
23899            "rust.side-effect-before-marker-error",
23900            |ctx, _input| async move {
23901                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
23902                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
23903                ctx.get_version("restart-safe", 2, 2)?;
23904                Ok(Value::Null)
23905            },
23906        );
23907
23908        let error = worker
23909            .execute_workflow_task(workflow_task(
23910                "rust.side-effect-before-marker-error",
23911                vec![history_event(
23912                    "VersionMarkerRecorded",
23913                    json!({
23914                        "sequence": 1,
23915                        "change_id": "restart-safe",
23916                        "version": 1,
23917                        "min_supported": 1,
23918                        "max_supported": 1,
23919                    }),
23920                )],
23921                DEFAULT_CODEC,
23922            ))
23923            .expect_err("replay error must return no queued workflow commands");
23924
23925        let Error::NonDeterministicReplay(failure) = error else {
23926            panic!("expected typed replay failure");
23927        };
23928        assert_eq!(failure.reason, "version_marker_incompatible_range");
23929        assert_eq!(failure.sequence, Some(1));
23930    }
23931
23932    #[test]
23933    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
23934        let client = Client::new("http://127.0.0.1:8080").expect("client");
23935        let mut worker = Worker::new(client, "rust-workers");
23936        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
23937            ctx.sleep(Duration::from_secs(5)).await?;
23938            Ok(json!({"status": "timer fired"}))
23939        });
23940
23941        let task = WorkflowTask {
23942            task_id: "wft-rust-timer-pending".to_string(),
23943            workflow_command_id: None,
23944            workflow_id: Some("wf-rust-timer".to_string()),
23945            run_id: Some("run-rust-timer".to_string()),
23946            workflow_type: "rust.timer.pending".to_string(),
23947            cancel_requested: false,
23948            payload_codec: DEFAULT_CODEC.to_string(),
23949            arguments: Some(
23950                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23951            ),
23952            history_events: vec![history_event(
23953                "TimerScheduled",
23954                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23955            )],
23956            total_history_events: Some(1),
23957            history_size_bytes: None,
23958            continue_as_new_recommended: None,
23959            history_budget_pressure: None,
23960            next_history_page_token: None,
23961            workflow_task_attempt: 1,
23962            workflow_signal_id: None,
23963            signal_name: None,
23964            signal_arguments: None,
23965            workflow_update_id: None,
23966            update_name: None,
23967            lease_owner: Some("rust-worker".to_string()),
23968        };
23969
23970        for _redelivery_or_restart in 0..2 {
23971            let commands = worker
23972                .execute_workflow_task(task.clone())
23973                .expect("recorded timer remains pending");
23974            assert!(
23975                commands.is_empty(),
23976                "recorded timer must not be rescheduled"
23977            );
23978        }
23979    }
23980
23981    #[test]
23982    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
23983        let client = Client::new("http://127.0.0.1:8080").expect("client");
23984        let mut worker = Worker::new(client, "rust-workers");
23985        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
23986            Ok(json!({"status": "completed"}))
23987        });
23988        let task = WorkflowTask {
23989            task_id: "wft-rust-timer-removed".to_string(),
23990            workflow_command_id: None,
23991            workflow_id: Some("wf-rust-timer".to_string()),
23992            run_id: Some("run-rust-timer".to_string()),
23993            workflow_type: "rust.timer.removed".to_string(),
23994            cancel_requested: false,
23995            payload_codec: DEFAULT_CODEC.to_string(),
23996            arguments: Some(
23997                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23998            ),
23999            history_events: vec![
24000                history_event(
24001                    "TimerScheduled",
24002                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24003                ),
24004                history_event(
24005                    "TimerFired",
24006                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24007                ),
24008            ],
24009            total_history_events: Some(2),
24010            history_size_bytes: None,
24011            continue_as_new_recommended: None,
24012            history_budget_pressure: None,
24013            next_history_page_token: None,
24014            workflow_task_attempt: 1,
24015            workflow_signal_id: None,
24016            signal_name: None,
24017            signal_arguments: None,
24018            workflow_update_id: None,
24019            update_name: None,
24020            lease_owner: Some("rust-worker".to_string()),
24021        };
24022
24023        let Error::NonDeterministicReplay(failure) = worker
24024            .execute_workflow_task(task)
24025            .expect_err("removed timer must fail replay")
24026        else {
24027            panic!("expected typed replay failure");
24028        };
24029        assert_eq!(failure.reason, "recorded_commands_unconsumed");
24030        assert_eq!(failure.sequence, Some(1));
24031    }
24032
24033    #[test]
24034    fn workflow_context_emits_explicit_child_workflow_contract() {
24035        let ctx = WorkflowContext {
24036            cancellation_scope_id: "root".into(),
24037            state: Arc::new(Mutex::new(
24038                WorkflowState::new_with_identity(
24039                    Vec::new(),
24040                    Some("wf-parent".to_string()),
24041                    Some("run-parent".to_string()),
24042                    "parent-workers".to_string(),
24043                    DEFAULT_CODEC.to_string(),
24044                    None,
24045                )
24046                .expect("workflow state"),
24047            )),
24048        };
24049        let options = ChildWorkflowOptions::new("python-workers")
24050            .parent_close_policy(ParentClosePolicy::RequestCancel)
24051            .retry_policy(ChildWorkflowRetryPolicy {
24052                max_attempts: Some(3),
24053                backoff_seconds: vec![1, 5],
24054                non_retryable_error_types: vec!["ValidationError".to_string()],
24055            })
24056            .execution_timeout_seconds(600)
24057            .run_timeout_seconds(120);
24058        let mut call = Box::pin(ctx.start_child_workflow(
24059            "python.fulfil-order",
24060            options,
24061            json!([{"order_id": "order-42"}]),
24062        ));
24063        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24064
24065        assert!(matches!(
24066            call.as_mut().poll(&mut task_context),
24067            Poll::Pending
24068        ));
24069        let commands = ctx.take_commands().expect("commands");
24070        assert_eq!(commands.len(), 1);
24071        let command = &commands[0];
24072        assert_eq!(command["type"], "start_child_workflow");
24073        assert_eq!(command["workflow_type"], "python.fulfil-order");
24074        assert_eq!(command["queue"], "python-workers");
24075        assert_eq!(command["parent_close_policy"], "request_cancel");
24076        assert_eq!(command["retry_policy"]["max_attempts"], 3);
24077        assert_eq!(command["execution_timeout_seconds"], 600);
24078        assert_eq!(command["run_timeout_seconds"], 120);
24079        assert_eq!(
24080            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
24081            json!([{"order_id": "order-42"}])
24082        );
24083    }
24084
24085    fn child_parent_worker() -> Worker {
24086        let client = Client::new("http://127.0.0.1:8080").expect("client");
24087        let mut worker = Worker::new(client, "rust-parent-workers");
24088        worker.register_workflow("rust.parent", |ctx, _input| async move {
24089            let child = ctx
24090                .start_child_workflow(
24091                    "python.child",
24092                    ChildWorkflowOptions::new("python-child-workers")
24093                        .parent_close_policy(ParentClosePolicy::Terminate),
24094                    json!([{"codec_probe": [1, true, "rust"]}]),
24095                )
24096                .await?;
24097            Ok(json!({
24098                "parent_workflow_id": child.parent.workflow_id,
24099                "parent_run_id": child.parent.run_id,
24100                "child_workflow_id": child.child.workflow_id,
24101                "child_run_id": child.child.run_id,
24102                "child_workflow_type": child.child_workflow_type,
24103                "result": child.result,
24104            }))
24105        });
24106        worker
24107    }
24108
24109    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
24110        WorkflowTask {
24111            task_id: "wft-child-parent".to_string(),
24112            workflow_command_id: None,
24113            workflow_id: Some("wf-parent".to_string()),
24114            run_id: Some("run-parent".to_string()),
24115            workflow_type: "rust.parent".to_string(),
24116            cancel_requested: false,
24117            payload_codec: DEFAULT_CODEC.to_string(),
24118            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24119            history_events: vec![
24120                HistoryEvent {
24121                    event_type: "ChildWorkflowScheduled".to_string(),
24122                    payload: json!({
24123                        "sequence": 1,
24124                        "child_call_id": "call-child",
24125                        "child_workflow_instance_id": "wf-child",
24126                        "child_workflow_run_id": "run-child",
24127                        "child_workflow_type": "python.child",
24128                        "parent_close_policy": "terminate",
24129                    }),
24130                    raw: HashMap::new(),
24131                },
24132                HistoryEvent {
24133                    event_type: event_type.to_string(),
24134                    payload,
24135                    raw: HashMap::new(),
24136                },
24137            ],
24138            total_history_events: Some(2),
24139            history_size_bytes: None,
24140            continue_as_new_recommended: None,
24141            history_budget_pressure: None,
24142            next_history_page_token: None,
24143            workflow_task_attempt: 1,
24144            workflow_signal_id: None,
24145            signal_name: None,
24146            signal_arguments: None,
24147            workflow_update_id: None,
24148            update_name: None,
24149            lease_owner: Some("rust-worker".to_string()),
24150        }
24151    }
24152
24153    #[test]
24154    fn committed_child_result_replays_without_starting_a_duplicate() {
24155        let worker = child_parent_worker();
24156        let task = child_parent_task(
24157            "ChildRunCompleted",
24158            json!({
24159                "sequence": 1,
24160                "child_call_id": "call-child",
24161                "child_workflow_instance_id": "wf-child",
24162                "child_workflow_run_id": "run-child",
24163                "child_workflow_type": "python.child",
24164                "payload_codec": DEFAULT_CODEC,
24165                "result": fixture_envelope(json!({"from":"python","ok":true})),
24166            }),
24167        );
24168
24169        for _restart in 0..2 {
24170            let commands = worker
24171                .execute_workflow_task(task.clone())
24172                .expect("replayed parent task");
24173            assert_eq!(commands.len(), 1);
24174            assert_eq!(commands[0]["type"], "complete_workflow");
24175            assert!(!commands
24176                .iter()
24177                .any(|command| command["type"] == "start_child_workflow"));
24178            let output =
24179                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
24180            assert_eq!(output["parent_workflow_id"], "wf-parent");
24181            assert_eq!(output["parent_run_id"], "run-parent");
24182            assert_eq!(output["child_workflow_id"], "wf-child");
24183            assert_eq!(output["child_run_id"], "run-child");
24184            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
24185        }
24186    }
24187
24188    #[test]
24189    fn typed_child_arguments_and_results_survive_replay() {
24190        let client = Client::new("http://127.0.0.1:8080").expect("client");
24191        let mut worker = Worker::new(client, "rust-parent-workers");
24192        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
24193            let child = ctx
24194                .start_child_workflow_avro_value(
24195                    "python.typed-child",
24196                    ChildWorkflowOptions::new("python-workers"),
24197                    AvroValue::Array(vec![typed_fidelity_probe()]),
24198                )
24199                .await?;
24200            Ok(child.result)
24201        });
24202
24203        let initial = worker
24204            .execute_workflow_task(workflow_task(
24205                "rust.typed-parent",
24206                Vec::new(),
24207                DEFAULT_CODEC,
24208            ))
24209            .expect("typed child start");
24210        assert_eq!(initial[0]["type"], "start_child_workflow");
24211        assert_eq!(
24212            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
24213                .expect("typed child arguments"),
24214            AvroValue::Array(vec![typed_fidelity_probe()])
24215        );
24216
24217        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
24218            .expect("typed child result");
24219        let task = workflow_task(
24220            "rust.typed-parent",
24221            vec![
24222                history_event(
24223                    "ChildWorkflowScheduled",
24224                    json!({
24225                        "sequence": 1,
24226                        "child_call_id": "call-typed",
24227                        "child_workflow_instance_id": "wf-child",
24228                        "child_workflow_run_id": "run-child",
24229                        "child_workflow_type": "python.typed-child",
24230                    }),
24231                ),
24232                history_event(
24233                    "ChildRunCompleted",
24234                    json!({
24235                        "sequence": 1,
24236                        "child_call_id": "call-typed",
24237                        "child_workflow_instance_id": "wf-child",
24238                        "child_workflow_run_id": "run-child",
24239                        "child_workflow_type": "python.typed-child",
24240                        "payload_codec": DEFAULT_CODEC,
24241                        "result": result,
24242                    }),
24243                ),
24244            ],
24245            DEFAULT_CODEC,
24246        );
24247
24248        let commands = worker
24249            .execute_workflow_task(task)
24250            .expect("typed child replay");
24251        assert_eq!(commands[0]["type"], "complete_workflow");
24252        assert_eq!(
24253            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
24254                .expect("typed parent result"),
24255            typed_fidelity_probe()
24256        );
24257    }
24258
24259    #[test]
24260    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
24261        let worker = child_parent_worker();
24262        let mut task = child_parent_task("unused", Value::Null);
24263        task.history_events.truncate(1);
24264        task.total_history_events = Some(1);
24265
24266        for _redelivery_or_restart in 0..2 {
24267            let commands = worker
24268                .execute_workflow_task(task.clone())
24269                .expect("recorded child remains pending");
24270            assert!(
24271                commands.is_empty(),
24272                "recorded pending child must not be started again"
24273            );
24274        }
24275    }
24276
24277    #[test]
24278    fn child_cancellation_becomes_stable_parent_failure_command() {
24279        let worker = child_parent_worker();
24280        let task = child_parent_task(
24281            "ChildRunCancelled",
24282            json!({
24283                "sequence": 1,
24284                "child_workflow_instance_id": "wf-child",
24285                "child_workflow_run_id": "run-child",
24286                "child_workflow_type": "python.child",
24287                "failure_id": "failure-child",
24288                "failure_category": "cancelled",
24289                "message": "cancelled by parent-close policy",
24290            }),
24291        );
24292
24293        let commands = worker
24294            .execute_workflow_task(task)
24295            .expect("parent settlement");
24296        assert_eq!(commands.len(), 1);
24297        assert_eq!(commands[0]["type"], "fail_workflow");
24298        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
24299        assert_eq!(
24300            commands[0]["exception"]["properties"]["reason"],
24301            "cancelled"
24302        );
24303        assert_eq!(
24304            commands[0]["exception"]["properties"]["child_workflow_run_id"],
24305            "run-child"
24306        );
24307    }
24308
24309    #[test]
24310    fn workflow_can_handle_typed_child_failure() {
24311        let client = Client::new("http://127.0.0.1:8080").expect("client");
24312        let mut worker = Worker::new(client, "rust-parent-workers");
24313        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
24314            match ctx
24315                .start_child_workflow(
24316                    "python.child",
24317                    ChildWorkflowOptions::new("python-child-workers"),
24318                    json!([]),
24319                )
24320                .await
24321            {
24322                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
24323                    "reason": failure.reason,
24324                    "failure_id": failure.failure_id,
24325                    "exception_class": failure.exception_class,
24326                    "child_run_id": failure.child_workflow_run_id,
24327                })),
24328                Err(error) => Err(error),
24329                Ok(_) => Err(Error::WorkerLoop(
24330                    "child unexpectedly succeeded".to_string(),
24331                )),
24332            }
24333        });
24334        let mut task = child_parent_task(
24335            "ChildRunFailed",
24336            json!({
24337                "sequence": 1,
24338                "child_workflow_instance_id": "wf-child",
24339                "child_workflow_run_id": "run-child",
24340                "child_workflow_type": "python.child",
24341                "failure_id": "failure-child",
24342                "failure_category": "child_workflow",
24343                "message": "payment rejected",
24344                "exception": {
24345                    "type": "PaymentRejected",
24346                    "class": "payments.PaymentRejected",
24347                    "message": "payment rejected"
24348                }
24349            }),
24350        );
24351        task.workflow_type = "rust.handled-parent".to_string();
24352        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
24353
24354        let commands = worker.execute_workflow_task(task).expect("handled failure");
24355        assert_eq!(commands[0]["type"], "complete_workflow");
24356        let output =
24357            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
24358        assert_eq!(output["reason"], "child_workflow");
24359        assert_eq!(output["failure_id"], "failure-child");
24360        assert_eq!(output["exception_class"], "payments.PaymentRejected");
24361        assert_eq!(output["child_run_id"], "run-child");
24362    }
24363
24364    #[test]
24365    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
24366        let client = Client::new("http://127.0.0.1:8080").expect("client");
24367        let mut worker = Worker::new(client, "rust-workers");
24368
24369        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
24370            let signal = ctx.wait_signal("start").await?;
24371            let name = signal
24372                .first()
24373                .and_then(|value| value.as_str())
24374                .unwrap_or("world");
24375            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
24376            Ok(json!({
24377                "greeting": greeting,
24378                "language": "rust"
24379            }))
24380        });
24381
24382        let signal_arguments =
24383            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
24384        let task = WorkflowTask {
24385            task_id: "wft-rust-signal-1".to_string(),
24386            workflow_command_id: None,
24387            workflow_id: Some("wf-rust-hello".to_string()),
24388            run_id: Some("run-rust-hello".to_string()),
24389            workflow_type: "rust.hello_workflow".to_string(),
24390            cancel_requested: false,
24391            payload_codec: DEFAULT_CODEC.to_string(),
24392            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24393            history_events: vec![HistoryEvent {
24394                event_type: "SignalReceived".to_string(),
24395                payload: json!({
24396                    "signal_id": "sig-rust-1",
24397                    "signal_name": "start"
24398                }),
24399                raw: HashMap::new(),
24400            }],
24401            total_history_events: Some(1),
24402            history_size_bytes: None,
24403            continue_as_new_recommended: None,
24404            history_budget_pressure: None,
24405            next_history_page_token: None,
24406            workflow_task_attempt: 1,
24407            workflow_signal_id: Some("sig-rust-1".to_string()),
24408            signal_name: Some("start".to_string()),
24409            signal_arguments: Some(signal_arguments),
24410            workflow_update_id: None,
24411            update_name: None,
24412            lease_owner: Some("rust-worker".to_string()),
24413        };
24414
24415        let commands = worker.execute_workflow_task(task).expect("workflow task");
24416
24417        assert_eq!(commands.len(), 1);
24418        assert_eq!(commands[0]["type"], "schedule_activity");
24419        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
24420        assert_eq!(
24421            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
24422            json!(["Rust"])
24423        );
24424    }
24425
24426    #[test]
24427    fn workflow_task_appends_paginated_history_events() {
24428        let mut task = WorkflowTask {
24429            task_id: "wft-rust-pages-1".to_string(),
24430            workflow_command_id: None,
24431            workflow_id: Some("wf-rust-pages".to_string()),
24432            run_id: Some("run-rust-pages".to_string()),
24433            workflow_type: "rust.hello_workflow".to_string(),
24434            cancel_requested: false,
24435            payload_codec: DEFAULT_CODEC.to_string(),
24436            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24437            history_events: vec![HistoryEvent {
24438                event_type: "WorkflowStarted".to_string(),
24439                payload: json!({}),
24440                raw: HashMap::new(),
24441            }],
24442            total_history_events: Some(3),
24443            history_size_bytes: None,
24444            continue_as_new_recommended: None,
24445            history_budget_pressure: None,
24446            next_history_page_token: Some("MQ==".to_string()),
24447            workflow_task_attempt: 1,
24448            workflow_signal_id: None,
24449            signal_name: None,
24450            signal_arguments: None,
24451            workflow_update_id: None,
24452            update_name: None,
24453            lease_owner: Some("rust-worker".to_string()),
24454        };
24455
24456        task.append_history_page(WorkflowTaskHistoryPage {
24457            history_events: vec![
24458                HistoryEvent {
24459                    event_type: "SignalReceived".to_string(),
24460                    payload: json!({
24461                        "signal_id": "sig-rust-1",
24462                        "signal_name": "start",
24463                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
24464                            .expect("signal arguments")
24465                    }),
24466                    raw: HashMap::new(),
24467                },
24468                HistoryEvent {
24469                    event_type: "MarkerRecorded".to_string(),
24470                    payload: json!({"sequence": 3}),
24471                    raw: HashMap::new(),
24472                },
24473            ],
24474            total_history_events: Some(3),
24475            next_history_page_token: None,
24476        });
24477
24478        assert_eq!(task.history_events.len(), 3);
24479        assert_eq!(task.total_history_events, Some(3));
24480        assert_eq!(task.next_history_page_token, None);
24481
24482        let signal = task
24483            .history_events
24484            .iter()
24485            .find(|event| event.event_type == "SignalReceived")
24486            .expect("signal event");
24487        assert_eq!(
24488            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
24489            vec![AvroValue::String("Rust".to_string())]
24490        );
24491    }
24492
24493    #[tokio::test]
24494    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
24495        let client = Client::new("http://127.0.0.1:8080").expect("client");
24496        let mut worker = Worker::new(client, "rust-workers");
24497        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24498        worker.register_query("counter", "current", |ctx, _args| async move {
24499            let mut count = 0_i64;
24500            for signal in ctx.signal_events() {
24501                let value = signal
24502                    .arguments
24503                    .first()
24504                    .and_then(Value::as_i64)
24505                    .unwrap_or_default();
24506                match signal.name.as_str() {
24507                    "increment" => count += value,
24508                    "set" => count = value,
24509                    _ => {}
24510                }
24511            }
24512            Ok(json!(count))
24513        });
24514
24515        let task = QueryTask {
24516            query_task_id: "query-rust-counter".to_string(),
24517            query_task_attempt: 1,
24518            lease_owner: Some("rust-worker".to_string()),
24519            workflow_id: Some("counter-1".to_string()),
24520            run_id: Some("run-counter-1".to_string()),
24521            workflow_type: "counter".to_string(),
24522            query_name: "current".to_string(),
24523            payload_codec: DEFAULT_CODEC.to_string(),
24524            workflow_arguments: Some(
24525                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24526            ),
24527            query_arguments: Some(
24528                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
24529            ),
24530            history_events: vec![
24531                HistoryEvent {
24532                    event_type: "SignalReceived".to_string(),
24533                    payload: json!({
24534                        "signal_id": "php-signal-1",
24535                        "signal_name": "increment",
24536                        "workflow_sequence": 1,
24537                        "payload_codec": DEFAULT_CODEC,
24538                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
24539                    }),
24540                    raw: HashMap::new(),
24541                },
24542                HistoryEvent {
24543                    event_type: "SignalReceived".to_string(),
24544                    payload: json!({
24545                        "signal_id": "python-signal-2",
24546                        "signal_name": "increment",
24547                        "workflow_sequence": 2,
24548                        "payload_codec": DEFAULT_CODEC,
24549                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
24550                    }),
24551                    raw: HashMap::new(),
24552                },
24553                HistoryEvent {
24554                    event_type: "SignalReceived".to_string(),
24555                    payload: json!({
24556                        "signal_id": "rust-signal-3",
24557                        "signal_name": "set",
24558                        "workflow_sequence": 3,
24559                        "payload_codec": DEFAULT_CODEC,
24560                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
24561                    }),
24562                    raw: HashMap::new(),
24563                },
24564            ],
24565            history_export: None,
24566            run_status: Some("completed".to_string()),
24567        };
24568
24569        let result = worker.execute_query_task(task).await.expect("query result");
24570        assert_eq!(result.into_json().expect("query projection"), json!(0));
24571    }
24572
24573    #[tokio::test]
24574    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
24575        let worker = replay_counter_worker();
24576        let running_history = json!([
24577            {
24578                "type": "ActivityCompleted",
24579                "payload": {
24580                    "sequence": 1,
24581                    "activity_type": "load-counter",
24582                    "payload_codec": DEFAULT_CODEC,
24583                    "result": fixture_envelope(json!("loaded"))
24584                }
24585            },
24586            {
24587                "type": "SignalWaitOpened",
24588                "payload": {
24589                    "sequence": 3,
24590                    "signal_name": "increment"
24591                }
24592            },
24593            {
24594                "type": "SignalReceived",
24595                "payload": {
24596                    "signal_id": "signal-3",
24597                    "signal_name": "increment",
24598                    "workflow_sequence": 2,
24599                    "payload_codec": DEFAULT_CODEC,
24600                    "arguments": fixture_envelope(json!([3]))
24601                }
24602            },
24603            {
24604                "type": "SignalApplied",
24605                "payload": {
24606                    "sequence": 3,
24607                    "signal_id": "signal-3",
24608                    "signal_name": "increment",
24609                    "payload_codec": DEFAULT_CODEC,
24610                    "value": fixture_envelope(json!([3]))
24611                }
24612            }
24613        ]);
24614
24615        let running = worker
24616            .execute_query_task(replay_counter_query(
24617                "current",
24618                running_history.clone(),
24619                "running",
24620            ))
24621            .await
24622            .expect("running replay query");
24623        assert_eq!(
24624            running.clone().into_json().expect("query projection"),
24625            json!({"loaded": "loaded", "count": 3, "finished": false})
24626        );
24627
24628        let detached = worker
24629            .execute_query_task(replay_counter_query(
24630                "detached-mutation",
24631                running_history.clone(),
24632                "running",
24633            ))
24634            .await
24635            .expect("query mutates only its detached state clone");
24636        assert_eq!(detached.into_json().expect("query projection"), json!(999));
24637        let failed = worker
24638            .execute_query_task(replay_counter_query(
24639                "failed-mutation",
24640                running_history.clone(),
24641                "running",
24642            ))
24643            .await
24644            .expect_err("failed query");
24645        assert_eq!(failed.reason, "query_rejected");
24646        let unchanged = worker
24647            .execute_query_task(replay_counter_query("current", running_history, "running"))
24648            .await
24649            .expect("later query reconstructs unchanged state");
24650        assert_eq!(unchanged, running);
24651
24652        let restarted_worker = replay_counter_worker();
24653        let empty_arguments = fixture_envelope(json!([]));
24654        let loaded_result = fixture_envelope(json!("loaded"));
24655        let signal_three = fixture_blob(json!([3]));
24656        let signal_five = fixture_blob(json!([5]));
24657        let restarted_task: QueryTask = serde_json::from_value(json!({
24658            "query_task_id": "query-after-restart",
24659            "workflow_id": "counter-1",
24660            "run_id": "run-counter-1",
24661            "workflow_type": "replay-counter",
24662            "query_name": "current",
24663            "payload_codec": DEFAULT_CODEC,
24664            "workflow_arguments": empty_arguments.clone(),
24665            "query_arguments": empty_arguments,
24666            "history_events": [],
24667            "history_export": {
24668                "payloads": {"codec": DEFAULT_CODEC},
24669                "history_events": [
24670                    {
24671                        "type": "ActivityCompleted",
24672                        "payload": {
24673                            "sequence": 1,
24674                            "activity_type": "load-counter",
24675                            "payload_codec": DEFAULT_CODEC,
24676                            "result": null
24677                        }
24678                    },
24679                    {
24680                        "type": "SignalWaitOpened",
24681                        "payload": {
24682                            "sequence": 3,
24683                            "signal_name": "increment"
24684                        }
24685                    },
24686                    {
24687                        "type": "SignalReceived",
24688                        "payload": {
24689                            "signal_id": "signal-3",
24690                            "signal_name": "increment",
24691                            "workflow_sequence": 2
24692                        }
24693                    },
24694                    {
24695                        "type": "SignalApplied",
24696                        "payload": {
24697                            "sequence": 3,
24698                            "signal_id": "signal-3",
24699                            "signal_name": "increment"
24700                        }
24701                    },
24702                    {
24703                        "type": "SignalWaitOpened",
24704                        "payload": {
24705                            "sequence": 5,
24706                            "signal_name": "increment"
24707                        }
24708                    },
24709                    {
24710                        "type": "SignalReceived",
24711                        "payload": {
24712                            "signal_id": "signal-5",
24713                            "signal_name": "increment",
24714                            "workflow_sequence": 4
24715                        }
24716                    },
24717                    {
24718                        "type": "SignalApplied",
24719                        "payload": {
24720                            "sequence": 5,
24721                            "signal_id": "signal-5",
24722                            "signal_name": "increment"
24723                        }
24724                    }
24725                ],
24726                "activities": [{
24727                    "sequence": 1,
24728                    "activity_type": "load-counter",
24729                    "payload_codec": DEFAULT_CODEC,
24730                    "result": loaded_result
24731                }],
24732                "signals": [
24733                    {
24734                        "id": "signal-3",
24735                        "name": "increment",
24736                        "workflow_sequence": 2,
24737                        "payload_codec": DEFAULT_CODEC,
24738                        "arguments": signal_three
24739                    },
24740                    {
24741                        "id": "signal-5",
24742                        "name": "increment",
24743                        "workflow_sequence": 4,
24744                        "payload_codec": DEFAULT_CODEC,
24745                        "arguments": signal_five
24746                    }
24747                ]
24748            },
24749            "run_status": "completed"
24750        }))
24751        .expect("cold replay query task");
24752        let completed = restarted_worker
24753            .execute_query_task(restarted_task)
24754            .await
24755            .expect("completed cold replay query");
24756        assert_eq!(
24757            completed.into_json().expect("query projection"),
24758            json!({"loaded": "loaded", "count": 8, "finished": true})
24759        );
24760    }
24761
24762    #[tokio::test]
24763    async fn replayed_query_replay_failures_are_machine_readable() {
24764        let worker = replay_counter_worker();
24765        let task = replay_counter_query(
24766            "current",
24767            json!([{
24768                "type": "ActivityCompleted",
24769                "payload": {
24770                    "sequence": 1,
24771                    "payload_codec": DEFAULT_CODEC,
24772                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
24773                }
24774            }]),
24775            "running",
24776        );
24777        let failure = worker
24778            .execute_query_task(task)
24779            .await
24780            .expect_err("invalid replay history payload");
24781        assert_eq!(failure.reason, "query_payload_decode_failed");
24782        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
24783        assert!(failure.message.contains("invalid_payload_framing"));
24784    }
24785
24786    #[tokio::test]
24787    async fn query_task_restores_compact_history_from_export() {
24788        let client = Client::new("http://127.0.0.1:8080").expect("client");
24789        let mut worker = Worker::new(client, "rust-workers");
24790        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24791        worker.register_query("counter", "current", |ctx, _args| async move {
24792            Ok(json!(ctx.signals("increment")[0][0]))
24793        });
24794        let empty_arguments = fixture_envelope(json!([]));
24795        let exported_signal = fixture_blob(json!([9]));
24796        let task: QueryTask = serde_json::from_value(json!({
24797            "query_task_id": "query-export",
24798            "workflow_type": "counter",
24799            "query_name": "current",
24800            "payload_codec": DEFAULT_CODEC,
24801            "workflow_arguments": empty_arguments.clone(),
24802            "query_arguments": empty_arguments,
24803            "history_events": [],
24804            "history_export": {
24805                "payloads": {"codec": DEFAULT_CODEC},
24806                "history_events": [{
24807                    "type": "SignalReceived",
24808                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
24809                }],
24810                "signals": [{
24811                    "id": "signal-export",
24812                    "name": "increment",
24813                    "status": "applied",
24814                    "workflow_sequence": 1,
24815                    "payload_codec": DEFAULT_CODEC,
24816                    "arguments": exported_signal
24817                }]
24818            }
24819        }))
24820        .expect("query task");
24821
24822        let result = worker.execute_query_task(task).await.expect("query result");
24823        assert_eq!(result.into_json().expect("query projection"), json!(9));
24824    }
24825
24826    #[tokio::test]
24827    async fn query_task_failures_have_stable_reasons() {
24828        let client = Client::new("http://127.0.0.1:8080").expect("client");
24829        let mut worker = Worker::new(client, "rust-workers");
24830        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24831        worker.register_query(
24832            "counter",
24833            "current",
24834            |_ctx, _args| async move { Ok(json!(0)) },
24835        );
24836
24837        let base_task = QueryTask {
24838            query_task_id: "query-errors".to_string(),
24839            query_task_attempt: 1,
24840            lease_owner: None,
24841            workflow_id: Some("counter-errors".to_string()),
24842            run_id: Some("run-errors".to_string()),
24843            workflow_type: "counter".to_string(),
24844            query_name: "missing".to_string(),
24845            payload_codec: DEFAULT_CODEC.to_string(),
24846            workflow_arguments: Some(fixture_envelope(json!([]))),
24847            query_arguments: Some(fixture_envelope(json!([]))),
24848            history_events: Vec::new(),
24849            history_export: None,
24850            run_status: Some("running".to_string()),
24851        };
24852
24853        let unknown = worker
24854            .execute_query_task(base_task.clone())
24855            .await
24856            .expect_err("unknown query");
24857        assert_eq!(unknown.reason, "rejected_unknown_query");
24858
24859        let mut malformed = base_task;
24860        malformed.query_name = "current".to_string();
24861        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
24862        let malformed = worker
24863            .execute_query_task(malformed)
24864            .await
24865            .expect_err("malformed payload");
24866        assert_eq!(malformed.reason, "query_payload_decode_failed");
24867
24868        let client = Client::new("http://127.0.0.1:8080").expect("client");
24869        let mut unavailable_worker = Worker::new(client, "rust-workers");
24870        unavailable_worker
24871            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24872        let empty_arguments = fixture_envelope(json!([]));
24873        let unavailable_task: QueryTask = serde_json::from_value(json!({
24874            "query_task_id": "query-unavailable",
24875            "workflow_type": "counter",
24876            "query_name": "current",
24877            "payload_codec": DEFAULT_CODEC,
24878            "workflow_arguments": empty_arguments.clone(),
24879            "query_arguments": empty_arguments
24880        }))
24881        .expect("query task");
24882        let unavailable = unavailable_worker
24883            .execute_query_task(unavailable_task)
24884            .await
24885            .expect_err("query handler unavailable");
24886        assert_eq!(unavailable.reason, "query_handler_unavailable");
24887    }
24888
24889    #[tokio::test]
24890    async fn client_query_decodes_result_and_typed_failure() {
24891        let server = MockWorkerServer::start();
24892        let client = Client::builder(server.base_url())
24893            .timeout(Duration::from_secs(2))
24894            .build()
24895            .expect("client");
24896
24897        let result = client
24898            .query_workflow("counter-1", "current", json!([]))
24899            .await
24900            .expect("query result");
24901        assert_eq!(result, json!({"count": 8}));
24902
24903        let error = client
24904            .query_workflow("counter-1", "missing", json!([]))
24905            .await
24906            .expect_err("unknown query");
24907        let Error::QueryFailed(failure) = error else {
24908            panic!("expected typed query failure");
24909        };
24910        assert_eq!(failure.status, 404);
24911        assert_eq!(failure.reason, "rejected_unknown_query");
24912    }
24913
24914    #[tokio::test]
24915    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
24916        let server = MockWorkerServer::start();
24917        let client = Client::builder(server.base_url())
24918            .timeout(Duration::from_secs(2))
24919            .build()
24920            .expect("client");
24921        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
24922
24923        client
24924            .start_workflow(
24925                "typed.echo",
24926                "rust-workers",
24927                "typed-start",
24928                arguments.clone(),
24929            )
24930            .await
24931            .expect("typed workflow start");
24932        assert_eq!(
24933            decode_wire_avro_value(
24934                &server.request_body("/api/workflows")["input"],
24935                DEFAULT_CODEC,
24936            )
24937            .expect("typed start input"),
24938            arguments
24939        );
24940
24941        client
24942            .signal_workflow("typed-1", "changed", arguments.clone())
24943            .await
24944            .expect("typed signal");
24945        assert_eq!(
24946            decode_wire_avro_value(
24947                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
24948                DEFAULT_CODEC,
24949            )
24950            .expect("typed signal input"),
24951            arguments
24952        );
24953
24954        assert_eq!(
24955            client
24956                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
24957                .await
24958                .expect("typed query"),
24959            typed_fidelity_probe()
24960        );
24961        assert_eq!(
24962            decode_wire_avro_value(
24963                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
24964                DEFAULT_CODEC,
24965            )
24966            .expect("typed query input"),
24967            arguments
24968        );
24969
24970        assert_eq!(
24971            client
24972                .update_workflow_avro_value(
24973                    "typed-1",
24974                    "replace",
24975                    arguments.clone(),
24976                    Some("typed-request"),
24977                )
24978                .await
24979                .expect("typed update"),
24980            typed_fidelity_probe()
24981        );
24982        let update = server.request_body("/api/workflows/typed-1/update/replace");
24983        assert_eq!(update["request_id"], "typed-request");
24984        assert_eq!(
24985            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
24986            arguments
24987        );
24988
24989        let handle = WorkflowHandle {
24990            client: client.clone(),
24991            workflow_id: "typed-1".to_string(),
24992            run_id: Some("run-typed-1".to_string()),
24993            workflow_type: "typed.echo".to_string(),
24994        };
24995        assert_eq!(
24996            handle
24997                .result_avro_value(WorkflowResultOptions::default())
24998                .await
24999                .expect("typed workflow result"),
25000            typed_fidelity_probe()
25001        );
25002
25003        client
25004            .complete_activity_task(
25005                "activity-typed",
25006                "attempt-typed",
25007                "rust-worker",
25008                typed_fidelity_probe(),
25009                DEFAULT_CODEC,
25010            )
25011            .await
25012            .expect("typed activity completion");
25013        assert_eq!(
25014            decode_wire_avro_value(
25015                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
25016                    ["result"],
25017                DEFAULT_CODEC,
25018            )
25019            .expect("typed activity result"),
25020            typed_fidelity_probe()
25021        );
25022        client
25023            .fail_activity_task(
25024                "activity-typed",
25025                "attempt-typed",
25026                "rust-worker",
25027                "typed failure",
25028                true,
25029            )
25030            .await
25031            .expect("activity failure");
25032    }
25033
25034    #[tokio::test]
25035    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
25036        let server = MockWorkerServer::start();
25037        let client = Client::builder(server.base_url())
25038            .timeout(Duration::from_secs(2))
25039            .build()
25040            .expect("client");
25041
25042        let options = WorkflowCommandOptions::new()
25043            .reason("cleanup requested")
25044            .request_id("cancel-17");
25045        let cancelled = client
25046            .cancel_workflow("wf-lifecycle", options)
25047            .await
25048            .expect("instance cancellation");
25049        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
25050        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
25051        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
25052        assert_eq!(
25053            server.request_body("/api/workflows/wf-lifecycle/cancel"),
25054            json!({"reason":"cleanup requested","request_id":"cancel-17"})
25055        );
25056
25057        let terminated = client
25058            .terminate_workflow(
25059                "wf-lifecycle",
25060                WorkflowCommandOptions::new().reason("forced stop"),
25061            )
25062            .await
25063            .expect("instance termination");
25064        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
25065        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
25066
25067        client
25068            .cancel_workflow_run(
25069                "wf-lifecycle",
25070                "run-current",
25071                WorkflowCommandOptions::default(),
25072            )
25073            .await
25074            .expect("selected run cancellation");
25075        client
25076            .terminate_workflow_run(
25077                "wf-lifecycle",
25078                "run-current",
25079                WorkflowCommandOptions::default(),
25080            )
25081            .await
25082            .expect("selected run termination");
25083
25084        for (command, error) in [
25085            (
25086                WorkflowCommandKind::Cancel,
25087                client
25088                    .cancel_workflow_run(
25089                        "wf-lifecycle",
25090                        "run-stale",
25091                        WorkflowCommandOptions::default(),
25092                    )
25093                    .await
25094                    .expect_err("stale cancellation must be rejected"),
25095            ),
25096            (
25097                WorkflowCommandKind::Terminate,
25098                client
25099                    .terminate_workflow_run(
25100                        "wf-lifecycle",
25101                        "run-stale",
25102                        WorkflowCommandOptions::default(),
25103                    )
25104                    .await
25105                    .expect_err("stale termination must be rejected"),
25106            ),
25107        ] {
25108            let Error::WorkflowCommandRejected(rejection) = error else {
25109                panic!("expected typed command rejection");
25110            };
25111            assert_eq!(rejection.command, command);
25112            assert_eq!(rejection.status, 409);
25113            assert_eq!(rejection.reason, "historical_run_command_rejected");
25114            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
25115            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
25116        }
25117    }
25118
25119    #[tokio::test]
25120    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
25121        let server = MockWorkerServer::start();
25122        let client = Client::builder(server.base_url())
25123            .timeout(Duration::from_secs(2))
25124            .build()
25125            .expect("client");
25126
25127        let result = client
25128            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
25129            .await
25130            .expect("redrive accepted");
25131        assert_eq!(result.workflow_id, "wf-lifecycle");
25132        assert_eq!(result.source_run_id, "run-failed");
25133        assert_eq!(result.run_id, "run-successor");
25134        assert_eq!(result.resume_step_sequence, 2);
25135        assert_eq!(
25136            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
25137            json!({"request_id":"retry-1"})
25138        );
25139
25140        let repeated = client
25141            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
25142            .await
25143            .expect("idempotent redrive response accepted");
25144        assert_eq!(repeated.run_id, "run-successor");
25145
25146        let error = client
25147            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
25148            .await
25149            .expect_err("completed run must be rejected");
25150        let Error::Http { status, body } = error else {
25151            panic!("expected HTTP redrive rejection");
25152        };
25153        assert_eq!(status.as_u16(), 409);
25154        assert!(body.contains("run_not_failed"));
25155        assert_eq!(
25156            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
25157            json!({})
25158        );
25159
25160        let handle = WorkflowHandle {
25161            client: client.clone(),
25162            workflow_id: "wf-lifecycle".to_string(),
25163            run_id: Some("run-failed".to_string()),
25164            workflow_type: "test".to_string(),
25165        };
25166        assert_eq!(
25167            handle.redrive(None).await.expect("handle redrive").run_id,
25168            "run-successor"
25169        );
25170        let missing_run = WorkflowHandle {
25171            run_id: None,
25172            ..handle
25173        };
25174        assert!(matches!(
25175            missing_run.redrive(None).await,
25176            Err(Error::Codec(_))
25177        ));
25178    }
25179
25180    #[tokio::test]
25181    async fn workflow_start_options_send_server_enforced_deadlines() {
25182        let server = MockWorkerServer::start();
25183        let client = Client::builder(server.base_url())
25184            .timeout(Duration::from_secs(2))
25185            .build()
25186            .expect("client");
25187
25188        let handle = client
25189            .start_workflow_with_options(
25190                "rust.timeout",
25191                "rust-timeouts",
25192                "wf-start-options",
25193                WorkflowStartOptions::new()
25194                    .execution_timeout_seconds(30)
25195                    .run_timeout_seconds(1),
25196                json!([]),
25197            )
25198            .await
25199            .expect("workflow start");
25200
25201        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
25202        let body = server.request_body("/api/workflows");
25203        assert_eq!(body["execution_timeout_seconds"], 30);
25204        assert_eq!(body["run_timeout_seconds"], 1);
25205
25206        let invalid = client
25207            .start_workflow_with_options(
25208                "rust.timeout",
25209                "rust-timeouts",
25210                "wf-invalid-options",
25211                WorkflowStartOptions::new()
25212                    .execution_timeout_seconds(1)
25213                    .run_timeout_seconds(2),
25214                json!([]),
25215            )
25216            .await
25217            .expect_err("invalid deadline ordering");
25218        assert!(invalid
25219            .to_string()
25220            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
25221    }
25222
25223    #[tokio::test]
25224    async fn workflow_result_returns_each_typed_terminal_outcome() {
25225        let server = MockWorkerServer::start();
25226        let client = Client::builder(server.base_url())
25227            .timeout(Duration::from_secs(2))
25228            .build()
25229            .expect("client");
25230        let options = WorkflowResultOptions {
25231            poll_interval: Duration::ZERO,
25232            timeout: Duration::from_secs(1),
25233        };
25234
25235        let failed = WorkflowHandle {
25236            client: client.clone(),
25237            workflow_id: "wf-failed".to_string(),
25238            run_id: Some("run-failed".to_string()),
25239            workflow_type: "failure".to_string(),
25240        }
25241        .result(options)
25242        .await
25243        .expect_err("failed outcome");
25244        let Error::WorkflowFailed(failure) = failed else {
25245            panic!("expected WorkflowFailed");
25246        };
25247        assert_eq!(failure.workflow_id, "wf-failed");
25248        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
25249        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
25250        assert_eq!(failure.failure_category.as_deref(), Some("application"));
25251        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
25252        assert_eq!(
25253            failure.exception_class.as_deref(),
25254            Some("billing::PaymentError")
25255        );
25256        assert_eq!(failure.non_retryable, Some(true));
25257
25258        for (workflow_id, expected_kind, expected_reason) in [
25259            (
25260                "wf-cancelled",
25261                WorkflowTerminalKind::Cancelled,
25262                "cleanup requested",
25263            ),
25264            (
25265                "wf-terminated",
25266                WorkflowTerminalKind::Terminated,
25267                "forced stop",
25268            ),
25269            (
25270                "wf-timed-out",
25271                WorkflowTerminalKind::TimedOut,
25272                "run_timeout",
25273            ),
25274        ] {
25275            let error = WorkflowHandle {
25276                client: client.clone(),
25277                workflow_id: workflow_id.to_string(),
25278                run_id: None,
25279                workflow_type: "terminal".to_string(),
25280            }
25281            .result(options)
25282            .await
25283            .expect_err("typed terminal outcome");
25284            let outcome = match error {
25285                Error::WorkflowCancelled(outcome) => outcome,
25286                Error::WorkflowTerminated(outcome) => outcome,
25287                Error::WorkflowTimedOut(outcome) => outcome,
25288                other => panic!("unexpected terminal error: {other}"),
25289            };
25290            assert_eq!(outcome.kind, expected_kind);
25291            assert_eq!(outcome.workflow_id, workflow_id);
25292            assert_eq!(outcome.reason, expected_reason);
25293        }
25294
25295        let wait_timeout = WorkflowHandle {
25296            client,
25297            workflow_id: "wf-waiting".to_string(),
25298            run_id: Some("run-waiting".to_string()),
25299            workflow_type: "waiting".to_string(),
25300        }
25301        .result(WorkflowResultOptions {
25302            poll_interval: Duration::ZERO,
25303            timeout: Duration::ZERO,
25304        })
25305        .await
25306        .expect_err("client wait timeout");
25307        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
25308            panic!("expected typed client timeout");
25309        };
25310        assert_eq!(timeout.reason, "result_wait_timeout");
25311        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
25312        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
25313    }
25314
25315    #[tokio::test]
25316    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
25317        let server = MockWorkerServer::start();
25318        let client = Client::builder(server.base_url())
25319            .timeout(Duration::from_secs(2))
25320            .build()
25321            .expect("client");
25322
25323        let handle = WorkflowHandle {
25324            client,
25325            workflow_id: "wf-selected".to_string(),
25326            run_id: Some("run-selected".to_string()),
25327            workflow_type: "selected".to_string(),
25328        };
25329        let options = WorkflowResultOptions {
25330            poll_interval: Duration::ZERO,
25331            timeout: Duration::from_secs(1),
25332        };
25333
25334        let current = handle
25335            .result(options)
25336            .await
25337            .expect("instance result follows the current run");
25338        assert_eq!(current, json!("current run output"));
25339
25340        let error = handle
25341            .result_selected_run(options)
25342            .await
25343            .expect_err("the selected run is cancelled even though the current run completed");
25344
25345        let Error::WorkflowCancelled(outcome) = error else {
25346            panic!("expected selected run cancellation");
25347        };
25348        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
25349        assert_eq!(outcome.reason, "selected run cancelled");
25350        assert_eq!(
25351            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
25352            1
25353        );
25354        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
25355    }
25356
25357    #[tokio::test]
25358    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
25359        let server = MockWorkerServer::draining_polls();
25360        let client = Client::builder(server.base_url())
25361            .timeout(Duration::from_secs(2))
25362            .build()
25363            .expect("client");
25364
25365        let workflow = client
25366            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
25367            .await
25368            .expect("workflow drain response");
25369        let activity = client
25370            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
25371            .await
25372            .expect("activity drain response");
25373        let query = client
25374            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
25375            .await
25376            .expect("query drain response");
25377
25378        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
25379            assert_eq!(
25380                outcome,
25381                WorkerPollOutcome::Stop {
25382                    poll_status: Some("draining".to_string()),
25383                    reason: Some("worker_draining".to_string()),
25384                }
25385            );
25386        }
25387
25388        assert!(client
25389            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
25390            .await
25391            .expect("compatibility poll")
25392            .is_none());
25393    }
25394
25395    #[tokio::test]
25396    async fn managed_worker_honors_drain_stop_for_every_task_family() {
25397        let server = MockWorkerServer::draining_polls();
25398        let client = Client::builder(server.base_url())
25399            .timeout(Duration::from_secs(2))
25400            .build()
25401            .expect("client");
25402
25403        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
25404            .worker_id("draining-workflow-worker")
25405            .poll_timeout(Duration::ZERO);
25406        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
25407        workflow_worker
25408            .run()
25409            .await
25410            .expect("workflow drain is a clean stop");
25411
25412        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
25413            .worker_id("draining-activity-worker")
25414            .poll_timeout(Duration::ZERO);
25415        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
25416        activity_worker
25417            .run()
25418            .await
25419            .expect("activity drain is a clean stop");
25420
25421        let mut query_worker = Worker::new(client, "rust-workers")
25422            .worker_id("draining-query-worker")
25423            .poll_timeout(Duration::ZERO);
25424        query_worker.register_query("counter", "current", |_ctx, _args| async {
25425            Ok(Value::Null)
25426        });
25427        query_worker
25428            .run()
25429            .await
25430            .expect("query drain is a clean stop");
25431    }
25432
25433    #[tokio::test]
25434    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
25435        let server = MockWorkerServer::start();
25436        let client = Client::builder(server.base_url())
25437            .timeout(Duration::from_secs(2))
25438            .build()
25439            .expect("client");
25440
25441        let heartbeat = client
25442            .heartbeat_activity_task(
25443                "activity-cancel",
25444                "attempt-cancel",
25445                "rust-worker",
25446                typed_fidelity_probe(),
25447            )
25448            .await
25449            .expect("cancellation heartbeat");
25450        assert!(heartbeat.cancel_requested);
25451        assert!(heartbeat.should_stop());
25452        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
25453        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
25454        let heartbeat_body =
25455            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
25456        assert_eq!(heartbeat_body["details"]["codec"], DEFAULT_CODEC);
25457        assert_eq!(
25458            decode_wire_avro_value(&heartbeat_body["details"], DEFAULT_CODEC)
25459                .expect("typed heartbeat details"),
25460            typed_fidelity_probe()
25461        );
25462
25463        let error = client
25464            .complete_activity_task(
25465                "activity-cancel",
25466                "attempt-cancel",
25467                "rust-worker",
25468                json!({"late":true}),
25469                DEFAULT_CODEC,
25470            )
25471            .await
25472            .expect_err("late completion must be refused");
25473        assert!(activity_task_rejection_is_final(&error));
25474        let Error::ActivityTaskRejected(rejection) = error else {
25475            panic!("expected typed activity rejection");
25476        };
25477        assert_eq!(rejection.status, 409);
25478        assert_eq!(rejection.reason, "run_cancelled");
25479        assert!(rejection.cancel_requested);
25480        assert_eq!(rejection.can_continue, Some(false));
25481    }
25482
25483    #[tokio::test]
25484    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
25485        let server = MockWorkerServer::cancelled_activity();
25486        let client = Client::builder(server.base_url())
25487            .timeout(Duration::from_secs(2))
25488            .build()
25489            .expect("client");
25490        let cancellation_observed = Arc::new(AtomicBool::new(false));
25491        let observed = Arc::clone(&cancellation_observed);
25492        let mut worker = Worker::new(client.clone(), "rust-workers")
25493            .worker_id("rust-cancel-worker")
25494            .poll_timeout(Duration::from_millis(10));
25495        worker.register_activity("cancel-aware", move |ctx, _args| {
25496            let observed = Arc::clone(&observed);
25497            async move {
25498                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
25499                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
25500                Ok(json!({"late":"completion"}))
25501            }
25502        });
25503
25504        assert_eq!(
25505            worker.run_once().await.expect("cancelled attempt handled"),
25506            1
25507        );
25508        assert!(cancellation_observed.load(Ordering::SeqCst));
25509        assert_eq!(
25510            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
25511            1
25512        );
25513
25514        let mut restarted = Worker::new(client, "rust-workers")
25515            .worker_id("rust-cancel-worker-restarted")
25516            .poll_timeout(Duration::from_millis(10));
25517        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
25518        assert_eq!(
25519            restarted
25520                .run_once()
25521                .await
25522                .expect("replacement worker continues polling"),
25523            0
25524        );
25525    }
25526
25527    #[tokio::test]
25528    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
25529        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"}"#;
25530        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
25531        let client = Client::builder(server.base_url())
25532            .timeout(Duration::from_secs(2))
25533            .build()
25534            .expect("client");
25535
25536        let direct_error = client
25537            .complete_workflow_task(
25538                "workflow-timeout-task",
25539                "timeout-worker",
25540                3,
25541                vec![json!({
25542                    "type": "complete_workflow",
25543                    "result": fixture_envelope(Value::Null)
25544                })],
25545            )
25546            .await
25547            .expect_err("the low-level client preserves the completion rejection");
25548        let Error::Http { status, body } = direct_error else {
25549            panic!("expected the original HTTP completion rejection");
25550        };
25551        assert_eq!(status, reqwest::StatusCode::CONFLICT);
25552        assert_eq!(
25553            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
25554            "run_timed_out"
25555        );
25556
25557        let mut worker = Worker::new(client, "rust-workers")
25558            .worker_id("timeout-worker")
25559            .poll_timeout(Duration::from_millis(10));
25560        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
25561            Ok(json!({"late": "result"}))
25562        });
25563
25564        assert_eq!(
25565            worker
25566                .run_once()
25567                .await
25568                .expect("authoritative selected-run timeout settles the tick"),
25569            1
25570        );
25571        assert_eq!(
25572            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
25573            2,
25574            "both the direct client proof and managed worker must see the rejection"
25575        );
25576    }
25577
25578    #[tokio::test]
25579    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
25580        for (name, status, response) in [
25581            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
25582            (
25583                "command was recorded",
25584                "409 Conflict",
25585                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25586            ),
25587            (
25588                "lease conflict",
25589                "409 Conflict",
25590                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
25591            ),
25592            (
25593                "nonterminal run",
25594                "409 Conflict",
25595                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
25596            ),
25597            (
25598                "different selected run",
25599                "409 Conflict",
25600                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"}"#,
25601            ),
25602            (
25603                "different task attempt",
25604                "409 Conflict",
25605                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25606            ),
25607            (
25608                "authentication failure",
25609                "401 Unauthorized",
25610                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25611            ),
25612            (
25613                "authorization failure",
25614                "403 Forbidden",
25615                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25616            ),
25617            (
25618                "protocol failure",
25619                "400 Bad Request",
25620                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
25621            ),
25622            (
25623                "malformed command",
25624                "422 Unprocessable Entity",
25625                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25626            ),
25627            (
25628                "transient server failure",
25629                "503 Service Unavailable",
25630                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25631            ),
25632        ] {
25633            let server = MockWorkerServer::workflow_completion(status, response);
25634            let client = Client::builder(server.base_url())
25635                .timeout(Duration::from_secs(2))
25636                .build()
25637                .expect("client");
25638            let mut worker = Worker::new(client, "rust-workers")
25639                .worker_id("timeout-worker")
25640                .poll_timeout(Duration::from_millis(10));
25641            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
25642                Ok(json!({"late": "result"}))
25643            });
25644
25645            let error = worker
25646                .run_once()
25647                .await
25648                .expect_err(&format!("{name} must remain an error"));
25649            assert!(
25650                matches!(error, Error::Http { .. } | Error::Protocol(_)),
25651                "{name} returned an unexpected error variant: {error}"
25652            );
25653        }
25654    }
25655
25656    #[tokio::test]
25657    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
25658        let server = MockWorkerServer::start();
25659        let client = Client::builder(server.base_url())
25660            .worker_token(Some("worker-secret".to_string()))
25661            .namespace("orders")
25662            .timeout(Duration::from_secs(2))
25663            .build()
25664            .expect("client");
25665        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
25666
25667        let result = client
25668            .deregister_worker_registration("worker/α space")
25669            .await
25670            .expect("deregister worker registration");
25671
25672        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
25673        assert_eq!(
25674            server.worker_protocol_for(path).as_deref(),
25675            Some(WORKER_PROTOCOL_VERSION)
25676        );
25677        assert_eq!(server.control_protocol_for(path), None);
25678        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
25679        assert_eq!(
25680            server.authorization_for(path).as_deref(),
25681            Some("Bearer worker-secret")
25682        );
25683        assert_eq!(
25684            result,
25685            WorkerDeregistrationEnvelope {
25686                worker_id: "deregistered-worker".to_string(),
25687                outcome: "deregistered".to_string(),
25688                recovered_workflow_task_count: 2,
25689            }
25690        );
25691    }
25692
25693    #[tokio::test]
25694    async fn low_level_registration_rejects_update_validators_before_transport() {
25695        let server = MockWorkerServer::start();
25696        let client = Client::builder(server.base_url())
25697            .timeout(Duration::from_secs(2))
25698            .build()
25699            .expect("client");
25700
25701        for update_validators in [json!(["approve"]), json!("approve")] {
25702            let error = client
25703                .register_worker_with_command_contracts(
25704                    "validator-claiming-worker",
25705                    "rust-workers",
25706                    vec!["orders".to_string()],
25707                    vec![],
25708                    1,
25709                    1,
25710                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
25711                    json!({
25712                        "orders": {
25713                            "queries": ["current"],
25714                            "updates": ["approve"],
25715                            "update_validators": update_validators,
25716                        },
25717                    }),
25718                )
25719                .await
25720                .expect_err("unsupported validator claims must fail before registration");
25721
25722            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
25723                panic!("expected typed unsupported-validator failure");
25724            };
25725            assert_eq!(workflow_type, "orders");
25726        }
25727        assert_eq!(server.request_count("/api/worker/register"), 0);
25728    }
25729
25730    #[tokio::test]
25731    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
25732        let server = MockWorkerServer::start();
25733        let client = Client::builder(server.base_url())
25734            .timeout(Duration::from_secs(2))
25735            .build()
25736            .expect("client");
25737        let mut worker = Worker::new(client, "rust-workers");
25738        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
25739        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
25740        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
25741        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
25742        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
25743
25744        worker.register().await.expect("register handler contracts");
25745
25746        let declaration =
25747            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
25748        let expected_contracts = json!([
25749            {
25750                "name": "a-avro",
25751                "parameters": [{
25752                    "name": "args", "position": 0, "required": false,
25753                    "variadic": true, "type": null, "allows_null": true,
25754                    "default_available": false, "default": null,
25755                }],
25756            },
25757            {
25758                "name": "z-json",
25759                "parameters": [{
25760                    "name": "args", "position": 0, "required": false,
25761                    "variadic": true, "type": null, "allows_null": true,
25762                    "default_available": false, "default": null,
25763                }],
25764            },
25765        ]);
25766        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
25767        assert_eq!(declaration["query_contracts"], expected_contracts);
25768        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
25769        assert_eq!(declaration["update_contracts"], expected_contracts);
25770        assert_eq!(declaration["update_validators"], json!([]));
25771    }
25772
25773    #[tokio::test]
25774    async fn low_level_registration_preserves_query_and_update_contracts() {
25775        let server = MockWorkerServer::start();
25776        let client = Client::builder(server.base_url())
25777            .timeout(Duration::from_secs(2))
25778            .build()
25779            .expect("client");
25780        let contracts = json!({
25781            "orders": {
25782                "queries": ["current"],
25783                "updates": ["approve"],
25784                "update_validators": [],
25785            },
25786            "payments": {
25787                "queries": ["status"],
25788                "updates": ["capture"],
25789            },
25790        });
25791
25792        client
25793            .register_worker_with_command_contracts(
25794                "command-worker",
25795                "rust-workers",
25796                vec!["orders".to_string(), "payments".to_string()],
25797                vec![],
25798                1,
25799                1,
25800                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
25801                contracts.clone(),
25802            )
25803            .await
25804            .expect("query and update contracts must remain supported");
25805
25806        assert_eq!(
25807            server.request_body("/api/worker/register")["workflow_command_contracts"],
25808            contracts
25809        );
25810        assert!(server
25811            .request_body("/api/worker/register")
25812            .get("workflow_definition_fingerprints")
25813            .is_none());
25814    }
25815
25816    #[tokio::test]
25817    async fn rust_worker_advertises_source_backed_definition_and_clears_it_on_reregistration() {
25818        let server = MockWorkerServer::start();
25819        let client = Client::builder(server.base_url())
25820            .timeout(Duration::from_secs(2))
25821            .build()
25822            .expect("client");
25823        let mut worker = Worker::new(client, "rust-workers");
25824        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
25825
25826        assert!(worker
25827            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
25828            .is_err());
25829        assert!(worker
25830            .set_workflow_definition_sources("orders", &[])
25831            .is_err());
25832        worker
25833            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
25834            .expect("embed workflow source");
25835        worker.register().await.expect("register worker");
25836        let first = server.request_bodies("/api/worker/register")[0]
25837            ["workflow_definition_fingerprints"]["orders"]
25838            .as_str()
25839            .expect("source-backed fingerprint")
25840            .to_string();
25841        assert!(first.starts_with("sha256:"));
25842
25843        worker
25844            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
25845            .expect("change embedded helper source");
25846        worker.register().await.expect("register changed source");
25847        let changed = server.request_bodies("/api/worker/register")[1]
25848            ["workflow_definition_fingerprints"]["orders"]
25849            .as_str()
25850            .expect("changed fingerprint")
25851            .to_string();
25852        assert_ne!(first, changed);
25853
25854        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
25855        worker
25856            .register()
25857            .await
25858            .expect("register replacement handler");
25859        assert_eq!(
25860            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
25861            json!({})
25862        );
25863    }
25864
25865    #[tokio::test]
25866    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
25867        let server = MockWorkerServer::start();
25868        let control_only = Client::builder(server.base_url())
25869            .control_token(Some("control-secret".to_string()))
25870            .build()
25871            .expect("control client");
25872
25873        let error = control_only
25874            .register_worker("worker", "queue", vec![], vec![], 1, 1)
25875            .await
25876            .expect_err("control token must not authorize a worker request");
25877        assert!(matches!(
25878            error,
25879            Error::MissingRoleCredentials { role: "worker", .. }
25880        ));
25881        assert_eq!(server.request_count("/api/worker/register"), 0);
25882
25883        let worker_only = Client::builder(server.base_url())
25884            .worker_token(Some("worker-secret".to_string()))
25885            .build()
25886            .expect("worker client");
25887        let error = worker_only
25888            .health()
25889            .await
25890            .expect_err("worker token must not authorize a control request");
25891        assert!(matches!(
25892            error,
25893            Error::MissingRoleCredentials {
25894                role: "control",
25895                ..
25896            }
25897        ));
25898        assert_eq!(server.request_count("/api/health"), 0);
25899    }
25900
25901    #[tokio::test]
25902    async fn shared_token_supports_worker_and_control_planes() {
25903        let server = MockWorkerServer::start();
25904        let client = Client::builder(server.base_url())
25905            .token(Some("shared-secret".to_string()))
25906            .build()
25907            .expect("client");
25908
25909        client.health().await.expect("control request");
25910        client
25911            .register_worker("worker", "queue", vec![], vec![], 1, 1)
25912            .await
25913            .expect("worker request");
25914
25915        assert_eq!(
25916            server.authorization_for("/api/health").as_deref(),
25917            Some("Bearer shared-secret")
25918        );
25919        assert_eq!(
25920            server.control_protocol_for("/api/health").as_deref(),
25921            Some(CONTROL_PLANE_VERSION)
25922        );
25923        assert_eq!(
25924            server.authorization_for("/api/worker/register").as_deref(),
25925            Some("Bearer shared-secret")
25926        );
25927        assert_eq!(
25928            server
25929                .worker_protocol_for("/api/worker/register")
25930                .as_deref(),
25931            Some(WORKER_PROTOCOL_VERSION)
25932        );
25933    }
25934
25935    #[tokio::test]
25936    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
25937        let server = MockWorkerServer::start();
25938        let client = Client::builder(server.base_url())
25939            .timeout(Duration::from_secs(2))
25940            .build()
25941            .expect("client");
25942
25943        client
25944            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
25945            .await
25946            .expect("register");
25947        client
25948            .heartbeat_worker("capture-worker", 1, 1)
25949            .await
25950            .expect("heartbeat");
25951        client
25952            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
25953            .await
25954            .expect("workflow poll");
25955        client
25956            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
25957            .await
25958            .expect("activity poll");
25959
25960        for path in [
25961            "/api/worker/register",
25962            "/api/worker/heartbeat",
25963            "/api/worker/workflow-tasks/poll",
25964            "/api/worker/activity-tasks/poll",
25965        ] {
25966            assert_eq!(
25967                server.worker_protocol_for(path).as_deref(),
25968                Some(WORKER_PROTOCOL_VERSION),
25969                "unexpected protocol for {path}"
25970            );
25971        }
25972
25973        assert_eq!(
25974            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
25975            1
25976        );
25977        assert_eq!(
25978            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
25979            500
25980        );
25981        assert_eq!(
25982            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
25983            1
25984        );
25985        assert!(
25986            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
25987                .as_str()
25988                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
25989        );
25990        assert!(
25991            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
25992                .as_str()
25993                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
25994        );
25995    }
25996
25997    #[tokio::test]
25998    async fn query_task_endpoints_send_the_query_feature_protocol() {
25999        let server = MockWorkerServer::start();
26000        let client = Client::builder(server.base_url())
26001            .timeout(Duration::from_secs(2))
26002            .build()
26003            .expect("client");
26004
26005        client
26006            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26007            .await
26008            .expect("query poll");
26009        client
26010            .complete_query_task(
26011                "query-capture",
26012                "capture-worker",
26013                1,
26014                json!(8),
26015                DEFAULT_CODEC,
26016            )
26017            .await
26018            .expect("query complete");
26019        client
26020            .fail_query_task(
26021                "query-capture",
26022                "capture-worker",
26023                1,
26024                "failed",
26025                "query_rejected",
26026                "QueryFailed",
26027            )
26028            .await
26029            .expect("query fail");
26030
26031        for path in [
26032            "/api/worker/query-tasks/poll",
26033            "/api/worker/query-tasks/query-capture/complete",
26034            "/api/worker/query-tasks/query-capture/fail",
26035        ] {
26036            assert_eq!(
26037                server.worker_protocol_for(path).as_deref(),
26038                Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
26039                "unexpected protocol for {path}"
26040            );
26041        }
26042
26043        assert_eq!(
26044            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
26045            1
26046        );
26047        assert!(
26048            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
26049                .as_str()
26050                .is_some_and(|id| id.starts_with("rust-query-poll-"))
26051        );
26052    }
26053
26054    #[tokio::test]
26055    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
26056        let server = MockWorkerServer::transient_worker_failures();
26057        let client = Client::builder(server.base_url())
26058            .timeout(Duration::from_secs(2))
26059            .build()
26060            .expect("client");
26061
26062        client
26063            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
26064            .await
26065            .expect("workflow poll retry");
26066        client
26067            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
26068            .await
26069            .expect("activity poll retry");
26070        client
26071            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26072            .await
26073            .expect("query poll retry");
26074
26075        for path in [
26076            "/api/worker/workflow-tasks/poll",
26077            "/api/worker/activity-tasks/poll",
26078            "/api/worker/query-tasks/poll",
26079        ] {
26080            let bodies = server.request_bodies(path);
26081            assert_eq!(bodies.len(), 2, "{path} must be retried once");
26082            assert_eq!(
26083                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
26084                "{path} must preserve the request binding across retry"
26085            );
26086        }
26087    }
26088
26089    #[tokio::test]
26090    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
26091        let server = MockWorkerServer::consecutive_poll_failures(2);
26092        let client = Client::builder(server.base_url())
26093            .timeout(Duration::from_secs(2))
26094            .build()
26095            .expect("client");
26096        let mut worker = Worker::new(client, "capture")
26097            .worker_id("capture-worker")
26098            .poll_timeout(Duration::from_millis(10))
26099            .retry_policy(WorkerRetryPolicy {
26100                max_retries: 2,
26101                initial_backoff: Duration::from_millis(1),
26102                max_backoff: Duration::from_millis(1),
26103            });
26104        worker.register_workflow(
26105            "capture.workflow",
26106            |_ctx, _input| async move { Ok(Value::Null) },
26107        );
26108        worker.register_activity(
26109            "capture.activity",
26110            |_ctx, _input| async move { Ok(Value::Null) },
26111        );
26112        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
26113            Ok(Value::Null)
26114        });
26115
26116        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
26117
26118        for path in [
26119            "/api/worker/workflow-tasks/poll",
26120            "/api/worker/activity-tasks/poll",
26121            "/api/worker/query-tasks/poll",
26122        ] {
26123            let bodies = server.request_bodies(path);
26124            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
26125            assert!(
26126                bodies
26127                    .iter()
26128                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
26129                "{path} must preserve one request binding across every retry"
26130            );
26131        }
26132    }
26133
26134    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
26135        let reason = if unavailable {
26136            "storage_admission_unavailable"
26137        } else {
26138            "storage_pressure"
26139        };
26140        let mut body = json!({
26141            "reason": reason,
26142            "storage_state": if unavailable { "fenced" } else { "draining" },
26143            "retryable": true,
26144            "retry_after_seconds": 1,
26145        });
26146        if !mid_poll {
26147            body["request_admitted"] = json!(false);
26148        }
26149        if let Some(id) = poll_id {
26150            body["task"] = Value::Null;
26151            body["poll_status"] = json!(reason);
26152            body["poll_request_id"] = json!(id);
26153            body["retry_same_poll_request_id"] = json!(true);
26154            body["claim_admitted"] = json!(false);
26155        }
26156        body
26157    }
26158
26159    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
26160        let operation = match path {
26161            "/api/worker/register" => "register_worker",
26162            "/api/worker/heartbeat" => "heartbeat_worker",
26163            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
26164            "/api/worker/activity-tasks/poll" => "poll_activity_task",
26165            "/api/worker/query-tasks/poll" => "poll_query_task",
26166            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
26167            _ => return None,
26168        };
26169        let request: Value = serde_json::from_str(request).ok()?;
26170        let mut response = json!({
26171            "reason": "backend_unavailable",
26172            "operation": operation,
26173            "outcome": "unknown",
26174            "retryable": true,
26175            "retry_after_seconds": 1,
26176            "worker_id": request["worker_id"],
26177            "task_queue": request.get("task_queue"),
26178        });
26179        if path.ends_with("/poll") {
26180            response["task"] = Value::Null;
26181            response["poll_status"] = json!("backend_unavailable");
26182            response["poll_request_id"] = request["poll_request_id"].clone();
26183            response["retry_same_poll_request_id"] = json!(true);
26184        }
26185        Some(response)
26186    }
26187
26188    fn backend_retry_override(
26189        path: &str,
26190        request: &str,
26191        number: usize,
26192    ) -> Option<(&'static str, String)> {
26193        if number > 8 {
26194            return None;
26195        }
26196        Some((
26197            "503 Service Unavailable",
26198            backend_refusal(path, request)?.to_string(),
26199        ))
26200    }
26201
26202    fn backend_unavailable_override(
26203        path: &str,
26204        request: &str,
26205        _number: usize,
26206    ) -> Option<(&'static str, String)> {
26207        Some((
26208            "503 Service Unavailable",
26209            backend_refusal(path, request)?.to_string(),
26210        ))
26211    }
26212
26213    fn storage_worker(server: &MockWorkerServer) -> Worker {
26214        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
26215            .worker_id("storage-worker")
26216            .retry_policy(WorkerRetryPolicy {
26217                max_retries: 1,
26218                initial_backoff: Duration::from_millis(1),
26219                max_backoff: Duration::from_millis(1),
26220            })
26221    }
26222
26223    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
26224        let requests = server.requests.lock().expect("requests");
26225        let bodies: Vec<_> = requests
26226            .iter()
26227            .filter(|request| request.path == path)
26228            .map(|request| &request.body)
26229            .collect();
26230        assert_eq!(bodies.len(), count, "{path}");
26231        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
26232    }
26233
26234    #[test]
26235    fn backend_recovery_requires_the_explicit_worker_contract() {
26236        for (path, operation) in [
26237            ("/worker/register", "register_worker"),
26238            ("/worker/heartbeat", "heartbeat_worker"),
26239            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
26240            ("/worker/activity-tasks/poll", "poll_activity_task"),
26241            ("/worker/query-tasks/poll", "poll_query_task"),
26242            (
26243                "/worker/update-validation-tasks/poll",
26244                "poll_update_validation_task",
26245            ),
26246        ] {
26247            let poll_id = path.ends_with("/poll").then_some("same-poll");
26248            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
26249            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
26250                .expect("worker operation");
26251            assert_eq!(body["operation"], operation);
26252            let error = Error::Http {
26253                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26254                body: body.to_string(),
26255            };
26256            assert_eq!(
26257                worker_backend_unavailable_retry_after(&error, path, poll_id),
26258                Some(Duration::from_secs(1))
26259            );
26260            assert!(!worker_operation_is_retryable(&error));
26261            for (field, value) in [
26262                ("operation", json!("wrong_operation")),
26263                ("outcome", json!("completed")),
26264                ("retryable", json!(false)),
26265                ("retry_after_seconds", json!(0)),
26266                ("worker_id", json!("")),
26267            ] {
26268                let mut invalid = body.clone();
26269                invalid[field] = value;
26270                let error = Error::Http {
26271                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26272                    body: invalid.to_string(),
26273                };
26274                assert!(
26275                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
26276                    "{path}: {field}"
26277                );
26278                assert!(!worker_operation_is_retryable(&error));
26279            }
26280            if let Some(poll_id) = poll_id {
26281                for (field, value) in [
26282                    ("poll_request_id", json!("wrong-poll")),
26283                    ("poll_status", json!("empty")),
26284                    ("task", json!({"task_id":"claimed"})),
26285                    ("retry_same_poll_request_id", json!(false)),
26286                ] {
26287                    let mut invalid = body.clone();
26288                    invalid[field] = value;
26289                    let error = Error::Http {
26290                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26291                        body: invalid.to_string(),
26292                    };
26293                    assert!(
26294                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
26295                            .is_none(),
26296                        "{path}: {field}"
26297                    );
26298                }
26299            }
26300            let error = Error::Http {
26301                status: reqwest::StatusCode::UNAUTHORIZED,
26302                body: body.to_string(),
26303            };
26304            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
26305            assert!(!worker_operation_is_retryable(&error));
26306        }
26307    }
26308
26309    #[tokio::test]
26310    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
26311        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26312            request_override: Some(backend_retry_override),
26313            ..MockWorkerBehavior::default()
26314        });
26315        let mut worker =
26316            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26317        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
26318        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
26319        worker.register_query("backend.workflow", "state", |_, _| async {
26320            Ok(Value::Null)
26321        });
26322        worker.register().await.expect("registration recovery");
26323        worker
26324            .client
26325            .heartbeat_worker("storage-worker", 1, 1)
26326            .await
26327            .expect("heartbeat recovery");
26328        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
26329        for path in [
26330            "/api/worker/register",
26331            "/api/worker/heartbeat",
26332            "/api/worker/workflow-tasks/poll",
26333            "/api/worker/activity-tasks/poll",
26334            "/api/worker/query-tasks/poll",
26335        ] {
26336            assert_identical_requests(&server, path, 9);
26337        }
26338    }
26339
26340    #[tokio::test]
26341    async fn backend_recovery_wait_stops_with_worker() {
26342        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26343            request_override: Some(backend_unavailable_override),
26344            ..MockWorkerBehavior::default()
26345        });
26346        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
26347            max_retries: 1,
26348            initial_backoff: Duration::from_secs(2),
26349            max_backoff: Duration::from_secs(2),
26350        });
26351        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
26352        let started = tokio::time::Instant::now();
26353        let _ = tokio::time::timeout(
26354            Duration::from_secs(1),
26355            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
26356        )
26357        .await
26358        .expect("shutdown interrupts backend wait");
26359        assert!(started.elapsed() < Duration::from_secs(1));
26360        assert!(server.request_count("/api/worker/register") >= 1);
26361    }
26362
26363    #[test]
26364    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
26365        for unavailable in [false, true] {
26366            for mid_poll in [false, true] {
26367                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
26368                let error = Error::Http {
26369                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26370                    body: body.to_string(),
26371                };
26372                assert_eq!(
26373                    worker_storage_admission_retry_after(&error, Some("same-poll")),
26374                    Some(Duration::from_secs(1))
26375                );
26376                assert!(
26377                    !worker_operation_is_retryable(&error),
26378                    "storage is not a bounded generic retry"
26379                );
26380                for (field, value) in [
26381                    ("poll_request_id", json!("wrong-poll")),
26382                    ("task", json!({"task_id":"claimed"})),
26383                    ("retryable", json!(false)),
26384                    ("retry_after_seconds", json!(0)),
26385                    ("retry_after_seconds", json!(true)),
26386                    ("retry_after_seconds", json!(1.0)),
26387                    ("storage_state", json!("normal")),
26388                    ("poll_status", json!("empty")),
26389                    ("claim_admitted", json!(true)),
26390                    ("retry_same_poll_request_id", json!(false)),
26391                    ("request_admitted", json!(true)),
26392                ] {
26393                    let mut invalid = body.clone();
26394                    invalid[field] = value;
26395                    let error = Error::Http {
26396                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26397                        body: invalid.to_string(),
26398                    };
26399                    assert!(
26400                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
26401                        "{field}"
26402                    );
26403                }
26404            }
26405        }
26406        let body = storage_refusal(None, false, false);
26407        let error = Error::Http {
26408            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26409            body: body.to_string(),
26410        };
26411        assert!(worker_storage_admission_retry_after(&error, None).is_some());
26412        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
26413        let error = Error::Http {
26414            status: reqwest::StatusCode::FORBIDDEN,
26415            body: body.to_string(),
26416        };
26417        assert!(worker_storage_admission_retry_after(&error, None).is_none());
26418        let body = storage_refusal(None, false, true);
26419        let error = Error::Http {
26420            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26421            body: body.to_string(),
26422        };
26423        assert!(worker_storage_admission_retry_after(&error, None).is_none());
26424    }
26425
26426    #[tokio::test]
26427    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
26428        for unavailable in [false, true] {
26429            for mid_poll in [false, true] {
26430                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26431                    poll_failures_per_path: 1,
26432                    storage_refusals: 7,
26433                    storage_path: Some("/poll"),
26434                    storage_unavailable: unavailable,
26435                    storage_mid_poll: mid_poll,
26436                    ..MockWorkerBehavior::default()
26437                });
26438                let mut worker = storage_worker(&server);
26439                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
26440                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
26441                for path in [
26442                    "/api/worker/workflow-tasks/poll",
26443                    "/api/worker/activity-tasks/poll",
26444                    "/api/worker/query-tasks/poll",
26445                ] {
26446                    assert_identical_requests(&server, path, 9);
26447                }
26448            }
26449        }
26450    }
26451
26452    #[tokio::test]
26453    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
26454        struct CountedBody(Arc<AtomicUsize>);
26455        impl Serialize for CountedBody {
26456            fn serialize<S: Serializer>(
26457                &self,
26458                serializer: S,
26459            ) -> std::result::Result<S::Ok, S::Error> {
26460                let count = self.0.fetch_add(1, Ordering::SeqCst);
26461                json!({"serialization":count,"lease_owner":"worker","attempt":7})
26462                    .serialize(serializer)
26463            }
26464        }
26465        for path in [
26466            "/api/worker/register",
26467            "/api/worker/heartbeat",
26468            "/api/worker/workflow-tasks/storage-task/complete",
26469            "/api/worker/workflow-tasks/storage-task/fail",
26470            "/api/worker/activity-tasks/storage-task/complete",
26471            "/api/worker/activity-tasks/storage-task/fail",
26472            "/api/worker/activity-tasks/storage-task/heartbeat",
26473            "/api/worker/query-tasks/storage-task/complete",
26474            "/api/worker/query-tasks/storage-task/fail",
26475        ] {
26476            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26477                storage_refusals: 7,
26478                storage_path: Some(path),
26479                ..MockWorkerBehavior::default()
26480            });
26481            let worker =
26482                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26483            let calls = Arc::new(AtomicUsize::new(0));
26484            let _: Value = worker
26485                .client
26486                .request_json(
26487                    reqwest::Method::POST,
26488                    &path[4..],
26489                    RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
26490                    Some(&CountedBody(Arc::clone(&calls))),
26491                )
26492                .await
26493                .expect("prepared request recovery");
26494            assert_eq!(calls.load(Ordering::SeqCst), 1);
26495            assert_identical_requests(&server, path, 8);
26496        }
26497        for worker_scope in [false, true] {
26498            let path = if worker_scope {
26499                "/api/health"
26500            } else {
26501                "/api/worker/register"
26502            };
26503            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26504                storage_refusals: usize::MAX,
26505                storage_path: Some(path),
26506                ..MockWorkerBehavior::default()
26507            });
26508            let worker = storage_worker(&server);
26509            let client = worker.client.clone();
26510            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
26511            let error = if worker_scope {
26512                worker
26513                    .client
26514                    .health()
26515                    .await
26516                    .expect_err("control plane is not retried")
26517            } else {
26518                client
26519                    .request_json::<Value, Value>(
26520                        reqwest::Method::POST,
26521                        "/worker/register",
26522                        RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
26523                        Some(&json!({})),
26524                    )
26525                    .await
26526                    .expect_err("direct client is not retried")
26527            };
26528            assert!(worker_storage_admission_body(&error).is_some());
26529            assert_eq!(server.request_count(path), 1);
26530        }
26531    }
26532
26533    #[tokio::test]
26534    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
26535        for fail in [false, true] {
26536            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26537                storage_activity: true,
26538                storage_refusals: 7,
26539                storage_path: Some("/storage-activity/"),
26540                ..MockWorkerBehavior::default()
26541            });
26542            let mut worker = storage_worker(&server);
26543            let calls = Arc::new(AtomicUsize::new(0));
26544            let observed = Arc::clone(&calls);
26545            worker.register_activity("storage.activity", move |ctx, _| {
26546                let calls = Arc::clone(&observed);
26547                async move {
26548                    calls.fetch_add(1, Ordering::SeqCst);
26549                    ctx.heartbeat(json!({"step":2})).await?;
26550                    if fail {
26551                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
26552                    } else {
26553                        Ok(json!({"receipt":true}))
26554                    }
26555                }
26556            });
26557            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
26558            assert_eq!(calls.load(Ordering::SeqCst), 1);
26559            assert_identical_requests(
26560                &server,
26561                "/api/worker/activity-tasks/storage-activity/heartbeat",
26562                8,
26563            );
26564            let suffix = if fail { "fail" } else { "complete" };
26565            assert_identical_requests(
26566                &server,
26567                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
26568                8,
26569            );
26570            let other = if fail { "complete" } else { "fail" };
26571            assert_eq!(
26572                server.request_count(&format!(
26573                    "/api/worker/activity-tasks/storage-activity/{other}"
26574                )),
26575                0
26576            );
26577        }
26578    }
26579
26580    #[tokio::test]
26581    async fn storage_waits_are_interruptible_without_false_activity_failure() {
26582        for path in [
26583            "/api/worker/register",
26584            "/api/worker/heartbeat",
26585            "/api/worker/activity-tasks/poll",
26586            "/api/worker/activity-tasks/storage-activity/heartbeat",
26587            "/api/worker/activity-tasks/storage-activity/complete",
26588        ] {
26589            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26590                storage_activity: true,
26591                storage_refusals: usize::MAX,
26592                storage_path: Some(path),
26593                ..MockWorkerBehavior::default()
26594            });
26595            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
26596            worker.register_activity("storage.activity", |ctx, _| async move {
26597                ctx.heartbeat(json!({"step":2})).await?;
26598                Ok(json!({"receipt":true}))
26599            });
26600            let shutdown = async {
26601                while server.request_count(path) == 0 {
26602                    tokio::time::sleep(Duration::from_millis(1)).await;
26603                }
26604            };
26605            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
26606                .await
26607                .expect("shutdown interrupts admission");
26608            assert!(
26609                result.is_err(),
26610                "a refused operation must not appear acknowledged: {path}, {result:?}"
26611            );
26612            assert_eq!(server.request_count(path), 1);
26613            assert_eq!(
26614                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
26615                0
26616            );
26617            assert_eq!(
26618                server.request_count("/api/worker/registrations/mock-worker"),
26619                usize::from(!path.ends_with("/register"))
26620            );
26621        }
26622    }
26623
26624    #[tokio::test]
26625    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
26626        for fail in [false, true] {
26627            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26628                storage_query: true,
26629                storage_refusals: 7,
26630                storage_path: Some("/storage-query/"),
26631                ..MockWorkerBehavior::default()
26632            });
26633            let mut worker = storage_worker(&server);
26634            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
26635            let calls = Arc::new(AtomicUsize::new(0));
26636            let observed = Arc::clone(&calls);
26637            worker.register_query("storage.workflow", "state", move |_, _| {
26638                let calls = Arc::clone(&observed);
26639                async move {
26640                    calls.fetch_add(1, Ordering::SeqCst);
26641                    if fail {
26642                        Err(Error::WorkerLoop("intentional query failure".to_string()))
26643                    } else {
26644                        Ok(json!({"state":"waiting"}))
26645                    }
26646                }
26647            });
26648            assert_eq!(worker.run_once().await.expect("query settled"), 1);
26649            assert_eq!(calls.load(Ordering::SeqCst), 1);
26650            let suffix = if fail { "fail" } else { "complete" };
26651            assert_identical_requests(
26652                &server,
26653                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
26654                8,
26655            );
26656            let other = if fail { "complete" } else { "fail" };
26657            assert_eq!(
26658                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
26659                0
26660            );
26661        }
26662    }
26663
26664    #[tokio::test]
26665    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
26666        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26667            storage_refusals: 7,
26668            storage_path: Some("/poll"),
26669            unauthorized_polls: true,
26670            ..MockWorkerBehavior::default()
26671        });
26672        let error = storage_worker(&server)
26673            .run_once()
26674            .await
26675            .expect_err("auth remains terminal");
26676        assert!(matches!(
26677            error,
26678            Error::Http {
26679                status: reqwest::StatusCode::UNAUTHORIZED,
26680                ..
26681            }
26682        ));
26683        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
26684
26685        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26686            storage_refusals: 7,
26687            storage_path: Some("/activity-cancel/complete"),
26688            ..MockWorkerBehavior::default()
26689        });
26690        let worker =
26691            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26692        let error = worker
26693            .client
26694            .complete_activity_task(
26695                "activity-cancel",
26696                "attempt-cancel",
26697                "worker",
26698                json!({}),
26699                DEFAULT_CODEC,
26700            )
26701            .await
26702            .expect_err("cancellation remains terminal");
26703        assert!(activity_task_rejection_is_final(&error));
26704        assert_identical_requests(
26705            &server,
26706            "/api/worker/activity-tasks/activity-cancel/complete",
26707            8,
26708        );
26709
26710        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26711            storage_refusals: usize::MAX,
26712            storage_path: Some("/poll"),
26713            storage_wrong_poll_id: true,
26714            ..MockWorkerBehavior::default()
26715        });
26716        assert!(storage_worker(&server).run_once().await.is_err());
26717        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
26718    }
26719
26720    #[tokio::test]
26721    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
26722        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26723            storage_refusals: usize::MAX,
26724            storage_path: Some("/poll"),
26725            ..MockWorkerBehavior::default()
26726        });
26727        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
26728        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
26729        let run = tokio::spawn(async move { worker.run().await });
26730        tokio::time::timeout(Duration::from_secs(2), async {
26731            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
26732                tokio::time::sleep(Duration::from_millis(1)).await;
26733            }
26734        })
26735        .await
26736        .expect("poll started");
26737        run.abort();
26738        assert!(run.await.expect_err("cancelled run").is_cancelled());
26739        tokio::time::sleep(Duration::from_millis(250)).await;
26740        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
26741    }
26742
26743    #[tokio::test]
26744    async fn query_protocol_rejection_from_older_server_is_typed() {
26745        let server = MockWorkerServer::reject_query_protocol();
26746        let client = Client::builder(server.base_url())
26747            .timeout(Duration::from_secs(2))
26748            .build()
26749            .expect("client");
26750
26751        let error = client
26752            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26753            .await
26754            .expect_err("server below query protocol floor must reject");
26755        let Error::Protocol(failure) = error else {
26756            panic!("expected typed protocol failure");
26757        };
26758
26759        assert_eq!(failure.status, 400);
26760        assert_eq!(failure.reason, "unsupported_protocol_version");
26761        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
26762        assert_eq!(
26763            failure.requested_version.as_deref(),
26764            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
26765        );
26766        assert_eq!(
26767            server
26768                .worker_protocol_for("/api/worker/query-tasks/poll")
26769                .as_deref(),
26770            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
26771        );
26772    }
26773
26774    #[tokio::test]
26775    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
26776        let server = MockWorkerServer::reject_query_protocol();
26777        let client = Client::builder(server.base_url())
26778            .timeout(Duration::from_secs(2))
26779            .build()
26780            .expect("client");
26781        let mut worker = Worker::new(client, "rust-workers")
26782            .worker_id("baseline-worker")
26783            .poll_timeout(Duration::from_millis(10));
26784
26785        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
26786            Ok(Value::Null)
26787        });
26788
26789        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
26790        assert_eq!(
26791            server
26792                .worker_protocol_for("/api/worker/workflow-tasks/poll")
26793                .as_deref(),
26794            Some(WORKER_PROTOCOL_VERSION)
26795        );
26796        assert_eq!(
26797            server.worker_protocol_for("/api/worker/query-tasks/poll"),
26798            None,
26799            "a worker without query handlers must not use the query-task endpoint"
26800        );
26801    }
26802
26803    #[tokio::test]
26804    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
26805        let server = MockWorkerServer::reject_query_completion();
26806        let client = Client::builder(server.base_url())
26807            .timeout(Duration::from_secs(2))
26808            .build()
26809            .expect("client");
26810
26811        let error = client
26812            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
26813            .await
26814            .expect_err("expired completion must be rejected");
26815        let Error::QueryFailed(failure) = error else {
26816            panic!("expected typed query failure");
26817        };
26818        assert_eq!(failure.status, 409);
26819        assert_eq!(failure.reason, "query_task_timed_out");
26820
26821        let mut worker = Worker::new(client, "rust-workers")
26822            .worker_id("late-worker")
26823            .poll_timeout(Duration::from_millis(10));
26824        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26825        worker.register_query(
26826            "counter",
26827            "current",
26828            |_ctx, _args| async move { Ok(json!(8)) },
26829        );
26830
26831        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
26832        assert_eq!(
26833            worker
26834                .run_once()
26835                .await
26836                .expect("worker continues after late completion"),
26837            0
26838        );
26839        assert_eq!(
26840            server.request_count("/api/worker/query-tasks/query-late/complete"),
26841            2
26842        );
26843        assert_eq!(
26844            server.request_count("/api/worker/query-tasks/query-late/fail"),
26845            0,
26846            "a server completion rejection must not be reported as an encoding failure"
26847        );
26848    }
26849
26850    #[tokio::test]
26851    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
26852        let server = MockWorkerServer::start();
26853        let client = Client::builder(server.base_url())
26854            .timeout(Duration::from_secs(2))
26855            .build()
26856            .expect("client");
26857        let mut worker = Worker::new(client, "rust-workers")
26858            .worker_id("joined-worker")
26859            .poll_timeout(Duration::from_millis(10));
26860        worker.register_workflow(
26861            "joined.workflow",
26862            |_ctx, _input| async move { Ok(Value::Null) },
26863        );
26864        worker.register_activity(
26865            "joined.activity",
26866            |_ctx, _input| async move { Ok(Value::Null) },
26867        );
26868        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
26869            Ok(Value::Null)
26870        });
26871
26872        worker
26873            .run_until(tokio::time::sleep(Duration::from_millis(20)))
26874            .await
26875            .expect("normal shutdown");
26876
26877        let deregistration_path = "/api/worker/registrations/mock-worker";
26878        assert_eq!(server.request_count(deregistration_path), 1);
26879        for poll_path in [
26880            "/api/worker/workflow-tasks/poll",
26881            "/api/worker/activity-tasks/poll",
26882            "/api/worker/query-tasks/poll",
26883        ] {
26884            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
26885        }
26886        assert_eq!(
26887            server.captured_paths().last().map(String::as_str),
26888            Some(deregistration_path),
26889            "deregistration must start only after every poller has joined"
26890        );
26891    }
26892
26893    #[tokio::test]
26894    async fn registration_failure_does_not_deregister() {
26895        let server = MockWorkerServer::rejected_registration();
26896        let client = Client::builder(server.base_url())
26897            .timeout(Duration::from_secs(2))
26898            .build()
26899            .expect("client");
26900        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
26901
26902        let error = worker
26903            .run_until(async {})
26904            .await
26905            .expect_err("registration must fail");
26906        assert!(matches!(
26907            error,
26908            Error::Http {
26909                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26910                ..
26911            }
26912        ));
26913        assert!(server
26914            .captured_paths()
26915            .iter()
26916            .all(|path| !path.starts_with("/api/worker/registrations/")));
26917    }
26918
26919    #[tokio::test]
26920    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
26921        let server = MockWorkerServer::rejected_registration_protocol();
26922        let client = Client::builder(server.base_url())
26923            .timeout(Duration::from_secs(2))
26924            .build()
26925            .expect("client");
26926        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
26927
26928        let error = worker
26929            .run_until(async {})
26930            .await
26931            .expect_err("a protocol 1.16 server must reject this worker");
26932        let Error::Protocol(failure) = error else {
26933            panic!("expected typed protocol rejection");
26934        };
26935        assert_eq!(failure.reason, "unsupported_protocol_version");
26936        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
26937        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
26938        assert_eq!(
26939            server
26940                .worker_protocol_for("/api/worker/register")
26941                .as_deref(),
26942            Some(WORKER_PROTOCOL_VERSION)
26943        );
26944    }
26945
26946    #[tokio::test]
26947    async fn declined_registration_does_not_deregister() {
26948        let server = MockWorkerServer::declined_registration();
26949        let client = Client::builder(server.base_url())
26950            .timeout(Duration::from_secs(2))
26951            .build()
26952            .expect("client");
26953        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
26954
26955        let error = worker
26956            .run_until(async {})
26957            .await
26958            .expect_err("declined registration must fail");
26959        assert!(matches!(error, Error::WorkerLoop(_)));
26960        assert!(error.to_string().contains("was not accepted"));
26961        assert!(server
26962            .captured_paths()
26963            .iter()
26964            .all(|path| !path.starts_with("/api/worker/registrations/")));
26965    }
26966
26967    #[tokio::test]
26968    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
26969        let server = MockWorkerServer::rejected_deregistration();
26970        let client = Client::builder(server.base_url())
26971            .timeout(Duration::from_secs(2))
26972            .build()
26973            .expect("client");
26974        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
26975
26976        let error = worker
26977            .run_until(async {})
26978            .await
26979            .expect_err("deregistration must fail");
26980        assert!(matches!(
26981            error,
26982            Error::Http {
26983                status: reqwest::StatusCode::FORBIDDEN,
26984                ..
26985            }
26986        ));
26987        assert_eq!(
26988            server.request_count("/api/worker/registrations/mock-worker"),
26989            1
26990        );
26991    }
26992
26993    #[tokio::test]
26994    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
26995        let server = MockWorkerServer::rejected_deregistration_protocol();
26996        let client = Client::builder(server.base_url())
26997            .timeout(Duration::from_secs(2))
26998            .build()
26999            .expect("client");
27000        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
27001
27002        let error = worker
27003            .run_until(async {})
27004            .await
27005            .expect_err("protocol rejection must fail shutdown");
27006        let Error::Protocol(failure) = error else {
27007            panic!("expected typed protocol failure");
27008        };
27009        assert_eq!(failure.reason, "unsupported_protocol_version");
27010        assert_eq!(
27011            failure.requested_version.as_deref(),
27012            Some(WORKER_PROTOCOL_VERSION)
27013        );
27014        assert_eq!(
27015            server.request_count("/api/worker/registrations/mock-worker"),
27016            1
27017        );
27018    }
27019
27020    #[tokio::test]
27021    async fn primary_poller_error_retains_deregistration_failure_context() {
27022        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
27023        let client = Client::builder(server.base_url())
27024            .timeout(Duration::from_secs(2))
27025            .build()
27026            .expect("client");
27027        let mut worker = Worker::new(client, "rust-workers")
27028            .worker_id("combined-failure")
27029            .poll_timeout(Duration::from_millis(10));
27030        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
27031            Ok(Value::Null)
27032        });
27033
27034        let error = worker
27035            .run()
27036            .await
27037            .expect_err("worker and cleanup must fail");
27038        let summary = error.to_string();
27039        assert!(summary.contains("authentication_failed"));
27040        assert!(summary.contains("worker cannot deregister"));
27041        let Error::WorkerShutdown {
27042            primary,
27043            deregistration,
27044        } = error
27045        else {
27046            panic!("expected combined worker shutdown error");
27047        };
27048        assert!(matches!(
27049            *primary,
27050            Error::Http {
27051                status: reqwest::StatusCode::UNAUTHORIZED,
27052                ..
27053            }
27054        ));
27055        assert!(matches!(
27056            *deregistration,
27057            Error::Http {
27058                status: reqwest::StatusCode::FORBIDDEN,
27059                ..
27060            }
27061        ));
27062        assert_eq!(
27063            server.request_count("/api/worker/registrations/mock-worker"),
27064            1
27065        );
27066    }
27067
27068    #[tokio::test]
27069    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
27070        let server = MockWorkerServer::start();
27071        let client = Client::builder(server.base_url())
27072            .timeout(Duration::from_secs(2))
27073            .build()
27074            .expect("client");
27075        let mut worker = Worker::new(client, "rust-workers")
27076            .worker_id("activity-only-worker")
27077            .poll_timeout(Duration::from_millis(10));
27078
27079        worker.register_activity(
27080            "activity.only",
27081            |_ctx, _args| async move { Ok(Value::Null) },
27082        );
27083
27084        worker.run_until(async {}).await.expect("run worker");
27085    }
27086
27087    #[tokio::test]
27088    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
27089        let server = MockWorkerServer::start();
27090        let client = Client::builder(server.base_url())
27091            .timeout(Duration::from_secs(2))
27092            .build()
27093            .expect("client");
27094        let mut worker = Worker::new(client, "rust-workers")
27095            .worker_id("workflow-only-worker")
27096            .poll_timeout(Duration::from_millis(10));
27097
27098        worker.register_workflow(
27099            "workflow.only",
27100            |_ctx, _input| async move { Ok(Value::Null) },
27101        );
27102
27103        worker.run_until(async {}).await.expect("run worker");
27104    }
27105
27106    #[tokio::test]
27107    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
27108        let server = MockWorkerServer::start();
27109        let client = Client::builder(server.base_url())
27110            .timeout(Duration::from_secs(2))
27111            .build()
27112            .expect("client");
27113        let observations = Arc::new(Mutex::new(Vec::new()));
27114        let observed = Arc::clone(&observations);
27115        let mut worker = Worker::new(client, "rust-workers")
27116            .worker_id("observed-heartbeat-worker")
27117            .poll_timeout(Duration::from_millis(10))
27118            .on_worker_heartbeat(move |observation| {
27119                observed
27120                    .lock()
27121                    .expect("heartbeat observations")
27122                    .push(observation.clone());
27123            });
27124
27125        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
27126            Ok(Value::Null)
27127        });
27128        let acknowledged = Arc::clone(&observations);
27129        worker
27130            .run_until(async move {
27131                tokio::time::timeout(Duration::from_secs(2), async move {
27132                    loop {
27133                        if !acknowledged
27134                            .lock()
27135                            .expect("heartbeat observations")
27136                            .is_empty()
27137                        {
27138                            break;
27139                        }
27140                        tokio::time::sleep(Duration::from_millis(1)).await;
27141                    }
27142                })
27143                .await
27144                .expect("heartbeat acknowledgement within timeout");
27145            })
27146            .await
27147            .expect("run worker");
27148
27149        let observations = observations.lock().expect("heartbeat observations");
27150        let first = observations.first().expect("heartbeat acknowledgement");
27151        assert_eq!(first.worker_id, "observed-heartbeat-worker");
27152        assert_eq!(first.task_queue, "rust-workers");
27153        assert!(first.acknowledged_at_unix_millis > 0);
27154        assert_eq!(first.acknowledgement, json!({}));
27155    }
27156
27157    #[tokio::test]
27158    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
27159        let server = MockWorkerServer::delayed_heartbeat_worker();
27160        let client = Client::builder(server.base_url())
27161            .timeout(Duration::from_secs(3))
27162            .build()
27163            .expect("client");
27164        let observations = Arc::new(Mutex::new(Vec::new()));
27165        let observed = Arc::clone(&observations);
27166        let mut worker = Worker::new(client, "rust-snapshot-workers")
27167            .worker_id("rust-snapshot-worker")
27168            .poll_timeout(Duration::from_millis(10))
27169            .on_worker_heartbeat(move |observation| {
27170                observed
27171                    .lock()
27172                    .expect("heartbeat observations")
27173                    .push(observation.clone());
27174            });
27175
27176        worker.register_workflow("snapshot", |ctx, _input| async move {
27177            ctx.wait_signal("finish").await?;
27178            Ok(json!({"status": "finished"}))
27179        });
27180        worker.register_query("snapshot", "current", |ctx, _args| async move {
27181            Ok(json!(ctx
27182                .signals("increment")
27183                .iter()
27184                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
27185                .sum::<i64>()))
27186        });
27187        worker.register_activity("cancel-aware", |_ctx, _args| async move {
27188            Ok(json!({"late": "completion"}))
27189        });
27190
27191        worker
27192            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
27193            .await
27194            .expect("delayed heartbeat must allow a clean worker shutdown");
27195
27196        let observations = observations.lock().expect("heartbeat observations");
27197        assert!(
27198            observations.len() >= 3,
27199            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
27200        );
27201        assert!(
27202            observations.windows(2).all(|pair| {
27203                pair[1].acknowledged_at_unix_millis
27204                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
27205                    >= 850
27206            }),
27207            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
27208        );
27209        drop(observations);
27210
27211        let heartbeat_times = server.request_times("/api/worker/heartbeat");
27212        let delayed_request_at = *heartbeat_times
27213            .get(1)
27214            .expect("intentionally delayed heartbeat request");
27215        let delay_window_start = delayed_request_at + Duration::from_millis(100);
27216        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
27217        for path in [
27218            "/api/worker/workflow-tasks/poll",
27219            "/api/worker/activity-tasks/poll",
27220            "/api/worker/query-tasks/poll",
27221        ] {
27222            assert!(
27223                server
27224                    .request_times(path)
27225                    .iter()
27226                    .any(|received_at| *received_at >= delay_window_start
27227                        && *received_at <= delay_window_end),
27228                "{path} must keep polling while a heartbeat acknowledgement is delayed"
27229            );
27230        }
27231        assert!(
27232            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
27233            "workflow work must be settled"
27234        );
27235        assert!(
27236            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
27237            "activity work must be settled"
27238        );
27239        assert!(
27240            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
27241            "query work must be settled"
27242        );
27243    }
27244
27245    #[tokio::test]
27246    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
27247        let server = MockWorkerServer::heartbeat_retry_worker();
27248        let client = Client::builder(server.base_url())
27249            .timeout(Duration::from_secs(2))
27250            .build()
27251            .expect("client");
27252        let observations = Arc::new(Mutex::new(Vec::new()));
27253        let observed = Arc::clone(&observations);
27254        let worker = Worker::new(client, "rust-workers")
27255            .worker_id("heartbeat-retry-worker")
27256            .retry_policy(WorkerRetryPolicy {
27257                max_retries: 1,
27258                initial_backoff: Duration::from_millis(300),
27259                max_backoff: Duration::from_millis(300),
27260            })
27261            .on_worker_heartbeat(move |observation| {
27262                observed
27263                    .lock()
27264                    .expect("heartbeat observations")
27265                    .push(observation.clone());
27266            });
27267
27268        worker
27269            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
27270            .await
27271            .expect("retryable heartbeat failure must remain bounded and recover");
27272
27273        let observations = observations.lock().expect("heartbeat observations");
27274        assert!(observations.len() >= 3, "heartbeat retry must recover");
27275        assert!(
27276            observations.windows(2).all(|pair| {
27277                pair[1]
27278                    .acknowledged_at_unix_millis
27279                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
27280                    >= 850
27281            }),
27282            "a successful retry must start a fresh advertised cadence: {observations:?}"
27283        );
27284        assert_eq!(
27285            server.request_count("/api/worker/heartbeat"),
27286            observations.len() + 1,
27287            "one retryable failure must add exactly one bounded request"
27288        );
27289    }
27290
27291    #[tokio::test]
27292    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
27293        let server = MockWorkerServer::waiting_query_worker();
27294        let client = Client::builder(server.base_url())
27295            .timeout(Duration::from_secs(2))
27296            .build()
27297            .expect("client");
27298        let observations = Arc::new(Mutex::new(Vec::new()));
27299        let observed = Arc::clone(&observations);
27300        let mut worker = Worker::new(client, "rust-snapshot-workers")
27301            .worker_id("rust-snapshot-worker")
27302            .poll_timeout(Duration::from_millis(10))
27303            .on_worker_heartbeat(move |observation| {
27304                observed
27305                    .lock()
27306                    .expect("heartbeat observations")
27307                    .push(observation.clone());
27308            });
27309
27310        worker.register_workflow("snapshot", |ctx, _input| async move {
27311            ctx.wait_signal("finish").await?;
27312            Ok(json!({"status": "finished"}))
27313        });
27314        worker.register_query("snapshot", "current", |ctx, _args| async move {
27315            let current = ctx
27316                .signals("increment")
27317                .iter()
27318                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
27319                .sum::<i64>();
27320            Ok(json!(current))
27321        });
27322        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
27323
27324        worker
27325            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
27326            .await
27327            .expect("pending workflow and query poller must remain live until shutdown");
27328
27329        assert!(
27330            observations.lock().expect("heartbeat observations").len() >= 4,
27331            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
27332        );
27333        assert!(
27334            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
27335            "workflow polling must continue after empty replay acknowledgements"
27336        );
27337        assert!(
27338            server.request_count("/api/worker/query-tasks/poll") >= 2,
27339            "query polling must continue after serving the current query"
27340        );
27341        assert_eq!(
27342            server.request_body("/api/worker/register")["capabilities"],
27343            json!([
27344                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
27345                DURABLE_SELECTION_CAPABILITY,
27346                MEMO_UPSERTS_CAPABILITY,
27347                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
27348                QUERY_TASKS_CAPABILITY,
27349                WORKFLOW_UPDATES_CAPABILITY,
27350                MESSAGE_STREAMS_CAPABILITY
27351            ])
27352        );
27353        assert_eq!(
27354            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
27355            json!({
27356                "queries": ["current"],
27357                "query_contracts": [{
27358                    "name": "current",
27359                    "parameters": [{
27360                        "name": "args", "position": 0, "required": false,
27361                        "variadic": true, "type": null, "allows_null": true,
27362                        "default_available": false, "default": null,
27363                    }],
27364                }],
27365                "signals": [],
27366                "signal_contracts": [],
27367                "updates": ["replace"],
27368                "update_contracts": [{
27369                    "name": "replace",
27370                    "parameters": [{
27371                        "name": "args", "position": 0, "required": false,
27372                        "variadic": true, "type": null, "allows_null": true,
27373                        "default_available": false, "default": null,
27374                    }],
27375                }],
27376                "update_validators": [],
27377            })
27378        );
27379
27380        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
27381        assert_eq!(
27382            opened["commands"],
27383            json!([{
27384                "type": "open_signal_wait",
27385                "signal_name": "finish",
27386            }])
27387        );
27388
27389        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
27390            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
27391            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
27392            let failure = server.request_body(&fail_path);
27393            assert_eq!(
27394                failure["failure"]["type"],
27395                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
27396            );
27397            assert_eq!(server.request_count(&completion_path), 0);
27398        }
27399
27400        let query_completion =
27401            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
27402        assert_eq!(query_completion["result"], json!(8));
27403
27404        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
27405        assert_eq!(
27406            server.request_count(terminal_path),
27407            1,
27408            "the matching signal must settle the workflow exactly once"
27409        );
27410        let terminal = server.request_body(terminal_path);
27411        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
27412        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
27413        assert_eq!(
27414            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
27415                .expect("terminal workflow result"),
27416            json!({"status": "finished"})
27417        );
27418    }
27419
27420    #[tokio::test]
27421    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
27422        let server = MockWorkerServer::transient_worker_failures();
27423        let client = Client::builder(server.base_url())
27424            .timeout(Duration::from_secs(2))
27425            .build()
27426            .expect("client");
27427        let mut worker = Worker::new(client, "rust-workers")
27428            .worker_id("retry-worker")
27429            .poll_timeout(Duration::from_millis(10))
27430            .retry_policy(WorkerRetryPolicy {
27431                max_retries: 2,
27432                initial_backoff: Duration::from_millis(1),
27433                max_backoff: Duration::from_millis(1),
27434            });
27435        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27436        worker.register_activity(
27437            "counter.activity",
27438            |_ctx, _input| async move { Ok(Value::Null) },
27439        );
27440        worker.register_query(
27441            "counter",
27442            "current",
27443            |_ctx, _args| async move { Ok(json!(8)) },
27444        );
27445
27446        worker
27447            .run_until(tokio::time::sleep(Duration::from_millis(75)))
27448            .await
27449            .expect("transient failures must not stop the worker");
27450
27451        for path in [
27452            "/api/worker/heartbeat",
27453            "/api/worker/workflow-tasks/poll",
27454            "/api/worker/activity-tasks/poll",
27455            "/api/worker/query-tasks/poll",
27456        ] {
27457            assert!(
27458                server.request_count(path) >= 2,
27459                "{path} must continue after its transient failure"
27460            );
27461        }
27462    }
27463
27464    #[tokio::test]
27465    async fn worker_continues_after_long_poll_capacity_backpressure() {
27466        let server = MockWorkerServer::capacity_limited_activity_poll();
27467        let client = Client::builder(server.base_url())
27468            .timeout(Duration::from_secs(2))
27469            .build()
27470            .expect("client");
27471        let mut worker = Worker::new(client, "rust-workers")
27472            .worker_id("capacity-worker")
27473            .poll_timeout(Duration::from_millis(10))
27474            .retry_policy(WorkerRetryPolicy {
27475                max_retries: 0,
27476                initial_backoff: Duration::from_millis(1),
27477                max_backoff: Duration::from_millis(1),
27478            });
27479        worker.register_activity("capacity.activity", |_ctx, _input| async move {
27480            Ok(json!({"handled": true}))
27481        });
27482
27483        worker
27484            .run_until(tokio::time::sleep(Duration::from_millis(50)))
27485            .await
27486            .expect("capacity backpressure must not stop the worker");
27487
27488        assert!(
27489            server.request_count("/api/worker/activity-tasks/poll") >= 2,
27490            "the activity poller must continue after capacity backpressure"
27491        );
27492        assert_eq!(
27493            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
27494            1,
27495            "the worker must complete work returned after capacity recovers"
27496        );
27497    }
27498
27499    #[test]
27500    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
27501        let capacity = Error::Http {
27502            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27503            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
27504        };
27505        assert_eq!(
27506            worker_poll_capacity_retry_after(&capacity),
27507            Some(Duration::from_secs(3))
27508        );
27509
27510        let rejected_capacity = Error::Http {
27511            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27512            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
27513        };
27514        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
27515        assert!(!worker_operation_is_retryable(&rejected_capacity));
27516
27517        let ordinary_rate_limit = Error::Http {
27518            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27519            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
27520                .to_string(),
27521        };
27522        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
27523        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
27524    }
27525
27526    #[tokio::test]
27527    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
27528        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27529            poll_failures_per_path: 8,
27530            heartbeat_failures: 8,
27531            ..MockWorkerBehavior::default()
27532        });
27533        let client = Client::builder(server.base_url())
27534            .timeout(Duration::from_secs(2))
27535            .build()
27536            .expect("client");
27537        let acknowledgements = Arc::new(AtomicUsize::new(0));
27538        let observed = Arc::clone(&acknowledgements);
27539        let mut worker = Worker::new(client, "rust-workers")
27540            .recover_transient_outages(true)
27541            .poll_timeout(Duration::from_millis(10))
27542            .retry_policy(WorkerRetryPolicy {
27543                max_retries: 2,
27544                initial_backoff: Duration::from_millis(2),
27545                max_backoff: Duration::from_millis(5),
27546            })
27547            .on_worker_heartbeat(move |_| {
27548                observed.fetch_add(1, Ordering::SeqCst);
27549            });
27550        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27551        worker.register_activity(
27552            "counter.activity",
27553            |_ctx, _input| async move { Ok(Value::Null) },
27554        );
27555        worker.register_query("counter", "current", |_ctx, _args| async move {
27556            Ok(Value::Null)
27557        });
27558
27559        worker
27560            .run_until(tokio::time::sleep(Duration::from_millis(500)))
27561            .await
27562            .expect("a recoverable outage must not stop the service worker");
27563
27564        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
27565        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
27566        for path in [
27567            "/api/worker/workflow-tasks/poll",
27568            "/api/worker/activity-tasks/poll",
27569            "/api/worker/query-tasks/poll",
27570        ] {
27571            let bodies = server.request_bodies(path);
27572            assert!(bodies.len() >= 10, "{path} must resume after recovery");
27573            let first = &bodies[0]["poll_request_id"];
27574            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
27575            for body in &bodies[..9] {
27576                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
27577            }
27578            assert_ne!(&bodies[9]["poll_request_id"], first);
27579            let times = server.request_times(path);
27580            for pair in times[..9].windows(2) {
27581                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
27582            }
27583        }
27584    }
27585
27586    #[tokio::test]
27587    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
27588        for heartbeat_outage in [false, true] {
27589            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27590                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
27591                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
27592                ..MockWorkerBehavior::default()
27593            });
27594            let client = Client::builder(server.base_url()).build().expect("client");
27595            let mut worker = Worker::new(client, "rust-workers")
27596                .recover_transient_outages(true)
27597                .retry_policy(WorkerRetryPolicy {
27598                    max_retries: 1,
27599                    initial_backoff: Duration::from_secs(5),
27600                    max_backoff: Duration::from_secs(5),
27601                });
27602            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27603            let started = Instant::now();
27604            worker
27605                .run_until(tokio::time::sleep(Duration::from_millis(200)))
27606                .await
27607                .expect("shutdown during an outage is a normal stop");
27608            assert!(started.elapsed() < Duration::from_secs(1));
27609            let path = if heartbeat_outage {
27610                "/api/worker/heartbeat"
27611            } else {
27612                "/api/worker/workflow-tasks/poll"
27613            };
27614            assert_eq!(server.request_count(path), 1);
27615            assert_eq!(
27616                server.request_count("/api/worker/registrations/mock-worker"),
27617                1
27618            );
27619        }
27620    }
27621
27622    #[tokio::test]
27623    async fn worker_outage_recovery_keeps_run_once_bounded() {
27624        let server = MockWorkerServer::unavailable_polls();
27625        let client = Client::builder(server.base_url()).build().expect("client");
27626        let mut worker = Worker::new(client, "rust-workers")
27627            .recover_transient_outages(true)
27628            .retry_policy(WorkerRetryPolicy {
27629                max_retries: 2,
27630                initial_backoff: Duration::from_millis(1),
27631                max_backoff: Duration::from_millis(1),
27632            });
27633        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27634        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
27635        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
27636    }
27637
27638    #[tokio::test]
27639    async fn worker_outage_recovery_respects_disabled_retries() {
27640        let server = MockWorkerServer::unavailable_polls();
27641        let client = Client::builder(server.base_url()).build().expect("client");
27642        let mut worker = Worker::new(client, "rust-workers")
27643            .recover_transient_outages(true)
27644            .retry_policy(WorkerRetryPolicy {
27645                max_retries: 0,
27646                ..WorkerRetryPolicy::default()
27647            });
27648        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27649        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
27650        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27651    }
27652
27653    #[tokio::test]
27654    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
27655        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27656            heartbeat_failures: usize::MAX,
27657            unauthorized_polls: true,
27658            ..MockWorkerBehavior::default()
27659        });
27660        let client = Client::builder(server.base_url()).build().expect("client");
27661        let mut worker = Worker::new(client, "rust-workers")
27662            .recover_transient_outages(true)
27663            .retry_policy(WorkerRetryPolicy {
27664                max_retries: 1,
27665                initial_backoff: Duration::from_secs(5),
27666                max_backoff: Duration::from_secs(5),
27667            });
27668        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27669        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
27670            .await
27671            .expect("fatal poll errors must interrupt heartbeat recovery")
27672            .expect_err("authentication failure is terminal");
27673        assert!(
27674            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
27675        );
27676        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27677    }
27678
27679    #[tokio::test]
27680    async fn worker_bounds_transport_retries() {
27681        let server = MockWorkerServer::unavailable_polls();
27682        let client = Client::builder(server.base_url())
27683            .timeout(Duration::from_secs(2))
27684            .build()
27685            .expect("client");
27686        let mut worker = Worker::new(client, "rust-workers")
27687            .worker_id("bounded-retry-worker")
27688            .poll_timeout(Duration::from_millis(10))
27689            .retry_policy(WorkerRetryPolicy {
27690                max_retries: 2,
27691                initial_backoff: Duration::from_millis(1),
27692                max_backoff: Duration::from_millis(1),
27693            });
27694        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27695
27696        let error = worker.run().await.expect_err("retry bound must terminate");
27697        assert!(matches!(error, Error::Transport(_)));
27698        assert_eq!(
27699            server.request_count("/api/worker/workflow-tasks/poll"),
27700            3,
27701            "one initial request plus exactly two retries"
27702        );
27703    }
27704
27705    #[tokio::test]
27706    async fn worker_retry_policy_can_disable_poll_retries() {
27707        let server = MockWorkerServer::unavailable_polls();
27708        let client = Client::builder(server.base_url())
27709            .timeout(Duration::from_secs(2))
27710            .build()
27711            .expect("client");
27712        let mut worker = Worker::new(client, "rust-workers")
27713            .worker_id("no-retry-worker")
27714            .poll_timeout(Duration::from_millis(10))
27715            .retry_policy(WorkerRetryPolicy {
27716                max_retries: 0,
27717                initial_backoff: Duration::from_millis(1),
27718                max_backoff: Duration::from_millis(1),
27719            });
27720        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27721
27722        let error = worker
27723            .run_once()
27724            .await
27725            .expect_err("disabled retries must return the first transport failure");
27726        assert!(matches!(error, Error::Transport(_)));
27727        assert_eq!(
27728            server.request_count("/api/worker/workflow-tasks/poll"),
27729            1,
27730            "max_retries=0 must send only the initial request"
27731        );
27732    }
27733
27734    #[tokio::test]
27735    async fn worker_does_not_retry_authentication_failures() {
27736        let server = MockWorkerServer::unauthorized_polls();
27737        let client = Client::builder(server.base_url())
27738            .timeout(Duration::from_secs(2))
27739            .build()
27740            .expect("client");
27741        let mut worker = Worker::new(client, "rust-workers")
27742            .worker_id("unauthorized-worker")
27743            .recover_transient_outages(true)
27744            .poll_timeout(Duration::from_millis(10));
27745        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27746
27747        let error = worker
27748            .run()
27749            .await
27750            .expect_err("authentication must terminate");
27751        let Error::Http { status, body } = error else {
27752            panic!("expected stable HTTP authentication error");
27753        };
27754        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
27755        assert!(body.contains("authentication_failed"));
27756        assert_eq!(
27757            server.request_count("/api/worker/workflow-tasks/poll"),
27758            1,
27759            "authentication failures must not be retried"
27760        );
27761    }
27762
27763    #[derive(Clone, Debug)]
27764    struct CapturedRequest {
27765        headers: String,
27766        method: String,
27767        path: String,
27768        authorization: Option<String>,
27769        namespace: Option<String>,
27770        worker_protocol: Option<String>,
27771        control_protocol: Option<String>,
27772        body: String,
27773        received_at: Instant,
27774    }
27775
27776    struct MockWorkerServer {
27777        addr: SocketAddr,
27778        stop: Arc<AtomicBool>,
27779        requests: Arc<Mutex<Vec<CapturedRequest>>>,
27780        thread: Option<thread::JoinHandle<()>>,
27781    }
27782
27783    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
27784
27785    #[derive(Clone, Copy, Default)]
27786    struct MockWorkerBehavior {
27787        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
27788        request_override: Option<RequestOverride>,
27789        storage_refusals: usize,
27790        storage_path: Option<&'static str>,
27791        storage_unavailable: bool,
27792        storage_mid_poll: bool,
27793        storage_activity: bool,
27794        storage_query: bool,
27795        storage_wrong_poll_id: bool,
27796        reject_query_protocol: bool,
27797        reject_query_completion: bool,
27798        waiting_query_worker: bool,
27799        decline_registration: bool,
27800        complete_named_signal: bool,
27801        poll_failures_per_path: usize,
27802        long_poll_capacity_responses_per_path: usize,
27803        heartbeat_failures: usize,
27804        heartbeat_failure_request: Option<usize>,
27805        delayed_heartbeat_request: Option<usize>,
27806        heartbeat_response_delay: Duration,
27807        concurrent_requests: bool,
27808        unauthorized_polls: bool,
27809        reject_registration: bool,
27810        reject_registration_protocol: bool,
27811        reject_deregistration: bool,
27812        reject_deregistration_protocol: bool,
27813        cancelled_activity: bool,
27814        draining_polls: bool,
27815        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
27816        workflow_completion_status: Option<&'static str>,
27817        workflow_completion_body: Option<&'static str>,
27818    }
27819
27820    impl MockWorkerServer {
27821        fn start() -> Self {
27822            Self::start_with_behavior(MockWorkerBehavior::default())
27823        }
27824
27825        fn reject_query_protocol() -> Self {
27826            Self::start_with_behavior(MockWorkerBehavior {
27827                reject_query_protocol: true,
27828                ..MockWorkerBehavior::default()
27829            })
27830        }
27831
27832        fn reject_query_completion() -> Self {
27833            Self::start_with_behavior(MockWorkerBehavior {
27834                reject_query_completion: true,
27835                ..MockWorkerBehavior::default()
27836            })
27837        }
27838
27839        fn waiting_query_worker() -> Self {
27840            Self::start_with_behavior(MockWorkerBehavior {
27841                waiting_query_worker: true,
27842                complete_named_signal: true,
27843                ..MockWorkerBehavior::default()
27844            })
27845        }
27846
27847        fn transient_worker_failures() -> Self {
27848            Self::start_with_behavior(MockWorkerBehavior {
27849                poll_failures_per_path: 1,
27850                heartbeat_failures: 1,
27851                ..MockWorkerBehavior::default()
27852            })
27853        }
27854
27855        fn consecutive_poll_failures(count: usize) -> Self {
27856            Self::start_with_behavior(MockWorkerBehavior {
27857                poll_failures_per_path: count,
27858                ..MockWorkerBehavior::default()
27859            })
27860        }
27861
27862        fn capacity_limited_activity_poll() -> Self {
27863            Self::start_with_behavior(MockWorkerBehavior {
27864                long_poll_capacity_responses_per_path: 1,
27865                ..MockWorkerBehavior::default()
27866            })
27867        }
27868
27869        fn delayed_heartbeat_worker() -> Self {
27870            Self::start_with_behavior(MockWorkerBehavior {
27871                waiting_query_worker: true,
27872                delayed_heartbeat_request: Some(2),
27873                heartbeat_response_delay: Duration::from_millis(1_500),
27874                concurrent_requests: true,
27875                cancelled_activity: true,
27876                ..MockWorkerBehavior::default()
27877            })
27878        }
27879
27880        fn heartbeat_retry_worker() -> Self {
27881            Self::start_with_behavior(MockWorkerBehavior {
27882                waiting_query_worker: true,
27883                heartbeat_failure_request: Some(2),
27884                concurrent_requests: true,
27885                ..MockWorkerBehavior::default()
27886            })
27887        }
27888
27889        fn unavailable_polls() -> Self {
27890            Self::start_with_behavior(MockWorkerBehavior {
27891                poll_failures_per_path: usize::MAX,
27892                ..MockWorkerBehavior::default()
27893            })
27894        }
27895
27896        fn unauthorized_polls() -> Self {
27897            Self::start_with_behavior(MockWorkerBehavior {
27898                unauthorized_polls: true,
27899                ..MockWorkerBehavior::default()
27900            })
27901        }
27902
27903        fn rejected_registration() -> Self {
27904            Self::start_with_behavior(MockWorkerBehavior {
27905                reject_registration: true,
27906                ..MockWorkerBehavior::default()
27907            })
27908        }
27909
27910        fn rejected_registration_protocol() -> Self {
27911            Self::start_with_behavior(MockWorkerBehavior {
27912                reject_registration_protocol: true,
27913                ..MockWorkerBehavior::default()
27914            })
27915        }
27916
27917        fn declined_registration() -> Self {
27918            Self::start_with_behavior(MockWorkerBehavior {
27919                decline_registration: true,
27920                ..MockWorkerBehavior::default()
27921            })
27922        }
27923
27924        fn rejected_deregistration() -> Self {
27925            Self::start_with_behavior(MockWorkerBehavior {
27926                reject_deregistration: true,
27927                ..MockWorkerBehavior::default()
27928            })
27929        }
27930
27931        fn rejected_deregistration_protocol() -> Self {
27932            Self::start_with_behavior(MockWorkerBehavior {
27933                reject_deregistration_protocol: true,
27934                ..MockWorkerBehavior::default()
27935            })
27936        }
27937
27938        fn unauthorized_polls_and_rejected_deregistration() -> Self {
27939            Self::start_with_behavior(MockWorkerBehavior {
27940                unauthorized_polls: true,
27941                reject_deregistration: true,
27942                ..MockWorkerBehavior::default()
27943            })
27944        }
27945
27946        fn cancelled_activity() -> Self {
27947            Self::start_with_behavior(MockWorkerBehavior {
27948                cancelled_activity: true,
27949                ..MockWorkerBehavior::default()
27950            })
27951        }
27952
27953        fn draining_polls() -> Self {
27954            Self::start_with_behavior(MockWorkerBehavior {
27955                draining_polls: true,
27956                ..MockWorkerBehavior::default()
27957            })
27958        }
27959
27960        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
27961            Self::start_with_behavior(MockWorkerBehavior {
27962                invalid_task_payload_codec: Some(codec),
27963                ..MockWorkerBehavior::default()
27964            })
27965        }
27966
27967        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
27968            Self::start_with_behavior(MockWorkerBehavior {
27969                workflow_completion_status: Some(status),
27970                workflow_completion_body: Some(body),
27971                ..MockWorkerBehavior::default()
27972            })
27973        }
27974
27975        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
27976            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
27977            listener
27978                .set_nonblocking(true)
27979                .expect("configure mock listener");
27980            let addr = listener.local_addr().expect("mock server address");
27981            let stop = Arc::new(AtomicBool::new(false));
27982            let server_stop = Arc::clone(&stop);
27983            let requests = Arc::new(Mutex::new(Vec::new()));
27984            let server_requests = Arc::clone(&requests);
27985            let thread = thread::spawn(move || {
27986                let mut request_threads = Vec::new();
27987                while !server_stop.load(Ordering::SeqCst) {
27988                    match listener.accept() {
27989                        Ok((mut stream, _)) => {
27990                            if behavior.concurrent_requests {
27991                                let requests = Arc::clone(&server_requests);
27992                                request_threads.push(thread::spawn(move || {
27993                                    handle_mock_worker_request(&mut stream, &requests, behavior)
27994                                }));
27995                            } else {
27996                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
27997                            }
27998                        }
27999                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
28000                            let mut index = 0;
28001                            while index < request_threads.len() {
28002                                if request_threads[index].is_finished() {
28003                                    request_threads
28004                                        .swap_remove(index)
28005                                        .join()
28006                                        .expect("join mock request");
28007                                } else {
28008                                    index += 1;
28009                                }
28010                            }
28011                            thread::sleep(Duration::from_millis(5));
28012                        }
28013                        Err(_) => break,
28014                    }
28015                }
28016                for request_thread in request_threads {
28017                    request_thread.join().expect("join mock request");
28018                }
28019            });
28020
28021            Self {
28022                addr,
28023                stop,
28024                requests,
28025                thread: Some(thread),
28026            }
28027        }
28028
28029        fn base_url(&self) -> String {
28030            format!("http://{}", self.addr)
28031        }
28032
28033        fn worker_protocol_for(&self, path: &str) -> Option<String> {
28034            self.requests
28035                .lock()
28036                .expect("captured requests")
28037                .iter()
28038                .find(|request| request.path == path)
28039                .and_then(|request| request.worker_protocol.clone())
28040        }
28041
28042        fn control_protocol_for(&self, path: &str) -> Option<String> {
28043            self.requests
28044                .lock()
28045                .expect("captured requests")
28046                .iter()
28047                .find(|request| request.path == path)
28048                .and_then(|request| request.control_protocol.clone())
28049        }
28050
28051        fn method_for(&self, path: &str) -> Option<String> {
28052            self.requests
28053                .lock()
28054                .expect("captured requests")
28055                .iter()
28056                .find(|request| request.path == path)
28057                .map(|request| request.method.clone())
28058        }
28059
28060        fn authorization_for(&self, path: &str) -> Option<String> {
28061            self.requests
28062                .lock()
28063                .expect("captured requests")
28064                .iter()
28065                .find(|request| request.path == path)
28066                .and_then(|request| request.authorization.clone())
28067        }
28068
28069        fn namespace_for(&self, path: &str) -> Option<String> {
28070            self.requests
28071                .lock()
28072                .expect("captured requests")
28073                .iter()
28074                .find(|request| request.path == path)
28075                .and_then(|request| request.namespace.clone())
28076        }
28077
28078        fn request_count(&self, path: &str) -> usize {
28079            self.requests
28080                .lock()
28081                .expect("captured requests")
28082                .iter()
28083                .filter(|request| request.path == path)
28084                .count()
28085        }
28086
28087        fn captured_paths(&self) -> Vec<String> {
28088            self.requests
28089                .lock()
28090                .expect("captured requests")
28091                .iter()
28092                .map(|request| request.path.clone())
28093                .collect()
28094        }
28095
28096        fn request_times(&self, path: &str) -> Vec<Instant> {
28097            self.requests
28098                .lock()
28099                .expect("captured requests")
28100                .iter()
28101                .filter(|request| request.path == path)
28102                .map(|request| request.received_at)
28103                .collect()
28104        }
28105
28106        fn request_body(&self, path: &str) -> Value {
28107            let requests = self.requests.lock().expect("captured requests");
28108            let body = &requests
28109                .iter()
28110                .find(|request| request.path == path)
28111                .unwrap_or_else(|| panic!("missing request for {path}"))
28112                .body;
28113            serde_json::from_str(body).unwrap_or_else(|error| {
28114                panic!("invalid JSON request body for {path}: {error}: {body:?}")
28115            })
28116        }
28117
28118        fn request_bodies(&self, path: &str) -> Vec<Value> {
28119            self.requests
28120                .lock()
28121                .expect("captured requests")
28122                .iter()
28123                .filter(|request| request.path == path)
28124                .map(|request| {
28125                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
28126                        panic!(
28127                            "invalid JSON request body for {path}: {error}: {:?}",
28128                            request.body
28129                        )
28130                    })
28131                })
28132                .collect()
28133        }
28134    }
28135
28136    impl Drop for MockWorkerServer {
28137        fn drop(&mut self) {
28138            self.stop.store(true, Ordering::SeqCst);
28139            let _ = TcpStream::connect(self.addr);
28140
28141            if let Some(thread) = self.thread.take() {
28142                thread.join().expect("join mock server");
28143            }
28144        }
28145    }
28146
28147    fn handle_mock_worker_request(
28148        stream: &mut TcpStream,
28149        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
28150        behavior: MockWorkerBehavior,
28151    ) {
28152        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
28153        let mut buffer = [0_u8; 8192];
28154        let mut request = Vec::new();
28155
28156        loop {
28157            match stream.read(&mut buffer) {
28158                Ok(0) => break,
28159                Ok(read) => {
28160                    request.extend_from_slice(&buffer[..read]);
28161                    if mock_request_is_complete(&request) {
28162                        break;
28163                    }
28164                }
28165                Err(error)
28166                    if matches!(
28167                        error.kind(),
28168                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
28169                    ) =>
28170                {
28171                    break;
28172                }
28173                Err(_) => return,
28174            }
28175        }
28176
28177        let request = String::from_utf8_lossy(&request);
28178        let body = request
28179            .split_once("\r\n\r\n")
28180            .map(|(_, body)| body)
28181            .unwrap_or_default();
28182        let path = request
28183            .lines()
28184            .next()
28185            .and_then(|line| line.split_whitespace().nth(1))
28186            .unwrap_or_default();
28187        let method = request
28188            .lines()
28189            .next()
28190            .and_then(|line| line.split_whitespace().next())
28191            .unwrap_or_default();
28192        let authorization = request.lines().find_map(|line| {
28193            let (name, value) = line.split_once(':')?;
28194            name.eq_ignore_ascii_case("Authorization")
28195                .then(|| value.trim().to_string())
28196        });
28197        let namespace = request.lines().find_map(|line| {
28198            let (name, value) = line.split_once(':')?;
28199            name.eq_ignore_ascii_case("X-Namespace")
28200                .then(|| value.trim().to_string())
28201        });
28202        let worker_protocol = request.lines().find_map(|line| {
28203            let (name, value) = line.split_once(':')?;
28204            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
28205                .then(|| value.trim().to_string())
28206        });
28207        let control_protocol = request.lines().find_map(|line| {
28208            let (name, value) = line.split_once(':')?;
28209            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
28210                .then(|| value.trim().to_string())
28211        });
28212        let request_number = {
28213            let mut requests = requests.lock().expect("captured requests");
28214            requests.push(CapturedRequest {
28215                headers: request
28216                    .split_once("\r\n\r\n")
28217                    .map_or("", |(headers, _)| headers)
28218                    .to_owned(),
28219                method: method.to_string(),
28220                path: path.to_string(),
28221                authorization,
28222                namespace,
28223                worker_protocol: worker_protocol.clone(),
28224                control_protocol,
28225                body: body.to_string(),
28226                received_at: Instant::now(),
28227            });
28228            requests
28229                .iter()
28230                .filter(|request| request.path == path)
28231                .count()
28232        };
28233
28234        if let Some(response) = behavior
28235            .request_override
28236            .and_then(|handler| handler(path, body, request_number))
28237        {
28238            write_mock_response(stream, response.0, &response.1);
28239            return;
28240        }
28241        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
28242            write_mock_response(stream, response.0, &response.1);
28243            return;
28244        }
28245        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
28246            return;
28247        }
28248        let pressure_path = behavior
28249            .storage_path
28250            .is_some_and(|part| path.contains(part));
28251        let prior_failures = if path.ends_with("/poll") {
28252            behavior.poll_failures_per_path
28253        } else {
28254            0
28255        };
28256        if pressure_path
28257            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
28258        {
28259            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
28260            let poll_id = path
28261                .ends_with("/poll")
28262                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
28263            let mut refusal = storage_refusal(
28264                poll_id,
28265                behavior.storage_unavailable,
28266                behavior.storage_mid_poll,
28267            );
28268            if behavior.storage_wrong_poll_id {
28269                refusal["poll_request_id"] = json!("wrong-poll");
28270            }
28271            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
28272            return;
28273        }
28274        if path.contains("/storage-task/")
28275            || path.contains("/storage-activity/")
28276            || path.contains("/storage-query/")
28277        {
28278            write_mock_response(stream, "200 OK", "{}");
28279            return;
28280        }
28281        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
28282            write_mock_response(stream, "200 OK", &json!({"task":{
28283                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
28284                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
28285                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28286                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28287                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
28288            }}).to_string());
28289            return;
28290        }
28291        if behavior.storage_activity
28292            && path == "/api/worker/activity-tasks/poll"
28293            && request_number == 1
28294        {
28295            write_mock_response(stream, "200 OK", &json!({"task":{
28296                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
28297                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28298                "attempt_number":7, "lease_owner":"storage-worker"
28299            }}).to_string());
28300            return;
28301        }
28302
28303        if path == "/api/worker/register" {
28304            if behavior.reject_registration_protocol {
28305                write_mock_response(
28306                    stream,
28307                    "400 Bad Request",
28308                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
28309                );
28310                return;
28311            }
28312            if behavior.reject_registration {
28313                write_mock_response(
28314                    stream,
28315                    "503 Service Unavailable",
28316                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
28317                );
28318                return;
28319            }
28320        }
28321
28322        if path.starts_with("/api/worker/registrations/") {
28323            if behavior.reject_deregistration_protocol {
28324                write_mock_response(
28325                    stream,
28326                    "400 Bad Request",
28327                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.19"}"#,
28328                );
28329            } else if behavior.reject_deregistration {
28330                write_mock_response(
28331                    stream,
28332                    "403 Forbidden",
28333                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
28334                );
28335            } else {
28336                write_mock_response(
28337                    stream,
28338                    "200 OK",
28339                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
28340                );
28341            }
28342            return;
28343        }
28344
28345        let is_poll = matches!(
28346            path,
28347            "/api/worker/workflow-tasks/poll"
28348                | "/api/worker/activity-tasks/poll"
28349                | "/api/worker/query-tasks/poll"
28350        );
28351        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
28352            write_mock_response(
28353                stream,
28354                "429 Too Many Requests",
28355                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
28356            );
28357            return;
28358        }
28359        if is_poll && request_number <= behavior.poll_failures_per_path {
28360            return;
28361        }
28362        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
28363            return;
28364        }
28365        if path == "/api/worker/heartbeat"
28366            && behavior.heartbeat_failure_request == Some(request_number)
28367        {
28368            return;
28369        }
28370        if path == "/api/worker/heartbeat"
28371            && behavior.delayed_heartbeat_request == Some(request_number)
28372        {
28373            thread::sleep(behavior.heartbeat_response_delay);
28374        }
28375        if behavior.unauthorized_polls && is_poll {
28376            write_mock_response(
28377                stream,
28378                "401 Unauthorized",
28379                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
28380            );
28381            return;
28382        }
28383        if behavior.draining_polls && is_poll {
28384            write_mock_response(
28385                stream,
28386                "409 Conflict",
28387                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
28388            );
28389            return;
28390        }
28391
28392        if let Some(codec_case) = behavior.invalid_task_payload_codec {
28393            if is_poll && request_number == 1 {
28394                let mut task = match path {
28395                    "/api/worker/workflow-tasks/poll" => json!({
28396                        "task_id": "codec-workflow",
28397                        "workflow_type": "codec.workflow",
28398                        "payload_codec": DEFAULT_CODEC,
28399                        "workflow_task_attempt": 1,
28400                        "lease_owner": "codec-worker"
28401                    }),
28402                    "/api/worker/activity-tasks/poll" => json!({
28403                        "task_id": "codec-activity",
28404                        "activity_attempt_id": "codec-activity-attempt",
28405                        "activity_type": "codec.activity",
28406                        "payload_codec": DEFAULT_CODEC,
28407                        "attempt_number": 1,
28408                        "lease_owner": "codec-worker"
28409                    }),
28410                    "/api/worker/query-tasks/poll" => json!({
28411                        "query_task_id": "codec-query",
28412                        "query_task_attempt": 1,
28413                        "workflow_type": "codec.workflow",
28414                        "query_name": "known",
28415                        "payload_codec": DEFAULT_CODEC,
28416                        "lease_owner": "codec-worker"
28417                    }),
28418                    _ => unreachable!("is_poll limits task codec probe paths"),
28419                };
28420                codec_case.apply(&mut task);
28421                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
28422                return;
28423            }
28424
28425            if matches!(
28426                path,
28427                "/api/worker/workflow-tasks/codec-workflow/fail"
28428                    | "/api/worker/activity-tasks/codec-activity/fail"
28429                    | "/api/worker/query-tasks/codec-query/fail"
28430            ) {
28431                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
28432                return;
28433            }
28434        }
28435
28436        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
28437            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
28438            let body = format!(
28439                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
28440            );
28441            write_mock_response(stream, "400 Bad Request", &body);
28442            return;
28443        }
28444
28445        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
28446        {
28447            write_mock_response(
28448                stream,
28449                "409 Conflict",
28450                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
28451            );
28452            return;
28453        }
28454
28455        if behavior.workflow_completion_status.is_some()
28456            && path == "/api/worker/workflow-tasks/poll"
28457            && request_number == 1
28458        {
28459            write_mock_response(
28460                stream,
28461                "200 OK",
28462                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"}}"#,
28463            );
28464            return;
28465        }
28466
28467        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
28468            if let (Some(status), Some(body)) = (
28469                behavior.workflow_completion_status,
28470                behavior.workflow_completion_body,
28471            ) {
28472                write_mock_response(stream, status, body);
28473                return;
28474            }
28475        }
28476
28477        if behavior.waiting_query_worker {
28478            if behavior.complete_named_signal
28479                && path == "/api/worker/workflow-tasks/poll"
28480                && request_number == 1
28481            {
28482                let body = json!({
28483                    "task": {
28484                        "task_id": "snapshot-open",
28485                        "workflow_id": "snapshot-1",
28486                        "run_id": "snapshot-run-1",
28487                        "workflow_type": "snapshot",
28488                        "payload_codec": DEFAULT_CODEC,
28489                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28490                            .expect("Avro workflow arguments"),
28491                        "history_events": [],
28492                        "workflow_task_attempt": 1,
28493                        "lease_owner": "rust-snapshot-worker"
28494                    }
28495                })
28496                .to_string();
28497                write_mock_response(stream, "200 OK", &body);
28498                return;
28499            }
28500
28501            let signal_request = request_number - usize::from(behavior.complete_named_signal);
28502            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
28503            if path == "/api/worker/workflow-tasks/poll"
28504                && signal_request >= 1
28505                && signal_request <= signal_request_limit
28506            {
28507                let finish = behavior.complete_named_signal && signal_request == 3;
28508                let amounts = if signal_request == 1 {
28509                    vec![3]
28510                } else {
28511                    vec![3, 5]
28512                };
28513                let task_id = if signal_request == 1 {
28514                    "snapshot-wait-3"
28515                } else if finish {
28516                    "snapshot-finish"
28517                } else {
28518                    "snapshot-wait-5"
28519                };
28520                let mut history_events = std::iter::once(json!({
28521                    "event_type": "SignalWaitOpened",
28522                    "payload": {"sequence": 1, "signal_name": "finish"}
28523                }))
28524                .chain(amounts.iter().enumerate().map(|(index, amount)| {
28525                    json!({
28526                        "event_type": "SignalReceived",
28527                        "payload": {
28528                            "signal_id": format!("increment-{amount}"),
28529                            "signal_name": "increment",
28530                            "workflow_sequence": index + 2,
28531                            "payload_codec": DEFAULT_CODEC,
28532                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28533                                .expect("Avro signal envelope")
28534                        }
28535                    })
28536                }))
28537                .collect::<Vec<_>>();
28538                let (resume_id, resume_name, resume_arguments) = if finish {
28539                    history_events.push(json!({
28540                        "event_type": "SignalReceived",
28541                        "payload": {
28542                            "signal_id": "finish",
28543                            "signal_name": "finish",
28544                            "workflow_sequence": 4,
28545                            "payload_codec": DEFAULT_CODEC,
28546                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28547                                .expect("Avro finish signal envelope")
28548                        }
28549                    }));
28550                    (
28551                        "finish".to_string(),
28552                        "finish".to_string(),
28553                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
28554                            .expect("Avro finish resume signal"),
28555                    )
28556                } else {
28557                    let amount = amounts.last().expect("amount");
28558                    (
28559                        format!("increment-{amount}"),
28560                        "increment".to_string(),
28561                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28562                            .expect("Avro increment resume signal"),
28563                    )
28564                };
28565                let body = json!({
28566                    "task": {
28567                        "task_id": task_id,
28568                        "workflow_id": "snapshot-1",
28569                        "run_id": "snapshot-run-1",
28570                        "workflow_type": "snapshot",
28571                        "payload_codec": DEFAULT_CODEC,
28572                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28573                            .expect("Avro workflow arguments"),
28574                        "history_events": history_events,
28575                        "workflow_task_attempt": 1,
28576                        "workflow_signal_id": resume_id,
28577                        "signal_name": resume_name,
28578                        "signal_arguments": resume_arguments,
28579                        "lease_owner": "rust-snapshot-worker"
28580                    }
28581                })
28582                .to_string();
28583                write_mock_response(stream, "200 OK", &body);
28584                return;
28585            }
28586
28587            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
28588                let history_events = [3, 5]
28589                    .into_iter()
28590                    .enumerate()
28591                    .map(|(index, amount)| {
28592                        json!({
28593                            "event_type": "SignalReceived",
28594                            "payload": {
28595                                "signal_id": format!("increment-{amount}"),
28596                                "signal_name": "increment",
28597                                "workflow_sequence": index + 2,
28598                                "payload_codec": DEFAULT_CODEC,
28599                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28600                                    .expect("Avro query signal envelope")
28601                            }
28602                        })
28603                    })
28604                    .collect::<Vec<_>>();
28605                let body = json!({
28606                    "task": {
28607                        "query_task_id": "snapshot-current",
28608                        "query_task_attempt": 1,
28609                        "lease_owner": "rust-snapshot-worker",
28610                        "workflow_id": "snapshot-1",
28611                        "run_id": "snapshot-run-1",
28612                        "workflow_type": "snapshot",
28613                        "query_name": "current",
28614                        "payload_codec": DEFAULT_CODEC,
28615                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28616                            .expect("Avro workflow arguments"),
28617                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28618                            .expect("Avro query arguments"),
28619                        "history_events": history_events,
28620                        "run_status": "waiting"
28621                    }
28622                })
28623                .to_string();
28624                write_mock_response(stream, "200 OK", &body);
28625                return;
28626            }
28627
28628            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
28629                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
28630            {
28631                write_mock_response(
28632                    stream,
28633                    "200 OK",
28634                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
28635                );
28636                return;
28637            }
28638
28639            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
28640                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
28641                return;
28642            }
28643
28644            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
28645                write_mock_response(
28646                    stream,
28647                    "200 OK",
28648                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
28649                );
28650                return;
28651            }
28652
28653            if path == "/api/worker/query-tasks/snapshot-current/complete" {
28654                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
28655                return;
28656            }
28657        }
28658
28659        if matches!(
28660            path,
28661            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
28662        ) {
28663            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
28664                .expect("typed mock result");
28665            let body = json!({
28666                "result": typed_fidelity_probe().into_json().expect("result projection"),
28667                "result_envelope": result,
28668            })
28669            .to_string();
28670            write_mock_response(stream, "200 OK", &body);
28671            return;
28672        }
28673
28674        if path == "/api/workflows/typed-1" {
28675            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
28676                .expect("typed mock result");
28677            let body = json!({
28678                "workflow_id": "typed-1",
28679                "run_id": "run-typed-1",
28680                "workflow_type": "typed.echo",
28681                "status": "completed",
28682                "output": typed_fidelity_probe().into_json().expect("output projection"),
28683                "output_envelope": result,
28684            })
28685            .to_string();
28686            write_mock_response(stream, "200 OK", &body);
28687            return;
28688        }
28689
28690        let (status, body) = match path {
28691            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
28692            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
28693            "/api/workflows" => (
28694                "201 Created",
28695                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
28696            ),
28697            "/api/worker/register" if behavior.decline_registration => (
28698                "200 OK",
28699                r#"{"worker_id":"declined-worker","registered":false}"#,
28700            ),
28701            "/api/worker/register" if behavior.waiting_query_worker => (
28702                "200 OK",
28703                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
28704            ),
28705            "/api/worker/register" => (
28706                "200 OK",
28707                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
28708            ),
28709            "/api/worker/heartbeat" => ("200 OK", "{}"),
28710            "/api/worker/activity-tasks/poll"
28711                if behavior.cancelled_activity && request_number == 1 =>
28712            {
28713                (
28714                    "200 OK",
28715                    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"}}"#,
28716                )
28717            }
28718            "/api/worker/activity-tasks/poll"
28719                if behavior.long_poll_capacity_responses_per_path > 0
28720                    && request_number
28721                        == behavior
28722                            .long_poll_capacity_responses_per_path
28723                            .saturating_add(1) =>
28724            {
28725                (
28726                    "200 OK",
28727                    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"}}"#,
28728                )
28729            }
28730            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
28731                ("200 OK", r#"{"task":null}"#)
28732            }
28733            "/api/worker/query-tasks/poll"
28734                if behavior.reject_query_completion && request_number == 1 =>
28735            {
28736                (
28737                    "200 OK",
28738                    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"}}"#,
28739                )
28740            }
28741            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
28742            "/api/worker/query-tasks/query-capture/complete"
28743            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
28744            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
28745                "200 OK",
28746                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
28747            ),
28748            "/api/worker/activity-tasks/activity-cancel/complete" => (
28749                "409 Conflict",
28750                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
28751            ),
28752            "/api/worker/activity-tasks/activity-typed/complete"
28753            | "/api/worker/activity-tasks/activity-typed/fail"
28754            | "/api/worker/activity-tasks/capacity-activity/complete"
28755            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
28756            "/api/workflows/counter-1/query/current" => (
28757                "200 OK",
28758                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
28759            ),
28760            "/api/workflows/counter-1/query/missing" => (
28761                "404 Not Found",
28762                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
28763            ),
28764            "/api/workflows/wf-lifecycle/cancel" => (
28765                "200 OK",
28766                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
28767            ),
28768            "/api/workflows/wf-lifecycle/terminate" => (
28769                "200 OK",
28770                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
28771            ),
28772            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
28773                "200 OK",
28774                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
28775            ),
28776            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
28777                "200 OK",
28778                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
28779            ),
28780            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
28781                "202 Accepted",
28782                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
28783            ),
28784            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
28785                "200 OK",
28786                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}"#,
28787            ),
28788            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
28789                "409 Conflict",
28790                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
28791            ),
28792            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
28793            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
28794                "409 Conflict",
28795                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
28796            ),
28797            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
28798                "200 OK",
28799                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"}]}}"#,
28800            ),
28801            "/api/workflows/wf-cancelled" => (
28802                "200 OK",
28803                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
28804            ),
28805            "/api/workflows/wf-terminated" => (
28806                "200 OK",
28807                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
28808            ),
28809            "/api/workflows/wf-timed-out" => (
28810                "200 OK",
28811                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
28812            ),
28813            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
28814                "200 OK",
28815                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
28816            ),
28817            "/api/workflows/wf-selected" => (
28818                "200 OK",
28819                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
28820            ),
28821            "/api/workflows/wf-selected/runs/run-selected" => (
28822                "200 OK",
28823                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
28824            ),
28825            _ => ("404 Not Found", r#"{"message":"not found"}"#),
28826        };
28827        write_mock_response(stream, status, body);
28828    }
28829
28830    fn mock_request_is_complete(request: &[u8]) -> bool {
28831        let Some(header_end) = request
28832            .windows(4)
28833            .position(|window| window == b"\r\n\r\n")
28834            .map(|position| position + 4)
28835        else {
28836            return false;
28837        };
28838        let headers = String::from_utf8_lossy(&request[..header_end]);
28839        let content_length = headers.lines().find_map(|line| {
28840            let (name, value) = line.split_once(':')?;
28841            name.eq_ignore_ascii_case("content-length")
28842                .then(|| value.trim().parse::<usize>().ok())
28843                .flatten()
28844        });
28845
28846        request.len() >= header_end + content_length.unwrap_or(0)
28847    }
28848
28849    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
28850        let response = format!(
28851            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
28852            body.len()
28853        );
28854
28855        let _ = stream.write_all(response.as_bytes());
28856        let _ = stream.flush();
28857    }
28858
28859    fn activity_completion_backend_recovery(
28860        path: &str,
28861        _body: &str,
28862        request_number: usize,
28863    ) -> Option<(&'static str, String)> {
28864        match path {
28865            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
28866                "200 OK",
28867                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(),
28868            )),
28869            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
28870                "503 Service Unavailable",
28871                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(),
28872            )),
28873            "/api/worker/activity-tasks/recover-activity/complete" => Some((
28874                "200 OK",
28875                r#"{"outcome":"completed","recorded":true}"#.to_string(),
28876            )),
28877            _ => None,
28878        }
28879    }
28880
28881    fn workflow_completion_backend_recovery(
28882        path: &str,
28883        _body: &str,
28884        request_number: usize,
28885    ) -> Option<(&'static str, String)> {
28886        match path {
28887            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
28888                "200 OK",
28889                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
28890            )),
28891            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
28892                "503 Service Unavailable",
28893                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(),
28894            )),
28895            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
28896                "200 OK",
28897                r#"{"outcome":"completed","recorded":true}"#.to_string(),
28898            )),
28899            _ => None,
28900        }
28901    }
28902
28903    fn activity_completion_stale_after_backend_recovery(
28904        path: &str,
28905        body: &str,
28906        request_number: usize,
28907    ) -> Option<(&'static str, String)> {
28908        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
28909            return Some((
28910                "409 Conflict",
28911                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(),
28912            ));
28913        }
28914        activity_completion_backend_recovery(path, body, request_number)
28915    }
28916
28917    fn activity_completion_remains_unavailable(
28918        path: &str,
28919        body: &str,
28920        request_number: usize,
28921    ) -> Option<(&'static str, String)> {
28922        if path == "/api/worker/activity-tasks/recover-activity/complete" {
28923            return activity_completion_backend_recovery(path, body, 1);
28924        }
28925        activity_completion_backend_recovery(path, body, request_number)
28926    }
28927
28928    #[tokio::test]
28929    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
28930        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28931            request_override: Some(activity_completion_backend_recovery),
28932            ..MockWorkerBehavior::default()
28933        });
28934        let client = Client::builder(server.base_url())
28935            .timeout(Duration::from_secs(2))
28936            .build()
28937            .expect("client");
28938        let handler_calls = Arc::new(AtomicUsize::new(0));
28939        let mut worker = Worker::new(client, "recover-queue")
28940            .worker_id("recover-worker")
28941            .poll_timeout(Duration::from_millis(10));
28942        worker.register_activity("recover.activity", {
28943            let handler_calls = Arc::clone(&handler_calls);
28944            move |_ctx, _args| {
28945                let handler_calls = Arc::clone(&handler_calls);
28946                async move {
28947                    handler_calls.fetch_add(1, Ordering::SeqCst);
28948                    Ok(json!("done"))
28949                }
28950            }
28951        });
28952
28953        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
28954        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
28955        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
28956        assert_eq!(bodies.len(), 2);
28957        assert_eq!(bodies[0], bodies[1]);
28958    }
28959
28960    #[tokio::test]
28961    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
28962        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28963            request_override: Some(workflow_completion_backend_recovery),
28964            ..MockWorkerBehavior::default()
28965        });
28966        let client = Client::builder(server.base_url())
28967            .timeout(Duration::from_secs(2))
28968            .build()
28969            .expect("client");
28970        let handler_calls = Arc::new(AtomicUsize::new(0));
28971        let mut worker = Worker::new(client, "recover-queue")
28972            .worker_id("recover-worker")
28973            .poll_timeout(Duration::from_millis(10));
28974        worker.register_workflow("recover.workflow", {
28975            let handler_calls = Arc::clone(&handler_calls);
28976            move |_ctx, _args| {
28977                let handler_calls = Arc::clone(&handler_calls);
28978                async move {
28979                    handler_calls.fetch_add(1, Ordering::SeqCst);
28980                    Ok(json!("done"))
28981                }
28982            }
28983        });
28984
28985        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
28986        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
28987        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
28988        assert_eq!(bodies.len(), 2);
28989        assert_eq!(bodies[0], bodies[1]);
28990    }
28991
28992    #[tokio::test]
28993    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
28994        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28995            request_override: Some(activity_completion_stale_after_backend_recovery),
28996            ..MockWorkerBehavior::default()
28997        });
28998        let client = Client::builder(server.base_url())
28999            .timeout(Duration::from_secs(2))
29000            .build()
29001            .expect("client");
29002        let handler_calls = Arc::new(AtomicUsize::new(0));
29003        let mut worker = Worker::new(client, "recover-queue")
29004            .worker_id("recover-worker")
29005            .poll_timeout(Duration::from_millis(10));
29006        worker.register_activity("recover.activity", {
29007            let handler_calls = Arc::clone(&handler_calls);
29008            move |_ctx, _args| {
29009                let handler_calls = Arc::clone(&handler_calls);
29010                async move {
29011                    handler_calls.fetch_add(1, Ordering::SeqCst);
29012                    Ok(json!("done"))
29013                }
29014            }
29015        });
29016
29017        assert_eq!(
29018            worker
29019                .run_once()
29020                .await
29021                .expect("authoritative stale outcome"),
29022            1
29023        );
29024        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
29025        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
29026        assert_eq!(bodies.len(), 2);
29027        assert_eq!(bodies[0], bodies[1]);
29028    }
29029
29030    #[test]
29031    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
29032        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
29033        let response = json!({
29034            "reason":"backend_unavailable", "operation":"complete_activity_task",
29035            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
29036            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
29037            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
29038        });
29039        let path = "/worker/activity-tasks/recover-activity/complete";
29040        let error = |body: Value| Error::Http {
29041            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29042            body: body.to_string(),
29043        };
29044        assert_eq!(
29045            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
29046            Some(Duration::from_secs(1))
29047        );
29048
29049        for (field, invalid) in [
29050            ("operation", json!("poll_activity_task")),
29051            ("outcome", json!("rejected")),
29052            ("worker_id", json!("another-worker")),
29053            ("task_queue", json!("recover-queue")),
29054            ("retryable", json!(false)),
29055            ("retry_after_seconds", json!(0)),
29056            ("task_id", json!("another-task")),
29057            ("lease_owner", json!("another-worker")),
29058            ("activity_attempt_id", json!("another-attempt")),
29059        ] {
29060            let mut invalid_response = response.clone();
29061            invalid_response[field] = invalid;
29062            assert_eq!(
29063                worker_fenced_completion_retry_after(
29064                    &error(invalid_response),
29065                    path,
29066                    Some(&request)
29067                ),
29068                None,
29069                "must not retry mismatched {field}"
29070            );
29071        }
29072        assert_eq!(
29073            worker_fenced_completion_retry_after(&error(response), path, None),
29074            None
29075        );
29076    }
29077
29078    #[tokio::test]
29079    async fn shutdown_interrupts_fenced_completion_backend_wait() {
29080        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29081            request_override: Some(activity_completion_remains_unavailable),
29082            ..MockWorkerBehavior::default()
29083        });
29084        let client = Client::builder(server.base_url())
29085            .timeout(Duration::from_secs(2))
29086            .build()
29087            .expect("client");
29088        let stop = Arc::new(AtomicBool::new(false));
29089        let worker = Worker::new(client, "recover-queue")
29090            .worker_id("recover-worker")
29091            .with_storage_admission(Arc::clone(&stop));
29092        let completion = tokio::spawn(async move {
29093            worker
29094                .client
29095                .complete_activity_task(
29096                    "recover-activity",
29097                    "recover-attempt",
29098                    "recover-worker",
29099                    json!("done"),
29100                    DEFAULT_CODEC,
29101                )
29102                .await
29103        });
29104        let path = "/api/worker/activity-tasks/recover-activity/complete";
29105        tokio::time::timeout(Duration::from_secs(2), async {
29106            while server.request_count(path) == 0 {
29107                tokio::time::sleep(Duration::from_millis(10)).await;
29108            }
29109        })
29110        .await
29111        .expect("first completion request");
29112        stop.store(true, Ordering::SeqCst);
29113        let error = tokio::time::timeout(Duration::from_secs(1), completion)
29114            .await
29115            .expect("shutdown must interrupt retry wait")
29116            .expect("completion task")
29117            .expect_err("backend is still unavailable");
29118        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
29119        assert_eq!(server.request_count(path), 1);
29120    }
29121}