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    signals: HashMap<String, Vec<String>>,
6426    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6427    max_concurrent_workflow_tasks: usize,
6428    max_concurrent_activity_tasks: usize,
6429    poll_timeout: Duration,
6430    heartbeat_interval: Duration,
6431    retry_policy: WorkerRetryPolicy,
6432    recover_transient_outages: bool,
6433    run_stop: Option<Arc<AtomicBool>>,
6434    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6435    cooperative_cancellation_enabled: bool,
6436    allow_cancellation_scope_authoring: bool,
6437    allow_cancellation_scope_delivery: bool,
6438    cooperative_registration_confirmed: Arc<AtomicBool>,
6439    local_registration_confirmed: Arc<AtomicBool>,
6440    session_registration_confirmed: Arc<AtomicBool>,
6441    resource_capabilities: Vec<String>,
6442    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6443}
6444
6445impl Worker {
6446    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6447        Self {
6448            client,
6449            worker_id: default_worker_id(),
6450            task_queue: task_queue.into(),
6451            workflows: HashMap::new(),
6452            activities: HashMap::new(),
6453            queries: HashMap::new(),
6454            signals: HashMap::new(),
6455            updates: HashMap::new(),
6456            max_concurrent_workflow_tasks: 10,
6457            max_concurrent_activity_tasks: 10,
6458            poll_timeout: Duration::from_secs(30),
6459            heartbeat_interval: Duration::from_secs(60),
6460            retry_policy: WorkerRetryPolicy::default(),
6461            recover_transient_outages: false,
6462            run_stop: None,
6463            heartbeat_observer: None,
6464            cooperative_cancellation_enabled: false,
6465            allow_cancellation_scope_authoring: false,
6466            allow_cancellation_scope_delivery: false,
6467            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6468            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6469            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6470            resource_capabilities: Vec::new(),
6471            sessions: Arc::new(Mutex::new(HashMap::new())),
6472        }
6473    }
6474
6475    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6476        self.worker_id = worker_id.into();
6477        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6478        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6479        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6480        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6481        self
6482    }
6483
6484    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6485        self.poll_timeout = timeout;
6486        self
6487    }
6488
6489    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6490        self.heartbeat_interval = interval;
6491        self
6492    }
6493
6494    /// Explicitly enable inline local activities in this workflow worker.
6495    ///
6496    /// The worker advertises the capability to Server only when enabled.
6497    /// These callbacks must yield to Tokio and have idempotent side effects.
6498    /// Cooperative prepared local supervision is a separate capability.
6499    pub fn local_activities(mut self, enabled: bool) -> Self {
6500        self.client.local_activities_enabled = enabled;
6501        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6502        self
6503    }
6504
6505    /// Opt in to separate cooperative workflow cancellation requests.
6506    ///
6507    /// Registration requires the Server to acknowledge this exact worker,
6508    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6509    /// processing uses canonical delivery and activity ownership fences.
6510    /// Existing terminal cancel and terminate operations remain terminal.
6511    /// The default is disabled, preserving ordinary protocol 1.19 workers.
6512    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6513    /// and [`Worker::run_until`] register automatically.
6514    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6515        self.cooperative_cancellation_enabled = enabled;
6516        self.client.cooperative_worker_protocol = enabled;
6517        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6518        self
6519    }
6520
6521    /// Enable candidate scope authoring without advertising scoped execution.
6522    #[doc(hidden)]
6523    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6524        self.allow_cancellation_scope_authoring = enabled;
6525        self
6526    }
6527
6528    /// Enable the candidate scoped call consumer with canonical authoring.
6529    #[doc(hidden)]
6530    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6531        self.allow_cancellation_scope_delivery = enabled;
6532        self
6533    }
6534
6535    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6536    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6537        self.retry_policy = policy;
6538        self
6539    }
6540
6541    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6542    ///
6543    /// Retries preserve the poll request identity and use capped exponential
6544    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6545    /// An in-flight poll is allowed to finish so leased work is not discarded.
6546    /// Authentication, protocol, codec, handler and task settlement failures
6547    /// remain errors. Registration and deregistration are not retried here.
6548    ///
6549    /// The default is disabled, preserving the bounded retry contract.
6550    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6551    /// even when this option is enabled.
6552    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6553        self.recover_transient_outages = enabled;
6554        self
6555    }
6556
6557    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6558    where
6559        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6560    {
6561        self.heartbeat_observer = Some(Arc::new(observer));
6562        self
6563    }
6564
6565    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6566        self.max_concurrent_workflow_tasks = count.max(1);
6567        self
6568    }
6569
6570    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6571        self.max_concurrent_activity_tasks = count.max(1);
6572        self
6573    }
6574
6575    /// Register a workflow handler.
6576    ///
6577    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6578    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6579    /// while acquiring or decoding a worker task remain worker-operation
6580    /// failures and do not get converted into workflow outcomes.
6581    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6582    where
6583        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6584        Fut: Future<Output = Result<Value>> + Send + 'static,
6585    {
6586        let handler = Arc::new(handler);
6587        self.workflows.insert(
6588            workflow_type.into(),
6589            RegisteredWorkflow {
6590                execute: Arc::new(move |ctx, input| {
6591                    let handler = Arc::clone(&handler);
6592                    Box::pin(async move {
6593                        let result = handler(ctx, input.into_json()?).await?;
6594                        AvroValue::from_serialize(&result)
6595                    })
6596                }),
6597                replay: None,
6598                state_type: None,
6599                definition_fingerprint: None,
6600            },
6601        );
6602    }
6603
6604    /// Register a workflow with one Serde request value and a Serde result.
6605    ///
6606    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
6607    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
6608    /// workflow-specific schema. A task must contain zero arguments for a unit
6609    /// request or exactly one argument for every other request type.
6610    ///
6611    /// See the runnable
6612    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
6613    /// for typed workflow and activity contracts with retry and timeout policy.
6614    pub fn register_typed_workflow<I, O, F, Fut>(
6615        &mut self,
6616        workflow_type: impl Into<String>,
6617        handler: F,
6618    ) where
6619        I: DeserializeOwned + Send + 'static,
6620        O: Serialize + Send + 'static,
6621        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
6622        Fut: Future<Output = Result<O>> + Send + 'static,
6623    {
6624        let workflow_type = workflow_type.into();
6625        let handler_name = workflow_type.clone();
6626        let handler = Arc::new(handler);
6627        self.workflows.insert(
6628            workflow_type,
6629            RegisteredWorkflow {
6630                execute: Arc::new(move |ctx, input| {
6631                    let handler = Arc::clone(&handler);
6632                    let handler_name = handler_name.clone();
6633                    Box::pin(async move {
6634                        let input =
6635                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6636                        let result = handler(ctx, input).await?;
6637                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6638                    })
6639                }),
6640                replay: None,
6641                state_type: None,
6642                definition_fingerprint: None,
6643            },
6644        );
6645    }
6646
6647    /// Register a workflow on the lossless fixed Avro Value surface.
6648    pub fn register_workflow_avro_value<F, Fut>(
6649        &mut self,
6650        workflow_type: impl Into<String>,
6651        handler: F,
6652    ) where
6653        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
6654        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6655    {
6656        self.workflows.insert(
6657            workflow_type.into(),
6658            RegisteredWorkflow {
6659                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
6660                replay: None,
6661                state_type: None,
6662                definition_fingerprint: None,
6663            },
6664        );
6665    }
6666
6667    /// Register a workflow whose typed instance state can be reconstructed for queries.
6668    ///
6669    /// `state_factory` creates a fresh instance for every normal workflow task and
6670    /// query replay. The workflow handler is the single source of truth for state
6671    /// transitions: it updates [`WorkflowInstance`] after activities and signals
6672    /// resolve. Query replay runs this same handler over committed history and
6673    /// discards any commands it would emit.
6674    pub fn register_replayed_workflow<S, Factory, F, Fut>(
6675        &mut self,
6676        workflow_type: impl Into<String>,
6677        state_factory: Factory,
6678        handler: F,
6679    ) where
6680        S: Clone + Send + Sync + 'static,
6681        Factory: Fn() -> S + Send + Sync + 'static,
6682        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6683        Fut: Future<Output = Result<Value>> + Send + 'static,
6684    {
6685        let state_factory = Arc::new(state_factory);
6686        let handler = Arc::new(handler);
6687
6688        let execute_factory = Arc::clone(&state_factory);
6689        let execute_handler = Arc::clone(&handler);
6690        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6691            let state = WorkflowInstance::new(execute_factory());
6692            let handler = Arc::clone(&execute_handler);
6693            Box::pin(async move {
6694                let result = handler(ctx, input.into_json()?, state).await?;
6695                AvroValue::from_serialize(&result)
6696            }) as WorkflowFuture
6697        });
6698
6699        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6700            let state = WorkflowInstance::new(state_factory());
6701            let snapshot_state = state.clone();
6702            let snapshot: WorkflowStateSnapshot =
6703                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6704            let replay_handler = Arc::clone(&handler);
6705            let future = async move {
6706                let result = replay_handler(ctx, input.into_json()?, state).await?;
6707                AvroValue::from_serialize(&result)
6708            };
6709            ReplayedWorkflowInvocation {
6710                future: Box::pin(future),
6711                snapshot,
6712            }
6713        });
6714
6715        self.workflows.insert(
6716            workflow_type.into(),
6717            RegisteredWorkflow {
6718                execute,
6719                replay: Some(replay),
6720                state_type: Some(TypeId::of::<S>()),
6721                definition_fingerprint: None,
6722            },
6723        );
6724    }
6725
6726    /// Register a replayable workflow with one Serde request value and result.
6727    ///
6728    /// Normal task execution and instance-state query replay both decode and
6729    /// encode through the fixed Avro Value codec. The state factory and handler
6730    /// otherwise follow [`Worker::register_replayed_workflow`].
6731    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
6732        &mut self,
6733        workflow_type: impl Into<String>,
6734        state_factory: Factory,
6735        handler: F,
6736    ) where
6737        I: DeserializeOwned + Send + 'static,
6738        O: Serialize + Send + 'static,
6739        S: Clone + Send + Sync + 'static,
6740        Factory: Fn() -> S + Send + Sync + 'static,
6741        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6742        Fut: Future<Output = Result<O>> + Send + 'static,
6743    {
6744        let workflow_type = workflow_type.into();
6745        let state_factory = Arc::new(state_factory);
6746        let handler = Arc::new(handler);
6747
6748        let execute_name = workflow_type.clone();
6749        let execute_factory = Arc::clone(&state_factory);
6750        let execute_handler = Arc::clone(&handler);
6751        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6752            let state = WorkflowInstance::new(execute_factory());
6753            let handler = Arc::clone(&execute_handler);
6754            let handler_name = execute_name.clone();
6755            Box::pin(async move {
6756                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6757                let result = handler(ctx, input, state).await?;
6758                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6759            }) as WorkflowFuture
6760        });
6761
6762        let replay_name = workflow_type.clone();
6763        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6764            let state = WorkflowInstance::new(state_factory());
6765            let snapshot_state = state.clone();
6766            let snapshot: WorkflowStateSnapshot =
6767                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6768            let handler = Arc::clone(&handler);
6769            let handler_name = replay_name.clone();
6770            let future = async move {
6771                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6772                let result = handler(ctx, input, state).await?;
6773                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6774            };
6775            ReplayedWorkflowInvocation {
6776                future: Box::pin(future),
6777                snapshot,
6778            }
6779        });
6780
6781        self.workflows.insert(
6782            workflow_type,
6783            RegisteredWorkflow {
6784                execute,
6785                replay: Some(replay),
6786                state_type: Some(TypeId::of::<S>()),
6787                definition_fingerprint: None,
6788            },
6789        );
6790    }
6791
6792    /// Declare the signal names consumed by a registered workflow.
6793    ///
6794    /// Call this after registering the workflow and before starting the worker.
6795    /// Names read through `wait_signal` or `signals` need a declaration for
6796    /// Server command admission. Arguments remain arbitrary positional values,
6797    /// including lossless Avro values. This replaces the previous declaration;
6798    /// an empty slice declares no signals. Names are sorted and deduplicated.
6799    /// Existing runs retain the declarations captured when they started.
6800    pub fn declare_workflow_signals(
6801        &mut self,
6802        workflow_type: &str,
6803        signal_names: &[&str],
6804    ) -> Result<()> {
6805        if !self.workflows.contains_key(workflow_type) {
6806            return Err(Error::Codec(format!(
6807                "workflow type {workflow_type:?} is not registered"
6808            )));
6809        }
6810        if signal_names
6811            .iter()
6812            .any(|name| name.is_empty() || *name != name.trim())
6813        {
6814            return Err(Error::Codec(
6815                "signal names must be non-empty and have no surrounding whitespace".into(),
6816            ));
6817        }
6818        let mut names = signal_names
6819            .iter()
6820            .map(|name| (*name).to_string())
6821            .collect::<Vec<_>>();
6822        names.sort();
6823        names.dedup();
6824        self.signals.insert(workflow_type.to_string(), names);
6825        Ok(())
6826    }
6827
6828    /// Bind a registered workflow to compile-time embedded source for safe redrive.
6829    ///
6830    /// Supply `include_str!` values for the workflow body and every helper whose
6831    /// behavior can affect replay. A handler re-registration clears the local
6832    /// identity; call this after registering the final handler. The server
6833    /// rejects reusing a worker ID when its prior fingerprint disappears.
6834    /// Workflows without source identity remain runnable but cannot be safely redriven.
6835    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
6836    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
6837    pub fn set_workflow_definition_sources(
6838        &mut self,
6839        workflow_type: &str,
6840        sources: &[&str],
6841    ) -> Result<()> {
6842        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
6843            return Err(Error::Codec(
6844                "workflow definition sources must be non-empty".to_string(),
6845            ));
6846        }
6847        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
6848            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
6849        })?;
6850        let mut hasher = Sha256::new();
6851        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
6852        hasher.update((workflow_type.len() as u64).to_be_bytes());
6853        hasher.update(workflow_type.as_bytes());
6854        for source in sources {
6855            hasher.update((source.len() as u64).to_be_bytes());
6856            hasher.update(source.as_bytes());
6857        }
6858        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
6859        Ok(())
6860    }
6861
6862    /// Register a replayable workflow on the lossless fixed Avro Value surface.
6863    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
6864        &mut self,
6865        workflow_type: impl Into<String>,
6866        state_factory: Factory,
6867        handler: F,
6868    ) where
6869        S: Clone + Send + Sync + 'static,
6870        Factory: Fn() -> S + Send + Sync + 'static,
6871        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6872        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6873    {
6874        let state_factory = Arc::new(state_factory);
6875        let handler = Arc::new(handler);
6876
6877        let execute_factory = Arc::clone(&state_factory);
6878        let execute_handler = Arc::clone(&handler);
6879        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6880            let state = WorkflowInstance::new(execute_factory());
6881            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
6882        });
6883
6884        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6885            let state = WorkflowInstance::new(state_factory());
6886            let snapshot_state = state.clone();
6887            let snapshot: WorkflowStateSnapshot =
6888                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6889            ReplayedWorkflowInvocation {
6890                future: Box::pin(handler(ctx, input, state)),
6891                snapshot,
6892            }
6893        });
6894
6895        self.workflows.insert(
6896            workflow_type.into(),
6897            RegisteredWorkflow {
6898                execute,
6899                replay: Some(replay),
6900                state_type: Some(TypeId::of::<S>()),
6901                definition_fingerprint: None,
6902            },
6903        );
6904    }
6905
6906    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
6907    where
6908        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
6909        Fut: Future<Output = Result<Value>> + Send + 'static,
6910    {
6911        let handler = Arc::new(handler);
6912        self.activities.insert(
6913            activity_type.into(),
6914            Arc::new(move |ctx, args| {
6915                let handler = Arc::clone(&handler);
6916                Box::pin(async move {
6917                    let result = handler(ctx, args.into_json()?).await?;
6918                    AvroValue::from_serialize(&result)
6919                })
6920            }),
6921        );
6922    }
6923
6924    /// Register an activity with one Serde request value and a Serde result.
6925    ///
6926    /// Inputs and results use the platform's fixed Avro Value schema. Shape
6927    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
6928    /// with the activity name and Rust type.
6929    pub fn register_typed_activity<I, O, F, Fut>(
6930        &mut self,
6931        activity_type: impl Into<String>,
6932        handler: F,
6933    ) where
6934        I: DeserializeOwned + Send + 'static,
6935        O: Serialize + Send + 'static,
6936        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
6937        Fut: Future<Output = Result<O>> + Send + 'static,
6938    {
6939        let activity_type = activity_type.into();
6940        let handler_name = activity_type.clone();
6941        let handler = Arc::new(handler);
6942        self.activities.insert(
6943            activity_type,
6944            Arc::new(move |ctx, input| {
6945                let handler = Arc::clone(&handler);
6946                let handler_name = handler_name.clone();
6947                Box::pin(async move {
6948                    let input =
6949                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
6950                    let result = handler(ctx, input).await?;
6951                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
6952                })
6953            }),
6954        );
6955    }
6956
6957    /// Register an activity on the lossless fixed Avro Value surface.
6958    pub fn register_activity_avro_value<F, Fut>(
6959        &mut self,
6960        activity_type: impl Into<String>,
6961        handler: F,
6962    ) where
6963        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
6964        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6965    {
6966        self.activities.insert(
6967            activity_type.into(),
6968            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
6969        );
6970    }
6971
6972    /// Register a named, read-only query handler for a workflow type.
6973    ///
6974    /// The workflow type must also be registered with [`Worker::register_workflow`]
6975    /// before the worker runs. The handler receives only an immutable committed
6976    /// state snapshot and normalized query arguments.
6977    pub fn register_query<F, Fut>(
6978        &mut self,
6979        workflow_type: impl Into<String>,
6980        query_name: impl Into<String>,
6981        handler: F,
6982    ) where
6983        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
6984        Fut: Future<Output = Result<Value>> + Send + 'static,
6985    {
6986        let handler = Arc::new(handler);
6987        self.queries
6988            .entry(workflow_type.into())
6989            .or_default()
6990            .insert(
6991                query_name.into(),
6992                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
6993                    let handler = Arc::clone(&handler);
6994                    Box::pin(async move {
6995                        let result = handler(ctx, args.into_json()?).await?;
6996                        AvroValue::from_serialize(&result)
6997                    })
6998                })),
6999            );
7000    }
7001
7002    /// Register a query handler on the lossless fixed Avro Value surface.
7003    pub fn register_query_avro_value<F, Fut>(
7004        &mut self,
7005        workflow_type: impl Into<String>,
7006        query_name: impl Into<String>,
7007        handler: F,
7008    ) where
7009        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7010        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7011    {
7012        self.queries
7013            .entry(workflow_type.into())
7014            .or_default()
7015            .insert(
7016                query_name.into(),
7017                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7018            );
7019    }
7020
7021    /// Register a named query against deterministically replayed instance state.
7022    ///
7023    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7024    /// same state type `S`. The handler receives an immutable, detached state
7025    /// clone, so successful and failed queries cannot affect workflow execution
7026    /// or the state reconstructed by a later query.
7027    pub fn register_replayed_query<S, F, Fut>(
7028        &mut self,
7029        workflow_type: impl Into<String>,
7030        query_name: impl Into<String>,
7031        handler: F,
7032    ) where
7033        S: Clone + Send + Sync + 'static,
7034        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7035        Fut: Future<Output = Result<Value>> + Send + 'static,
7036    {
7037        let handler = Arc::new(handler);
7038        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7039            let state = state.downcast::<S>().map_err(|_| {
7040                "registered query state type does not match the replayed workflow state".to_string()
7041            })?;
7042            let handler = Arc::clone(&handler);
7043            Ok(Box::pin(async move {
7044                let result = handler(ctx, state, args.into_json()?).await?;
7045                AvroValue::from_serialize(&result)
7046            }))
7047        });
7048
7049        self.queries
7050            .entry(workflow_type.into())
7051            .or_default()
7052            .insert(
7053                query_name.into(),
7054                RegisteredQuery::Replayed {
7055                    state_type: TypeId::of::<S>(),
7056                    handler: erased_handler,
7057                },
7058            );
7059    }
7060
7061    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7062    pub fn register_replayed_query_avro_value<S, F, Fut>(
7063        &mut self,
7064        workflow_type: impl Into<String>,
7065        query_name: impl Into<String>,
7066        handler: F,
7067    ) where
7068        S: Clone + Send + Sync + 'static,
7069        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7070        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7071    {
7072        let handler = Arc::new(handler);
7073        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7074            let state = state.downcast::<S>().map_err(|_| {
7075                "registered query state type does not match the replayed workflow state".to_string()
7076            })?;
7077            Ok(Box::pin(handler(ctx, state, args)))
7078        });
7079
7080        self.queries
7081            .entry(workflow_type.into())
7082            .or_default()
7083            .insert(
7084                query_name.into(),
7085                RegisteredQuery::Replayed {
7086                    state_type: TypeId::of::<S>(),
7087                    handler: erased_handler,
7088                },
7089            );
7090    }
7091
7092    /// Register a synchronous workflow update handler.
7093    pub fn register_update<F, Fut>(
7094        &mut self,
7095        workflow_type: impl Into<String>,
7096        update_name: impl Into<String>,
7097        handler: F,
7098    ) where
7099        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7100        Fut: Future<Output = Result<Value>> + Send + 'static,
7101    {
7102        let handler = Arc::new(handler);
7103        self.updates
7104            .entry(workflow_type.into())
7105            .or_default()
7106            .insert(
7107                update_name.into(),
7108                Arc::new(move |ctx, args| {
7109                    let handler = Arc::clone(&handler);
7110                    Box::pin(async move {
7111                        let result = handler(ctx, args.into_json()?).await?;
7112                        AvroValue::from_serialize(&result)
7113                    })
7114                }),
7115            );
7116    }
7117
7118    /// Register an update handler on the lossless fixed Avro Value surface.
7119    pub fn register_update_avro_value<F, Fut>(
7120        &mut self,
7121        workflow_type: impl Into<String>,
7122        update_name: impl Into<String>,
7123        handler: F,
7124    ) where
7125        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7126        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7127    {
7128        self.updates
7129            .entry(workflow_type.into())
7130            .or_default()
7131            .insert(
7132                update_name.into(),
7133                Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7134            );
7135    }
7136
7137    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7138        self.session_registration_confirmed
7139            .store(false, Ordering::SeqCst);
7140        for capability in &self.resource_capabilities {
7141            worker_session::validate_resource_capability(capability)?;
7142        }
7143        self.local_registration_confirmed
7144            .store(false, Ordering::SeqCst);
7145        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7146            return Err(Error::CooperativeCancellationUnavailable(
7147                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7148            ));
7149        }
7150        let mut command_contracts = serde_json::Map::new();
7151        for workflow_type in self.workflows.keys() {
7152            let mut queries = self
7153                .queries
7154                .get(workflow_type)
7155                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7156                .unwrap_or_default();
7157            queries.sort();
7158            let mut updates = self
7159                .updates
7160                .get(workflow_type)
7161                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7162                .unwrap_or_default();
7163            updates.sort();
7164            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7165            command_contracts.insert(
7166                workflow_type.clone(),
7167                json!({
7168                    "queries": queries,
7169                    "query_contracts": argument_vector_contracts(&queries),
7170                    "signals": signals,
7171                    "signal_contracts": argument_vector_contracts(&signals),
7172                    "updates": updates,
7173                    "update_contracts": argument_vector_contracts(&updates),
7174                    "update_validators": [],
7175                }),
7176            );
7177        }
7178
7179        self.cooperative_registration_confirmed
7180            .store(false, Ordering::SeqCst);
7181        let response = self
7182            .client
7183            .register_worker_with_definition_fingerprints(
7184                &self.worker_id,
7185                &self.task_queue,
7186                self.workflows.keys().cloned().collect(),
7187                self.activities.keys().cloned().collect(),
7188                self.max_concurrent_workflow_tasks,
7189                self.max_concurrent_activity_tasks,
7190                [
7191                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7192                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7193                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7194                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7195                    self.client
7196                        .local_activities_enabled
7197                        .then(|| "local_activities".to_string()),
7198                    self.client
7199                        .worker_sessions_enabled
7200                        .then(|| "worker_sessions".to_string()),
7201                    self.cooperative_cancellation_enabled
7202                        .then(|| "cooperative_cancellation".to_string()),
7203                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7204                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7205                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7206                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7207                ]
7208                .into_iter()
7209                .flatten()
7210                .chain(self.resource_capabilities.iter().cloned())
7211                .collect(),
7212                Value::Object(command_contracts),
7213                Some(
7214                    self.workflows
7215                        .iter()
7216                        .filter_map(|(workflow_type, workflow)| {
7217                            workflow
7218                                .definition_fingerprint
7219                                .as_ref()
7220                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7221                        })
7222                        .collect(),
7223                ),
7224            )
7225            .await?;
7226        if self.cooperative_cancellation_enabled && response.registered {
7227            self.cooperative_registration_confirmed
7228                .store(true, Ordering::SeqCst);
7229        }
7230        if self.client.local_activities_enabled && response.registered {
7231            self.local_registration_confirmed
7232                .store(true, Ordering::SeqCst);
7233        }
7234        if self.client.worker_sessions_enabled && response.registered {
7235            self.session_registration_confirmed
7236                .store(true, Ordering::SeqCst);
7237        }
7238        Ok(response)
7239    }
7240
7241    /// Run until shutdown or a terminal worker error occurs.
7242    ///
7243    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7244    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7245    /// authentication, protocol, and other non-retryable failures are returned.
7246    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7247    /// poll and heartbeat outages beyond the ordinary retry budget.
7248    pub async fn run(&self) -> Result<()> {
7249        self.run_until(std::future::pending::<()>()).await
7250    }
7251
7252    /// Run until `shutdown` resolves or a terminal worker error occurs.
7253    ///
7254    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7255    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7256    where
7257        F: Future<Output = ()>,
7258    {
7259        let stop = Arc::new(AtomicBool::new(false));
7260        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7261        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7262        worker.run_stop = Some(Arc::clone(&stop));
7263        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7264        tokio::pin!(run);
7265        tokio::pin!(shutdown);
7266        tokio::select! {
7267            result = &mut run => result,
7268            _ = &mut shutdown => {
7269                stop.store(true, Ordering::SeqCst);
7270                run.await
7271            }
7272        }
7273    }
7274
7275    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7276        let mut worker = self.clone();
7277        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7278            policy: self.retry_policy,
7279            stop,
7280        });
7281        worker
7282    }
7283
7284    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7285        let registration = self.register().await?;
7286        if !registration.registered {
7287            return Err(Error::WorkerLoop(format!(
7288                "worker registration for {:?} was not accepted",
7289                self.worker_id
7290            )));
7291        }
7292        let registered_worker_id = registration.worker_id.clone();
7293        let primary = self.run_registered_until(stop, registration).await;
7294        let primary = match (primary, self.close_worker_sessions().await) {
7295            (Ok(()), result) => result,
7296            (Err(error), Ok(())) => Err(error),
7297            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7298                primary: Box::new(primary),
7299                deregistration: Box::new(close),
7300            }),
7301        };
7302        self.session_registration_confirmed
7303            .store(false, Ordering::SeqCst);
7304        self.cooperative_registration_confirmed
7305            .store(false, Ordering::SeqCst);
7306        self.local_registration_confirmed
7307            .store(false, Ordering::SeqCst);
7308        let deregistration = self
7309            .client
7310            .deregister_worker_registration(&registered_worker_id)
7311            .await;
7312
7313        match (primary, deregistration) {
7314            (Ok(()), Ok(_)) => Ok(()),
7315            (Ok(()), Err(deregistration)) => Err(deregistration),
7316            (Err(primary), Ok(_)) => Err(primary),
7317            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7318                primary: Box::new(primary),
7319                deregistration: Box::new(deregistration),
7320            }),
7321        }
7322    }
7323
7324    async fn run_registered_until(
7325        &self,
7326        stop: Arc<AtomicBool>,
7327        registration: RegisterWorkerResponse,
7328    ) -> Result<()> {
7329        let heartbeat_interval = Duration::from_secs(
7330            registration
7331                .heartbeat_interval_seconds
7332                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7333        );
7334        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7335        // from the completion of the preceding attempt, including its bounded
7336        // retries. A fixed-epoch interval can leave an already-due tick queued
7337        // while an acknowledgement is slow, producing a catch-up heartbeat as
7338        // soon as that request completes.
7339        let heartbeat = tokio::time::sleep(Duration::ZERO);
7340        tokio::pin!(heartbeat);
7341        // Poll responses may already have leased server-side work by the time
7342        // they become ready, so each poller owns its responses through
7343        // completion or failure instead of racing raw polls in this select.
7344        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7345            let worker = self.clone();
7346            let stop = Arc::clone(&stop);
7347            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7348        });
7349        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7350            let worker = self.clone();
7351            let stop = Arc::clone(&stop);
7352            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7353        });
7354        let mut query_poller = (!self.queries.is_empty()).then(|| {
7355            let worker = self.clone();
7356            let stop = Arc::clone(&stop);
7357            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7358        });
7359
7360        loop {
7361            tokio::select! {
7362                _ = wait_for_worker_stop(&stop) => {
7363                    stop.store(true, Ordering::SeqCst);
7364                    break;
7365                }
7366                _ = &mut heartbeat => {
7367                    let result = self.retry_worker_operation(|| {
7368                        self.client.heartbeat_worker_with_sessions(
7369                            &self.worker_id,
7370                            self.max_concurrent_workflow_tasks,
7371                            self.max_concurrent_activity_tasks,
7372                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7373                        )
7374                    }).await;
7375                    heartbeat
7376                        .as_mut()
7377                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7378                    match result {
7379                        Ok(Some(acknowledgement)) => {
7380                            if let Some(observer) = &self.heartbeat_observer {
7381                                observer(&WorkerHeartbeatObservation {
7382                                    worker_id: self.worker_id.clone(),
7383                                    task_queue: self.task_queue.clone(),
7384                                    acknowledged_at_unix_millis: SystemTime::now()
7385                                        .duration_since(UNIX_EPOCH)
7386                                        .unwrap_or_default()
7387                                        .as_millis()
7388                                        .min(u64::MAX as u128)
7389                                        as u64,
7390                                    acknowledgement,
7391                                });
7392                            }
7393                        }
7394                        Ok(None) => break,
7395                        Err(error) => {
7396                            stop.store(true, Ordering::SeqCst);
7397                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7398                            return Err(error);
7399                        }
7400                    }
7401                }
7402                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7403                    workflow_poller = None;
7404                    let stopped_by_server = stop.load(Ordering::SeqCst);
7405                    stop.store(true, Ordering::SeqCst);
7406                    let poller_result = optional_poller_result("workflow", result);
7407                    let join_result =
7408                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7409                    poller_result?;
7410                    join_result?;
7411                    if stopped_by_server {
7412                        return Ok(());
7413                    }
7414                    return Err(Error::WorkerLoop(
7415                        "workflow poller stopped unexpectedly".to_string(),
7416                    ));
7417                }
7418                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7419                    activity_poller = None;
7420                    let stopped_by_server = stop.load(Ordering::SeqCst);
7421                    stop.store(true, Ordering::SeqCst);
7422                    let poller_result = optional_poller_result("activity", result);
7423                    let join_result =
7424                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7425                    poller_result?;
7426                    join_result?;
7427                    if stopped_by_server {
7428                        return Ok(());
7429                    }
7430                    return Err(Error::WorkerLoop(
7431                        "activity poller stopped unexpectedly".to_string(),
7432                    ));
7433                }
7434                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7435                    query_poller = None;
7436                    let stopped_by_server = stop.load(Ordering::SeqCst);
7437                    stop.store(true, Ordering::SeqCst);
7438                    let poller_result = optional_poller_result("query", result);
7439                    let join_result =
7440                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7441                    poller_result?;
7442                    join_result?;
7443                    if stopped_by_server {
7444                        return Ok(());
7445                    }
7446                    return Err(Error::WorkerLoop(
7447                        "query poller stopped unexpectedly".to_string(),
7448                    ));
7449                }
7450            }
7451        }
7452
7453        join_pollers(
7454            workflow_poller.take(),
7455            activity_poller.take(),
7456            query_poller.take(),
7457        )
7458        .await
7459    }
7460
7461    /// Poll and settle at most one task from each enabled task family.
7462    ///
7463    /// A workflow may reach its server-enforced run deadline while this worker
7464    /// holds a task. When the completion endpoint authoritatively rejects that
7465    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
7466    /// terminal `run_status=failed`, the workflow tick is considered settled:
7467    /// the late command was not recorded and cannot replace the terminal run.
7468    /// Every other completion rejection remains an error. This worker-level
7469    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
7470    /// only bounds how long a client waits for a result.
7471    ///
7472    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
7473    /// the original [`Error::Http`] status and response body.
7474    pub async fn run_once(&self) -> Result<usize> {
7475        if self.client.worker_sessions_enabled {
7476            self.require_session_registration()?;
7477        }
7478        if self.cooperative_cancellation_enabled
7479            && !self
7480                .cooperative_registration_confirmed
7481                .load(Ordering::SeqCst)
7482        {
7483            return Err(Error::CooperativeCancellationUnavailable(
7484                "register this cooperative worker before polling tasks".into(),
7485            ));
7486        }
7487        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
7488        let mut handled = 0;
7489        match worker.poll_workflow_once().await? {
7490            ManagedPollOutcome::Handled => handled += 1,
7491            ManagedPollOutcome::Stop => return Ok(handled),
7492            ManagedPollOutcome::Idle => {}
7493        }
7494        match worker.poll_activity_once().await? {
7495            ManagedPollOutcome::Handled => handled += 1,
7496            ManagedPollOutcome::Stop => return Ok(handled),
7497            ManagedPollOutcome::Idle => {}
7498        }
7499        if !self.queries.is_empty() {
7500            match worker.poll_query_once().await? {
7501                ManagedPollOutcome::Handled => handled += 1,
7502                ManagedPollOutcome::Stop => return Ok(handled),
7503                ManagedPollOutcome::Idle => {}
7504            }
7505        }
7506        Ok(handled)
7507    }
7508
7509    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
7510        if self.client.local_activities_enabled
7511            && !self.local_registration_confirmed.load(Ordering::SeqCst)
7512        {
7513            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
7514        }
7515        if self.cooperative_cancellation_enabled {
7516            return self.poll_cooperative_workflow_once().await;
7517        }
7518        let poll_request_id = unique_request_id("rust-workflow-poll");
7519        let response = self
7520            .retry_worker_operation(|| {
7521                self.client.poll_workflow_task_response_with_request_id(
7522                    &self.worker_id,
7523                    &self.task_queue,
7524                    self.poll_timeout,
7525                    &poll_request_id,
7526                    0,
7527                )
7528            })
7529            .await;
7530        let Some(response) = self.settle_worker_poll_response(response).await? else {
7531            return Ok(ManagedPollOutcome::Idle);
7532        };
7533        if response.outcome().should_stop() {
7534            return Ok(ManagedPollOutcome::Stop);
7535        }
7536        let memo_updates_supported =
7537            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
7538        let Some(task) = response.task else {
7539            return Ok(ManagedPollOutcome::Idle);
7540        };
7541
7542        let task_id = task.task_id.clone();
7543        let attempt = task.workflow_task_attempt;
7544        let run_id = task.run_id.clone();
7545        let lease_owner = task
7546            .lease_owner
7547            .clone()
7548            .unwrap_or_else(|| self.worker_id.clone());
7549
7550        let decision = match self.execute_workflow_with_local_activities(task).await {
7551            Ok(Some(decision)) => Ok(decision),
7552            Ok(None) => return Ok(ManagedPollOutcome::Handled),
7553            Err(error) => Err(error),
7554        };
7555        self.settle_workflow_task_decision(
7556            &task_id,
7557            &lease_owner,
7558            attempt,
7559            run_id.as_deref(),
7560            decision,
7561            memo_updates_supported,
7562        )
7563        .await
7564    }
7565
7566    async fn settle_workflow_task_decision(
7567        &self,
7568        task_id: &str,
7569        lease_owner: &str,
7570        attempt: u64,
7571        run_id: Option<&str>,
7572        decision: Result<WorkflowTaskDecision>,
7573        memo_updates_supported: bool,
7574    ) -> Result<ManagedPollOutcome> {
7575        match decision {
7576            Ok(decision)
7577                if decision.cancellation_delivery.is_some()
7578                    || decision.cancellation_scope_delivery.is_some()
7579                    || decision.cancellation_scope_opening.is_some() =>
7580            {
7581                return Err(Error::CooperativeCancellationUnavailable(
7582                    "worker cancellation delivery has not been negotiated".into(),
7583                ));
7584            }
7585            Ok(decision)
7586                if commands_use_workflow_memo_updates(&decision.commands)
7587                    && !memo_updates_supported =>
7588            {
7589                self.client
7590                    .fail_workflow_task(
7591                        task_id,
7592                        lease_owner,
7593                        attempt,
7594                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
7595                    )
7596                    .await?;
7597            }
7598            Ok(decision) if decision.commands.is_empty() => {
7599                // A replay can consume a recorded pending durable command
7600                // without producing a new command. The standalone protocol
7601                // acknowledges that state through the typed waiting outcome;
7602                // an empty completion is rejected by servers that require at
7603                // least one executable command.
7604                self.client
7605                    .fail_workflow_task_with_type(
7606                        task_id,
7607                        lease_owner,
7608                        attempt,
7609                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
7610                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
7611                    )
7612                    .await?;
7613            }
7614            Ok(decision) => {
7615                let completion = self
7616                    .client
7617                    .complete_workflow_task_with_message_streams(
7618                        task_id,
7619                        lease_owner,
7620                        attempt,
7621                        decision.commands,
7622                        decision.message_stream_cursors,
7623                        decision.message_stream_waits,
7624                    )
7625                    .await;
7626                if let Err(error) = completion {
7627                    if !workflow_task_completion_is_terminal_timeout(
7628                        &error, task_id, attempt, run_id,
7629                    ) {
7630                        return Err(error);
7631                    }
7632                }
7633            }
7634            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
7635            Err(error) => {
7636                self.client
7637                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
7638                    .await?;
7639            }
7640        }
7641
7642        Ok(ManagedPollOutcome::Handled)
7643    }
7644
7645    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7646        while !stop.load(Ordering::SeqCst) {
7647            match self.poll_workflow_once().await {
7648                Ok(ManagedPollOutcome::Stop) => {
7649                    stop.store(true, Ordering::SeqCst);
7650                    break;
7651                }
7652                Err(error) => {
7653                    stop.store(true, Ordering::SeqCst);
7654                    return Err(error);
7655                }
7656                _ => {}
7657            }
7658        }
7659
7660        Ok(())
7661    }
7662
7663    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
7664        if self.client.worker_sessions_enabled {
7665            self.require_session_registration()?;
7666        }
7667        if self.cooperative_cancellation_enabled {
7668            return self.poll_cooperative_activity_once().await;
7669        }
7670        let poll_request_id = unique_request_id("rust-activity-poll");
7671        let response = self
7672            .retry_worker_operation(|| {
7673                self.client.poll_activity_task_response_with_request_id(
7674                    &self.worker_id,
7675                    &self.task_queue,
7676                    self.poll_timeout,
7677                    &poll_request_id,
7678                    0,
7679                )
7680            })
7681            .await;
7682        let Some(response) = self.settle_worker_poll_response(response).await? else {
7683            return Ok(ManagedPollOutcome::Idle);
7684        };
7685        if response.outcome().should_stop() {
7686            return Ok(ManagedPollOutcome::Stop);
7687        }
7688        let Some(task) = response.task else {
7689            return Ok(ManagedPollOutcome::Idle);
7690        };
7691
7692        let session = self.track_session_task(task.worker_session.as_ref())?;
7693        let task = task.task;
7694
7695        let task_id = task.task_id.clone();
7696        let attempt_id = task
7697            .activity_attempt_id
7698            .clone()
7699            .or(task.attempt_id.clone())
7700            .unwrap_or_default();
7701        let lease_owner = task
7702            .lease_owner
7703            .clone()
7704            .unwrap_or_else(|| self.worker_id.clone());
7705        let codec = task.payload_codec.clone();
7706        let result = self.execute_session_activity_task(task, session).await;
7707        match result {
7708            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
7709            Ok(value) => {
7710                let completion = self
7711                    .client
7712                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
7713                    .await;
7714                if let Err(error) = completion {
7715                    if !activity_task_rejection_is_final(&error) {
7716                        return Err(error);
7717                    }
7718                }
7719            }
7720            Err(error) => {
7721                let failure = self
7722                    .client
7723                    .fail_activity_task(
7724                        &task_id,
7725                        &attempt_id,
7726                        &lease_owner,
7727                        error.to_string(),
7728                        false,
7729                    )
7730                    .await;
7731                if let Err(error) = failure {
7732                    if !activity_task_rejection_is_final(&error) {
7733                        return Err(error);
7734                    }
7735                }
7736            }
7737        }
7738
7739        Ok(ManagedPollOutcome::Handled)
7740    }
7741
7742    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7743        // Each lane retains its leased response through callback settlement.
7744        // A bounded independent activity must not occupy the cleanup lane too.
7745        // Preserve the existing serial loop for default protocol 1.19 workers.
7746        let lane_count = if self.cooperative_cancellation_enabled {
7747            self.max_concurrent_activity_tasks
7748        } else {
7749            1
7750        };
7751        let mut lanes = FuturesUnordered::new();
7752        for _ in 0..lane_count {
7753            let worker = self.clone();
7754            let stop = Arc::clone(&stop);
7755            lanes.push(async move {
7756                while !stop.load(Ordering::SeqCst) {
7757                    match worker.poll_activity_once().await {
7758                        Ok(ManagedPollOutcome::Stop) => {
7759                            stop.store(true, Ordering::SeqCst);
7760                            break;
7761                        }
7762                        Err(error) => {
7763                            stop.store(true, Ordering::SeqCst);
7764                            return Err(error);
7765                        }
7766                        _ => {}
7767                    }
7768                }
7769                Ok(())
7770            });
7771        }
7772        // Join every lane before deregistration, including after one fails.
7773        let mut first_error = None;
7774        while let Some(result) = lanes.next().await {
7775            if let Err(error) = result {
7776                first_error.get_or_insert(error);
7777            }
7778        }
7779        first_error.map_or(Ok(()), Err)
7780    }
7781
7782    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
7783        let poll_request_id = unique_request_id("rust-query-poll");
7784        let response = self
7785            .retry_worker_operation(|| {
7786                self.client.poll_query_task_response_with_request_id(
7787                    &self.worker_id,
7788                    &self.task_queue,
7789                    self.poll_timeout,
7790                    &poll_request_id,
7791                    0,
7792                )
7793            })
7794            .await;
7795        let Some(response) = self.settle_worker_poll_response(response).await? else {
7796            return Ok(ManagedPollOutcome::Idle);
7797        };
7798        if response.outcome().should_stop() {
7799            return Ok(ManagedPollOutcome::Stop);
7800        }
7801        let Some(task) = response.task else {
7802            return Ok(ManagedPollOutcome::Idle);
7803        };
7804
7805        let query_task_id = task.query_task_id.clone();
7806        let attempt = task.query_task_attempt;
7807        let lease_owner = task
7808            .lease_owner
7809            .clone()
7810            .unwrap_or_else(|| self.worker_id.clone());
7811        let codec = task.payload_codec.clone();
7812
7813        match self.execute_query_task(task).await {
7814            Ok(value) => {
7815                let result_envelope = match encode_typed_envelope(&value, &codec) {
7816                    Ok(result_envelope) => result_envelope,
7817                    Err(error) => {
7818                        let failure = self
7819                            .client
7820                            .fail_query_task(
7821                                &query_task_id,
7822                                &lease_owner,
7823                                attempt,
7824                                error.to_string(),
7825                                "query_result_encode_failed",
7826                                "QueryResultEncodeFailed",
7827                            )
7828                            .await;
7829                        if let Err(error) = failure {
7830                            if !query_task_rejection_is_final(&error) {
7831                                return Err(error);
7832                            }
7833                        }
7834                        return Ok(ManagedPollOutcome::Handled);
7835                    }
7836                };
7837
7838                if let Err(error) = self
7839                    .client
7840                    .complete_query_task_with_envelope(
7841                        &query_task_id,
7842                        &lease_owner,
7843                        attempt,
7844                        value.clone().into_json()?,
7845                        result_envelope,
7846                    )
7847                    .await
7848                {
7849                    if !query_task_rejection_is_final(&error) {
7850                        return Err(error);
7851                    }
7852                }
7853            }
7854            Err(failure) => {
7855                let result = self
7856                    .client
7857                    .fail_query_task(
7858                        &query_task_id,
7859                        &lease_owner,
7860                        attempt,
7861                        failure.message,
7862                        failure.reason,
7863                        failure.failure_type,
7864                    )
7865                    .await;
7866                if let Err(error) = result {
7867                    if !query_task_rejection_is_final(&error) {
7868                        return Err(error);
7869                    }
7870                }
7871            }
7872        }
7873
7874        Ok(ManagedPollOutcome::Handled)
7875    }
7876
7877    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7878        while !stop.load(Ordering::SeqCst) {
7879            match self.poll_query_once().await {
7880                Ok(ManagedPollOutcome::Stop) => {
7881                    stop.store(true, Ordering::SeqCst);
7882                    break;
7883                }
7884                Err(error) => {
7885                    stop.store(true, Ordering::SeqCst);
7886                    return Err(error);
7887                }
7888                _ => {}
7889            }
7890        }
7891
7892        Ok(())
7893    }
7894
7895    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
7896    where
7897        F: FnMut() -> Fut,
7898        Fut: Future<Output = Result<T>>,
7899    {
7900        let mut retries = 0;
7901
7902        loop {
7903            if self
7904                .run_stop
7905                .as_ref()
7906                .is_some_and(|stop| stop.load(Ordering::SeqCst))
7907            {
7908                return Ok(None);
7909            }
7910            match operation().await {
7911                Err(error)
7912                    if worker_operation_is_retryable(&error)
7913                        && (retries < self.retry_policy.max_retries
7914                            || (self.recover_transient_outages
7915                                && self.run_stop.is_some()
7916                                && self.retry_policy.max_retries > 0)) =>
7917                {
7918                    retries = retries.saturating_add(1);
7919                    let delay = worker_retry_delay(self.retry_policy, retries)
7920                        .max(Duration::from_millis(1));
7921                    if let Some(stop) = &self.run_stop {
7922                        tokio::select! {
7923                            _ = tokio::time::sleep(delay) => {}
7924                            _ = wait_for_worker_stop(stop) => return Ok(None),
7925                        }
7926                    } else {
7927                        tokio::time::sleep(delay).await;
7928                    }
7929                }
7930                result => return result.map(Some),
7931            }
7932        }
7933    }
7934
7935    async fn settle_worker_poll_response<T>(
7936        &self,
7937        response: Result<Option<T>>,
7938    ) -> Result<Option<T>> {
7939        match response {
7940            Ok(response) => Ok(response),
7941            Err(error) => {
7942                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
7943                    return Err(error);
7944                };
7945                let minimum_delay = self
7946                    .retry_policy
7947                    .initial_backoff
7948                    .max(Duration::from_millis(1));
7949                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
7950                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
7951                Ok(None)
7952            }
7953        }
7954    }
7955
7956    async fn execute_query_task(
7957        &self,
7958        mut task: QueryTask,
7959    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
7960        validate_query_task_payloads(&task).map_err(|error| {
7961            QueryTaskExecutionFailure::new(
7962                "query_payload_decode_failed",
7963                error.to_string(),
7964                "QueryPayloadDecodeFailed",
7965            )
7966        })?;
7967
7968        if !self.workflows.contains_key(&task.workflow_type) {
7969            return Err(QueryTaskExecutionFailure::new(
7970                "query_workflow_type_not_registered",
7971                format!("no workflow registered for type {:?}", task.workflow_type),
7972                "WorkflowTypeNotRegistered",
7973            ));
7974        }
7975
7976        let Some(handlers) = self.queries.get(&task.workflow_type) else {
7977            return Err(QueryTaskExecutionFailure::new(
7978                "query_handler_unavailable",
7979                format!(
7980                    "query handlers are unavailable for workflow type {:?}",
7981                    task.workflow_type
7982                ),
7983                "QueryHandlerUnavailable",
7984            ));
7985        };
7986        let Some(query) = handlers.get(&task.query_name) else {
7987            return Err(QueryTaskExecutionFailure::new(
7988                "rejected_unknown_query",
7989                format!("unknown query {:?}", task.query_name),
7990                "QueryFailed",
7991            ));
7992        };
7993
7994        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
7995            .map_err(|error| {
7996            QueryTaskExecutionFailure::new(
7997                "query_payload_decode_failed",
7998                format!("cannot decode query arguments: {error}"),
7999                "QueryPayloadDecodeFailed",
8000            )
8001        })?;
8002        let workflow_input_typed =
8003            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8004                .map_err(|error| {
8005                    QueryTaskExecutionFailure::new(
8006                        "query_workflow_state_unavailable",
8007                        format!("cannot decode workflow start input: {error}"),
8008                        "QueryWorkflowStateUnavailable",
8009                    )
8010                })?;
8011        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8012            QueryTaskExecutionFailure::new(
8013                "query_workflow_state_unavailable",
8014                format!("cannot project workflow start input: {error}"),
8015                "QueryWorkflowStateUnavailable",
8016            )
8017        })?;
8018        hydrate_query_history_from_export(&mut task).map_err(|error| {
8019            QueryTaskExecutionFailure::new(
8020                "query_workflow_state_unavailable",
8021                format!("cannot restore query history snapshot: {error}"),
8022                "QueryWorkflowStateUnavailable",
8023            )
8024        })?;
8025        enrich_query_history_from_export(&mut task).map_err(|error| {
8026            QueryTaskExecutionFailure::new(
8027                "query_workflow_state_unavailable",
8028                format!("cannot restore compact query history payloads: {error}"),
8029                "QueryWorkflowStateUnavailable",
8030            )
8031        })?;
8032        let signal_events = query_signal_events(&task).map_err(|error| {
8033            QueryTaskExecutionFailure::new(
8034                "query_workflow_state_unavailable",
8035                format!("cannot decode committed workflow signals: {error}"),
8036                "QueryWorkflowStateUnavailable",
8037            )
8038        })?;
8039        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8040        let context = QueryContext {
8041            workflow_id: task.workflow_id,
8042            run_id: task.run_id,
8043            workflow_type: task.workflow_type.clone(),
8044            run_status: task.run_status,
8045            workflow_input,
8046            workflow_input_avro_value: workflow_input_typed.clone(),
8047            history_events: Arc::clone(&history_events),
8048            signal_events: Arc::new(signal_events),
8049        };
8050
8051        let future = match query {
8052            RegisteredQuery::Snapshot(handler) => handler(context, args),
8053            RegisteredQuery::Replayed {
8054                state_type,
8055                handler,
8056            } => {
8057                let workflow = self
8058                    .workflows
8059                    .get(&task.workflow_type)
8060                    .expect("workflow registration was checked above");
8061                if workflow.state_type != Some(*state_type) {
8062                    return Err(QueryTaskExecutionFailure::new(
8063                        "query_workflow_state_unavailable",
8064                        "replayed query state type does not match its workflow registration",
8065                        "QueryWorkflowStateUnavailable",
8066                    ));
8067                }
8068                let replay = workflow.replay.as_ref().ok_or_else(|| {
8069                    QueryTaskExecutionFailure::new(
8070                        "query_workflow_state_unavailable",
8071                        format!(
8072                            "workflow type {:?} is not registered for instance-state replay",
8073                            task.workflow_type
8074                        ),
8075                        "QueryWorkflowStateUnavailable",
8076                    )
8077                })?;
8078                let workflow_state = Arc::new(Mutex::new(
8079                    WorkflowState::new_with_identity(
8080                        history_events.as_ref().clone(),
8081                        context.workflow_id.clone(),
8082                        context.run_id.clone(),
8083                        self.task_queue.clone(),
8084                        task.payload_codec,
8085                        None,
8086                    )
8087                    .map_err(|error| {
8088                        QueryTaskExecutionFailure::new(
8089                            "query_workflow_state_unavailable",
8090                            format!("workflow replay failed before query: {error}"),
8091                            "QueryWorkflowStateUnavailable",
8092                        )
8093                    })?,
8094                ));
8095                let workflow_context = WorkflowContext {
8096                    state: workflow_state,
8097                    cancellation_scope_id: "root".into(),
8098                };
8099                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8100                let mut cx = TaskContext::from_waker(noop_waker_ref());
8101                let outcome = {
8102                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8103                        .map_err(|error| {
8104                            QueryTaskExecutionFailure::new(
8105                                "query_workflow_state_unavailable",
8106                                error.to_string(),
8107                                "QueryWorkflowStateUnavailable",
8108                            )
8109                        })?;
8110                    invocation.future.as_mut().poll(&mut cx)
8111                };
8112                match outcome {
8113                    Poll::Ready(Ok(_)) => {
8114                        workflow_context
8115                            .ensure_history_consumed()
8116                            .map_err(|error| {
8117                                QueryTaskExecutionFailure::new(
8118                                    "query_workflow_state_unavailable",
8119                                    format!("workflow replay failed before query: {error}"),
8120                                    "QueryWorkflowStateUnavailable",
8121                                )
8122                            })?;
8123                    }
8124                    Poll::Ready(Err(error)) => {
8125                        return Err(QueryTaskExecutionFailure::new(
8126                            "query_workflow_state_unavailable",
8127                            format!("workflow replay failed before query: {error}"),
8128                            "QueryWorkflowStateUnavailable",
8129                        ));
8130                    }
8131                    Poll::Pending => {
8132                        let commands = workflow_context.take_commands().map_err(|error| {
8133                            QueryTaskExecutionFailure::new(
8134                                "query_workflow_state_unavailable",
8135                                format!("workflow replay failed before query: {error}"),
8136                                "QueryWorkflowStateUnavailable",
8137                            )
8138                        })?;
8139                        if commands.is_empty()
8140                            && !workflow_context
8141                                .matched_recorded_pending()
8142                                .map_err(|error| {
8143                                    QueryTaskExecutionFailure::new(
8144                                        "query_workflow_state_unavailable",
8145                                        format!("workflow replay failed before query: {error}"),
8146                                        "QueryWorkflowStateUnavailable",
8147                                    )
8148                                })?
8149                        {
8150                            return Err(QueryTaskExecutionFailure::new(
8151                                "query_workflow_state_unavailable",
8152                                "workflow replay yielded without a durable command",
8153                                "QueryWorkflowStateUnavailable",
8154                            ));
8155                        }
8156                    }
8157                }
8158                let state = (invocation.snapshot)().map_err(|error| {
8159                    QueryTaskExecutionFailure::new(
8160                        "query_workflow_state_unavailable",
8161                        format!("cannot snapshot replayed workflow state: {error}"),
8162                        "QueryWorkflowStateUnavailable",
8163                    )
8164                })?;
8165                handler(context, state, args).map_err(|message| {
8166                    QueryTaskExecutionFailure::new(
8167                        "query_workflow_state_unavailable",
8168                        message,
8169                        "QueryWorkflowStateUnavailable",
8170                    )
8171                })?
8172            }
8173        };
8174
8175        future.await.map_err(|error| {
8176            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8177        })
8178    }
8179
8180    #[cfg(test)]
8181    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8182        Ok(self.execute_workflow_task_decision(task)?.commands)
8183    }
8184
8185    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8186        self.execute_workflow_task_decision_with_cancellation(task, None)
8187    }
8188
8189    fn execute_workflow_task_decision_with_cancellation(
8190        &self,
8191        task: WorkflowTask,
8192        observation: Option<&CancellationRequest>,
8193    ) -> Result<WorkflowTaskDecision> {
8194        match self.prepare_workflow_task_execution(task, observation)? {
8195            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8196            PreparedWorkflowTask::Execution {
8197                task,
8198                context,
8199                mut future,
8200            } => {
8201                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8202                self.finish_workflow_task_execution(&task, &context, outcome)
8203            }
8204        }
8205    }
8206
8207    fn prepare_workflow_task_execution(
8208        &self,
8209        task: WorkflowTask,
8210        observation: Option<&CancellationRequest>,
8211    ) -> Result<PreparedWorkflowTask> {
8212        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8213            && !self.cooperative_cancellation_enabled
8214        {
8215            return Err(Error::CancellationScopeExecutionUnavailable);
8216        }
8217        validate_workflow_task_payloads(&task)?;
8218        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8219            &task.history_events,
8220            self.allow_cancellation_scope_authoring,
8221            self.allow_cancellation_scope_delivery,
8222        )?;
8223        let cancellation_history = if let Some(observation) = observation {
8224            observation.validate_observation()?;
8225            cooperative_cancellation::cancellation_claim(&task)?;
8226            let canonical = CancellationHistory::from_events(
8227                &task.history_events,
8228                task.run_id.as_deref().unwrap_or_default(),
8229                Some(observation),
8230            )?;
8231            if canonical.request_index >= task.history_events.len() {
8232                return Err(Error::InvalidCooperativeCancellation(
8233                    "workflow replay requires the observed canonical request".into(),
8234                ));
8235            }
8236            Some(canonical)
8237        } else {
8238            None
8239        };
8240        if let Some(update_id) = task
8241            .workflow_update_id
8242            .as_deref()
8243            .filter(|update_id| !update_id.is_empty())
8244        {
8245            if self.allow_cancellation_scope_delivery {
8246                return Err(Error::CancellationScopeExecutionUnavailable);
8247            }
8248            CancellationHistory::from_events(
8249                &task.history_events,
8250                task.run_id.as_deref().unwrap_or_default(),
8251                None,
8252            )?;
8253            return self
8254                .execute_update_task(&task, update_id)
8255                .map(WorkflowTaskDecision::without_message_streams)
8256                .map(PreparedWorkflowTask::Decision);
8257        }
8258
8259        let workflow = self
8260            .workflows
8261            .get(&task.workflow_type)
8262            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8263        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8264        let resume_signal = decode_resume_signal(&task)?;
8265        let history_budget = WorkflowHistoryBudget {
8266            event_count: task
8267                .total_history_events
8268                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8269            size_bytes: task.history_size_bytes,
8270            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8271            pressure: task.history_budget_pressure.clone(),
8272        };
8273        let workflow_command_identity = task
8274            .workflow_command_id
8275            .clone()
8276            .filter(|identity| !identity.is_empty())
8277            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8278            .unwrap_or_default();
8279        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8280            task.history_events.clone(),
8281            task.workflow_id.clone(),
8282            task.run_id.clone(),
8283            self.task_queue.clone(),
8284            task.payload_codec.clone(),
8285            resume_signal,
8286            self.allow_cancellation_scope_authoring,
8287            self.allow_cancellation_scope_delivery,
8288        )?;
8289        workflow_state.history_budget = history_budget;
8290        workflow_state.workflow_command_identity = workflow_command_identity;
8291        if let Some(canonical) = cancellation_history {
8292            workflow_state.cancellation_history = canonical;
8293            workflow_state.cancellation_delivery_enabled = true;
8294        }
8295        if workflow_state.cancellation_history.request.is_none() {
8296            workflow_state.cancel_requested = task.cancel_requested;
8297        }
8298        let state = Arc::new(Mutex::new(workflow_state));
8299        let ctx = WorkflowContext {
8300            state,
8301            cancellation_scope_id: "root".into(),
8302        };
8303        let future = (workflow.execute)(ctx.clone(), input);
8304        Ok(PreparedWorkflowTask::Execution {
8305            task,
8306            context: ctx,
8307            future,
8308        })
8309    }
8310
8311    fn poll_workflow_future(
8312        ctx: &WorkflowContext,
8313        future: &mut WorkflowFuture,
8314    ) -> Result<Poll<Result<AvroValue>>> {
8315        let mut cx = TaskContext::from_waker(noop_waker_ref());
8316        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
8317        Ok(future.as_mut().poll(&mut cx))
8318    }
8319
8320    fn finish_workflow_task_execution(
8321        &self,
8322        task: &WorkflowTask,
8323        ctx: &WorkflowContext,
8324        outcome: Poll<Result<AvroValue>>,
8325    ) -> Result<WorkflowTaskDecision> {
8326        if !ctx
8327            .state
8328            .lock()
8329            .map_err(|_| Error::WorkflowStatePoisoned)?
8330            .local_activity_requests
8331            .is_empty()
8332        {
8333            return Err(Error::CooperativeCancellationUnavailable(
8334                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
8335            ));
8336        }
8337        let awaiting_canonical_boundary = {
8338            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8339            state.cancellation_delivery_intent.is_some()
8340                || state.cancellation_scope_opening.is_some()
8341                || state
8342                    .scope_delivery
8343                    .as_ref()
8344                    .is_some_and(|replay| replay.intent.is_some())
8345        };
8346        if awaiting_canonical_boundary {
8347            // A private delivery intent never becomes an application error.
8348            // Even a custom future which ignores a pending durable call cannot
8349            // publish terminal commands before canonical delivery and replay.
8350            if let Poll::Ready(Err(error)) = outcome {
8351                if workflow_task_integrity_error(&error) {
8352                    return Err(error);
8353                }
8354            }
8355            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8356        }
8357
8358        match outcome {
8359            Poll::Ready(Ok(result)) => {
8360                ctx.ensure_history_consumed()?;
8361                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8362                let mut commands = ctx.take_commands()?;
8363                commands.push(json!({
8364                    "type": "complete_workflow",
8365                    "result": result
8366                }));
8367                self.message_stream_decision(&ctx, commands)
8368            }
8369            Poll::Ready(Err(error)) => {
8370                if let Error::ContinueAsNew(request) = error {
8371                    let mut commands = ctx.take_commands()?;
8372                    if let Some(command) = ctx.continue_as_new_command(request)? {
8373                        commands.push(command);
8374                    }
8375                    ctx.ensure_history_consumed()?;
8376                    return self.message_stream_decision(&ctx, commands);
8377                }
8378                if workflow_task_integrity_error(&error) {
8379                    // Replay and protocol failures describe the workflow-task
8380                    // decision itself. Preserve their specific failure reason
8381                    // instead of replacing it with the derivative fact that
8382                    // recorded commands remain unconsumed.
8383                    return Err(error);
8384                }
8385                // A handler error must not hide a committed durable command that
8386                // upgraded workflow code no longer consumes.
8387                ctx.ensure_history_consumed()?;
8388                let mut commands = ctx.take_commands()?;
8389                commands.push(workflow_failure_command(
8390                    &error,
8391                    recorded_activity_failure_boundary(&ctx, &error),
8392                ));
8393                self.message_stream_decision(&ctx, commands)
8394            }
8395            Poll::Pending => {
8396                let commands = ctx.take_commands()?;
8397                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8398                    Err(Error::WorkflowYieldedWithoutCommand)
8399                } else {
8400                    self.message_stream_decision(&ctx, commands)
8401                }
8402            }
8403        }
8404    }
8405
8406    fn message_stream_decision(
8407        &self,
8408        ctx: &WorkflowContext,
8409        commands: Vec<Value>,
8410    ) -> Result<WorkflowTaskDecision> {
8411        if !self.cooperative_cancellation_enabled
8412            && commands.iter().any(|command| {
8413                command["type"] == "schedule_activity"
8414                    && command.get("cancellation_policy").is_some()
8415            })
8416        {
8417            return Err(Error::CooperativeCancellationUnavailable(format!(
8418                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8419                self.worker_id,
8420            )));
8421        }
8422        if !self.cooperative_cancellation_enabled
8423            && commands.iter().any(|command| {
8424                command["type"] == "start_child_workflow"
8425                    && (command["parent_close_policy"] == "request_cancellation"
8426                        || matches!(
8427                            command["cancellation_policy"].as_str(),
8428                            Some("try_cancel" | "wait_cancellation_completed")
8429                        ))
8430            })
8431        {
8432            return Err(Error::CooperativeCancellationUnavailable(format!(
8433                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8434                self.worker_id,
8435            )));
8436        }
8437        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
8438        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8439        let scope_delivery = state
8440            .scope_delivery
8441            .as_ref()
8442            .and_then(|replay| replay.intent.clone());
8443        if scope_delivery
8444            .as_ref()
8445            .is_some_and(|intent| commands.len() != intent.command_count)
8446        {
8447            return Err(invalid_recorded_history(
8448                "cancellation_scope_pending_call_escaped",
8449                scope_delivery.as_ref().unwrap().boundary.sequence,
8450                "commands preceding the pending scoped call",
8451                "commands after suspension",
8452                "workflow cannot publish beyond an uncommitted scope delivery",
8453            ));
8454        }
8455        if let Some(opening) = &state.cancellation_scope_opening {
8456            if commands.len() != opening.command_count {
8457                return Err(invalid_recorded_history(
8458                    "cancellation_scope_pending_call_escaped",
8459                    opening.sequence,
8460                    "commands before original scope opening",
8461                    "commands after suspended opening",
8462                    "workflow cannot publish beyond an uncommitted scope opening",
8463                ));
8464            }
8465        }
8466        if state.cancellation_delivery_intent.is_some()
8467            && commands.len() != state.cancellation_delivery_command_count
8468        {
8469            return Err(invalid_recorded_history(
8470                "cooperative_cancellation_pending_call_escaped",
8471                state
8472                    .cancellation_delivery_intent
8473                    .as_ref()
8474                    .expect("pending delivery")
8475                    .sequence,
8476                "only commands preceding the pending cancellation call",
8477                "commands authored after a suspended call",
8478                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
8479            ));
8480        }
8481        Ok(WorkflowTaskDecision {
8482            commands,
8483            message_stream_cursors,
8484            message_stream_waits,
8485            cancellation_delivery: state.cancellation_delivery_intent.clone(),
8486            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
8487            cancellation_scope_delivery: scope_delivery,
8488        })
8489    }
8490
8491    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
8492        if !self.workflows.contains_key(&task.workflow_type) {
8493            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
8494        }
8495
8496        let accepted = task.history_events.iter().rev().find_map(|event| {
8497            (event.event_type == "UpdateAccepted"
8498                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
8499            .then_some(&event.payload)
8500        });
8501        let update_name = accepted
8502            .and_then(|payload| payload.get("update_name"))
8503            .and_then(Value::as_str)
8504            .or(task.update_name.as_deref())
8505            .unwrap_or_default();
8506        let Some(handler) = self
8507            .updates
8508            .get(&task.workflow_type)
8509            .and_then(|handlers| handlers.get(update_name))
8510        else {
8511            return Ok(vec![json!({
8512                "type": "fail_update",
8513                "update_id": update_id,
8514                "message": format!(
8515                    "no update handler is registered for {}.{update_name}",
8516                    task.workflow_type
8517                ),
8518                "exception_type": "UnknownUpdate",
8519                "non_retryable": true,
8520            })]);
8521        };
8522        let arguments = accepted
8523            .and_then(|payload| payload.get("arguments"))
8524            .or(task.arguments.as_ref());
8525        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
8526        let context = QueryContext {
8527            workflow_id: task.workflow_id.clone(),
8528            run_id: task.run_id.clone(),
8529            workflow_type: task.workflow_type.clone(),
8530            run_status: Some("running".to_string()),
8531            workflow_input: Value::Null,
8532            workflow_input_avro_value: AvroValue::Null,
8533            history_events: Arc::new(task.history_events.clone()),
8534            signal_events: Arc::new(Vec::new()),
8535        };
8536        let mut future = handler(context, arguments);
8537        let mut cx = TaskContext::from_waker(noop_waker_ref());
8538
8539        match future.as_mut().poll(&mut cx) {
8540            Poll::Ready(Ok(result)) => Ok(vec![json!({
8541                "type": "complete_update",
8542                "update_id": update_id,
8543                "result": encode_typed_envelope(&result, &task.payload_codec)?,
8544            })]),
8545            Poll::Ready(Err(error)) => Ok(vec![json!({
8546                "type": "fail_update",
8547                "update_id": update_id,
8548                "message": error.to_string(),
8549                "exception_type": "UpdateFailed",
8550                "non_retryable": true,
8551            })]),
8552            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
8553        }
8554    }
8555
8556    #[cfg(test)]
8557    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
8558        self.execute_session_activity_task(task, None).await
8559    }
8560
8561    async fn execute_session_activity_task(
8562        &self,
8563        task: ActivityTask,
8564        worker_session: Option<WorkerSession>,
8565    ) -> Result<AvroValue> {
8566        validate_activity_task_payloads(&task)?;
8567        if worker_session.is_some() {
8568            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
8569                || task
8570                    .activity_attempt_id
8571                    .as_deref()
8572                    .or(task.attempt_id.as_deref())
8573                    .is_none_or(str::is_empty)
8574                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
8575            {
8576                return Err(Error::ActivityExecutionAbandoned(
8577                    "session activity requires this worker's exact immutable claim".into(),
8578                ));
8579            }
8580        }
8581
8582        let handler = self
8583            .activities
8584            .get(&task.activity_type)
8585            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
8586        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8587        let attempt_id = task
8588            .activity_attempt_id
8589            .clone()
8590            .or(task.attempt_id.clone())
8591            .unwrap_or_default();
8592        let lease_owner = task
8593            .lease_owner
8594            .clone()
8595            .unwrap_or_else(|| self.worker_id.clone());
8596        let session = worker_session.clone();
8597        let ctx = ActivityContext {
8598            client: self.client.clone(),
8599            task_id: task.task_id,
8600            activity_attempt_id: attempt_id,
8601            lease_owner,
8602            activity_type: task.activity_type,
8603            attempt_number: task.attempt_number,
8604            task_queue: self.task_queue.clone(),
8605            worker_id: self.worker_id.clone(),
8606            claim_guard: None,
8607            local_heartbeats: None,
8608            worker_session,
8609        };
8610
8611        let callback = handler(ctx, args);
8612        if let Some(session) = session {
8613            tokio::select! {
8614                biased;
8615                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
8616                result = callback => if session.active() { result } else {
8617                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
8618                },
8619            }
8620        } else {
8621            callback.await
8622        }
8623    }
8624}
8625
8626fn poller_result(
8627    kind: &str,
8628    result: std::result::Result<Result<()>, tokio::task::JoinError>,
8629) -> Result<()> {
8630    match result {
8631        Ok(result) => result,
8632        Err(error) => Err(Error::WorkerLoop(format!(
8633            "{kind} poller join error: {error}"
8634        ))),
8635    }
8636}
8637
8638fn optional_poller_result(
8639    kind: &str,
8640    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
8641) -> Result<()> {
8642    match result {
8643        Some(result) => poller_result(kind, result),
8644        None => Ok(()),
8645    }
8646}
8647
8648async fn join_pollers(
8649    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8650    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8651    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8652) -> Result<()> {
8653    let mut first_error = None;
8654
8655    if let Some(handle) = workflow_poller {
8656        if let Err(error) = poller_result("workflow", handle.await) {
8657            first_error.get_or_insert(error);
8658        }
8659    }
8660
8661    if let Some(handle) = activity_poller {
8662        if let Err(error) = poller_result("activity", handle.await) {
8663            first_error.get_or_insert(error);
8664        }
8665    }
8666
8667    if let Some(handle) = query_poller {
8668        if let Err(error) = poller_result("query", handle.await) {
8669            first_error.get_or_insert(error);
8670        }
8671    }
8672
8673    if let Some(error) = first_error {
8674        Err(error)
8675    } else {
8676        Ok(())
8677    }
8678}
8679
8680fn default_worker_id() -> String {
8681    let millis = SystemTime::now()
8682        .duration_since(UNIX_EPOCH)
8683        .unwrap_or_default()
8684        .as_millis();
8685    format!("rust-worker-{}-{millis}", std::process::id())
8686}
8687
8688fn percent_encode_path_segment(segment: &str) -> String {
8689    const HEX: &[u8; 16] = b"0123456789ABCDEF";
8690    let mut encoded = String::with_capacity(segment.len());
8691
8692    for byte in segment.bytes() {
8693        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
8694            encoded.push(char::from(byte));
8695        } else {
8696            encoded.push('%');
8697            encoded.push(char::from(HEX[(byte >> 4) as usize]));
8698            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
8699        }
8700    }
8701
8702    encoded
8703}
8704
8705fn unique_request_id(prefix: &str) -> String {
8706    let nanos = SystemTime::now()
8707        .duration_since(UNIX_EPOCH)
8708        .unwrap_or_default()
8709        .as_nanos();
8710    format!("{prefix}-{}-{nanos}", std::process::id())
8711}
8712
8713#[derive(Debug)]
8714struct QueryTaskExecutionFailure {
8715    reason: String,
8716    message: String,
8717    failure_type: String,
8718}
8719
8720impl QueryTaskExecutionFailure {
8721    fn new(
8722        reason: impl Into<String>,
8723        message: impl Into<String>,
8724        failure_type: impl Into<String>,
8725    ) -> Self {
8726        Self {
8727            reason: reason.into(),
8728            message: message.into(),
8729            failure_type: failure_type.into(),
8730        }
8731    }
8732}
8733
8734/// Typed local state owned by one deterministic workflow invocation.
8735///
8736/// Use [`WorkflowInstance::update`] for the same state transitions during
8737/// ordinary execution and replay. A replayed query receives a detached
8738/// immutable `Arc<S>` rather than this mutation-capable handle.
8739#[derive(Clone, Debug)]
8740pub struct WorkflowInstance<S> {
8741    state: Arc<Mutex<S>>,
8742}
8743
8744impl<S> WorkflowInstance<S> {
8745    fn new(state: S) -> Self {
8746        Self {
8747            state: Arc::new(Mutex::new(state)),
8748        }
8749    }
8750
8751    /// Read the current workflow-instance state without changing it.
8752    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
8753        let state = self
8754            .state
8755            .lock()
8756            .map_err(|_| Error::WorkflowStatePoisoned)?;
8757        Ok(reader(&state))
8758    }
8759
8760    /// Apply one deterministic workflow-instance state transition.
8761    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
8762        let mut state = self
8763            .state
8764            .lock()
8765            .map_err(|_| Error::WorkflowStatePoisoned)?;
8766        Ok(transition(&mut state))
8767    }
8768}
8769
8770impl<S: Clone> WorkflowInstance<S> {
8771    fn snapshot(&self) -> Result<S> {
8772        self.read(Clone::clone)
8773    }
8774}
8775
8776#[derive(Clone, Debug, PartialEq)]
8777pub struct MessageStreamMessage {
8778    pub stream_name: String,
8779    pub message_id: String,
8780    pub position: u64,
8781    pub arguments: Vec<AvroValue>,
8782}
8783
8784#[derive(Clone, Debug)]
8785pub struct MessageStream {
8786    ctx: WorkflowContext,
8787    name: String,
8788}
8789
8790impl MessageStream {
8791    /// Wait for one message, then return a bounded currently-available batch.
8792    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
8793        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
8794            return Err(Error::Codec(format!(
8795                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
8796            )));
8797        }
8798        loop {
8799            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
8800                return Ok(batch);
8801            }
8802
8803            self.ctx.record_message_stream_wait(&self.name)?;
8804            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
8805            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
8806            self.ctx.buffer_message_stream_delivery(arguments)?;
8807            if let Some(sequence) = replay_wait_sequence {
8808                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
8809            }
8810        }
8811    }
8812
8813    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
8814        self.receive(1)
8815            .await?
8816            .into_iter()
8817            .next()
8818            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
8819    }
8820}
8821
8822#[derive(Clone, Debug)]
8823pub struct WorkflowContext {
8824    state: Arc<Mutex<WorkflowState>>,
8825    cancellation_scope_id: String,
8826}
8827
8828fn valid_memo_key(key: &str) -> bool {
8829    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
8830
8831    !key.is_empty()
8832        && key.len() <= 64
8833        && (numeric_candidate.is_empty()
8834            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
8835        && key
8836            .bytes()
8837            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
8838}
8839
8840fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
8841    BASE64
8842        .decode(encode_avro_value(value)?.blob)
8843        .map(|bytes| bytes.len())
8844        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
8845}
8846
8847fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
8848    let AvroValue::Map(entries) = value else {
8849        return Err(Error::InvalidMemoUpdate(
8850            "entries must serialize to an Avro string-keyed map".to_string(),
8851        ));
8852    };
8853    if require_entries && entries.is_empty() {
8854        return Err(Error::InvalidMemoUpdate(
8855            "at least one entry is required".to_string(),
8856        ));
8857    }
8858    if entries.len() > MAX_MEMO_ENTRIES {
8859        return Err(Error::InvalidMemoUpdate(format!(
8860            "at most {MAX_MEMO_ENTRIES} entries are allowed"
8861        )));
8862    }
8863
8864    for (key, value) in &entries {
8865        if !valid_memo_key(&key) {
8866            return Err(Error::InvalidMemoUpdate(
8867                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
8868            ));
8869        }
8870        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
8871            return Err(Error::InvalidMemoUpdate(format!(
8872                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
8873            )));
8874        }
8875    }
8876
8877    let value = AvroValue::Map(entries);
8878    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
8879        return Err(Error::InvalidMemoUpdate(format!(
8880            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
8881        )));
8882    }
8883    Ok(value)
8884}
8885
8886fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
8887    let object = envelope.as_object().ok_or_else(|| {
8888        Error::InvalidMemoUpdate(
8889            "history field must use the public {codec, blob} payload envelope".to_string(),
8890        )
8891    })?;
8892    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
8893        return Err(Error::InvalidMemoUpdate(
8894            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
8895        ));
8896    }
8897
8898    canonical_memo_entries(
8899        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
8900        require_entries,
8901    )
8902}
8903
8904impl WorkflowContext {
8905    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
8906        let name = name.into();
8907        if name.is_empty()
8908            || name.len() > 128
8909            || !name.bytes().all(|byte| {
8910                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
8911            })
8912        {
8913            return Err(Error::Codec(
8914                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
8915                    .to_string(),
8916            ));
8917        }
8918        Ok(MessageStream {
8919            ctx: self.clone(),
8920            name,
8921        })
8922    }
8923
8924    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
8925        let mut state = self
8926            .state
8927            .lock()
8928            .map_err(|_| Error::WorkflowStatePoisoned)?;
8929        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
8930        state
8931            .message_stream_waits
8932            .insert(name.to_string(), position);
8933        Ok(())
8934    }
8935
8936    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
8937        let mut state = self
8938            .state
8939            .lock()
8940            .map_err(|_| Error::WorkflowStatePoisoned)?;
8941        let cursor = state
8942            .message_stream_cursors
8943            .get(&message.stream_name)
8944            .copied()
8945            .unwrap_or(0);
8946        if message.position <= cursor {
8947            return Ok(());
8948        }
8949        let pending = state
8950            .message_stream_messages
8951            .entry(message.stream_name.clone())
8952            .or_default();
8953        if pending.iter().any(|candidate| {
8954            candidate.position == message.position || candidate.message_id == message.message_id
8955        }) {
8956            return Ok(());
8957        }
8958        pending.push(message);
8959        pending.sort_by_key(|candidate| candidate.position);
8960        Ok(())
8961    }
8962
8963    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
8964        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
8965            match delivery {
8966                MessageStreamDelivery::Message(message) => {
8967                    let stream_name = message.stream_name.clone();
8968                    self.buffer_message_stream(message)?;
8969                    return Ok(Some(stream_name));
8970                }
8971                MessageStreamDelivery::Cursor {
8972                    stream_name,
8973                    through_position,
8974                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
8975            }
8976        }
8977        Ok(None)
8978    }
8979
8980    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
8981        let state = self
8982            .state
8983            .lock()
8984            .map_err(|_| Error::WorkflowStatePoisoned)?;
8985        Ok(match state.recorded_commands.get(state.command_cursor) {
8986            Some(RecordedCommand::SignalWait {
8987                sequence,
8988                signal_name,
8989                ..
8990            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
8991            _ => None,
8992        })
8993    }
8994
8995    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
8996        let (history, payload_codec) = {
8997            let state = self
8998                .state
8999                .lock()
9000                .map_err(|_| Error::WorkflowStatePoisoned)?;
9001            (
9002                Arc::clone(&state.history_events),
9003                state.payload_codec.clone(),
9004            )
9005        };
9006
9007        let Some(opened_index) = history.iter().position(|event| {
9008            event.event_type == "SignalWaitOpened"
9009                && durable_event_sequence(event) == Some(wait_sequence)
9010                && event.payload.get("signal_name").and_then(Value::as_str)
9011                    == Some(MESSAGE_STREAM_SIGNAL)
9012        }) else {
9013            return Ok(());
9014        };
9015        let boundary_index = history
9016            .iter()
9017            .enumerate()
9018            .skip(opened_index + 1)
9019            .find_map(|(index, event)| {
9020                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9021                    && is_authored_command_open_event(event))
9022                .then_some(index)
9023            })
9024            .unwrap_or(history.len());
9025
9026        for event in history[opened_index + 1..boundary_index]
9027            .iter()
9028            .filter(|event| {
9029                event.event_type == "SignalReceived"
9030                    && event.payload.get("signal_name").and_then(Value::as_str)
9031                        == Some(MESSAGE_STREAM_SIGNAL)
9032            })
9033        {
9034            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9035                .into_iter()
9036                .map(AvroValue::into_json)
9037                .collect::<Result<Vec<_>>>()?;
9038            self.buffer_message_stream_delivery(arguments)?;
9039        }
9040        Ok(())
9041    }
9042
9043    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9044        let mut state = self
9045            .state
9046            .lock()
9047            .map_err(|_| Error::WorkflowStatePoisoned)?;
9048        let cursor = state
9049            .message_stream_cursors
9050            .entry(name.to_string())
9051            .or_default();
9052        *cursor = (*cursor).max(through_position);
9053        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9054            pending.retain(|message| message.position > through_position);
9055        }
9056        Ok(())
9057    }
9058
9059    fn take_message_stream_batch(
9060        &self,
9061        name: &str,
9062        max_items: usize,
9063    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9064        let mut state = self
9065            .state
9066            .lock()
9067            .map_err(|_| Error::WorkflowStatePoisoned)?;
9068        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9069        let pending = state
9070            .message_stream_messages
9071            .entry(name.to_string())
9072            .or_default();
9073        let count = contiguous_message_stream_count(pending, cursor, max_items);
9074        if count == 0 {
9075            return Ok(None);
9076        }
9077        let batch = pending.drain(..count).collect::<Vec<_>>();
9078        let position = batch.last().map(|message| message.position).unwrap_or(0);
9079        state
9080            .message_stream_cursors
9081            .insert(name.to_string(), position);
9082        state.message_stream_waits.remove(name);
9083        Ok(Some(batch))
9084    }
9085
9086    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9087        let state = self
9088            .state
9089            .lock()
9090            .map_err(|_| Error::WorkflowStatePoisoned)?;
9091        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9092        cursors.sort_by_key(|(name, _)| *name);
9093        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9094        waits.sort_by_key(|(name, _)| *name);
9095        Ok((
9096            cursors
9097                .into_iter()
9098                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9099                .collect(),
9100            waits
9101                .into_iter()
9102                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9103                .collect(),
9104        ))
9105    }
9106    /// Identity of the parent workflow currently being replayed.
9107    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9108        let state = self
9109            .state
9110            .lock()
9111            .map_err(|_| Error::WorkflowStatePoisoned)?;
9112        Ok(WorkflowIdentity {
9113            workflow_id: state.workflow_id.clone(),
9114            run_id: state.run_id.clone(),
9115        })
9116    }
9117
9118    /// Return the server-published history budget for this workflow task.
9119    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9120        let state = self
9121            .state
9122            .lock()
9123            .map_err(|_| Error::WorkflowStatePoisoned)?;
9124        Ok(state.history_budget.clone())
9125    }
9126
9127    /// Continue this workflow instance as a fresh run with replacement arguments.
9128    ///
9129    /// Return this value directly from the workflow handler. The worker converts
9130    /// it to the terminal protocol command only after replay has consumed every
9131    /// recorded durable command.
9132    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9133        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9134    }
9135
9136    /// Continue as new with optional workflow-type and task-queue overrides.
9137    pub fn continue_as_new_with_options<T: Serialize>(
9138        &self,
9139        options: ContinueAsNewOptions,
9140        args: T,
9141    ) -> Result<Value> {
9142        options.validate()?;
9143        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9144            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9145            options,
9146        }))
9147    }
9148
9149    pub fn activity<T: Serialize>(
9150        &self,
9151        activity_type: impl Into<String>,
9152        args: T,
9153    ) -> ActivityCall {
9154        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9155    }
9156
9157    pub fn activity_on_queue<T, Q>(
9158        &self,
9159        activity_type: impl Into<String>,
9160        task_queue: Option<Q>,
9161        args: T,
9162    ) -> ActivityCall
9163    where
9164        T: Serialize,
9165        Q: Into<String>,
9166    {
9167        let mut options = ActivityOptions::new();
9168        options.task_queue = task_queue.map(Into::into);
9169        self.activity_with_options(activity_type, options, args)
9170    }
9171
9172    /// Schedule one durable activity with retry, routing, and timeout options.
9173    ///
9174    /// Options are validated before the command is emitted. Once the command is
9175    /// recorded, replay consumes the same activity lifecycle at this command
9176    /// position and never emits a duplicate schedule.
9177    ///
9178    /// ```no_run
9179    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9180    /// # use std::time::Duration;
9181    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9182    /// let result = ctx
9183    ///     .activity_with_options(
9184    ///         "charge-card",
9185    ///         ActivityOptions::new()
9186    ///             .task_queue("payments")
9187    ///             .retry_policy(
9188    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9189    ///                     Duration::from_secs(1),
9190    ///                     2,
9191    ///                     Some(Duration::from_secs(30)),
9192    ///                 ),
9193    ///             )
9194    ///             .start_to_close_timeout(Duration::from_secs(60))
9195    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9196    ///             .heartbeat_timeout(Duration::from_secs(15)),
9197    ///         json!([{"order_id": "order-42"}]),
9198    ///     )
9199    ///     .await;
9200    /// match result {
9201    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9202    ///         "reason": failure.reason,
9203    ///         "timeout_kind": failure.timeout_kind,
9204    ///     })),
9205    ///     other => other,
9206    /// }
9207    /// # }
9208    /// ```
9209    pub fn activity_with_options<T: Serialize>(
9210        &self,
9211        activity_type: impl Into<String>,
9212        options: ActivityOptions,
9213        args: T,
9214    ) -> ActivityCall {
9215        ActivityCall {
9216            ctx: self.clone(),
9217            activity_type: activity_type.into(),
9218            options,
9219            worker_session: None,
9220            args: Some(AvroValue::from_serialize(&args)),
9221            scheduled: false,
9222            local: false,
9223            local_result: None,
9224            parallel_group_path: Vec::new(),
9225        }
9226    }
9227
9228    pub async fn activity_avro_value<T: Serialize>(
9229        &self,
9230        activity_type: impl Into<String>,
9231        args: T,
9232    ) -> Result<AvroValue> {
9233        let mut call = self.activity(activity_type, args);
9234        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9235    }
9236
9237    pub async fn activity_avro_value_with_options<T: Serialize>(
9238        &self,
9239        activity_type: impl Into<String>,
9240        options: ActivityOptions,
9241        args: T,
9242    ) -> Result<AvroValue> {
9243        let mut call = self.activity_with_options(activity_type, options, args);
9244        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9245    }
9246
9247    /// Schedule an activity with a Serde request and decode its Serde result.
9248    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9249    where
9250        I: Serialize,
9251        O: DeserializeOwned,
9252    {
9253        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9254            .await
9255    }
9256
9257    /// Schedule an activity with options and decode its result into `O`.
9258    ///
9259    /// Both directions use the fixed Avro Value codec. In particular, this
9260    /// method does not deserialize the JSON-safe inspection projection returned
9261    /// by the dynamic [`ActivityCall`] future.
9262    pub async fn activity_typed_with_options<I, O>(
9263        &self,
9264        activity_type: impl Into<String>,
9265        options: ActivityOptions,
9266        args: I,
9267    ) -> Result<O>
9268    where
9269        I: Serialize,
9270        O: DeserializeOwned,
9271    {
9272        let activity_type = activity_type.into();
9273        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9274            handler_type_error::<I>(
9275                HandlerKind::Activity,
9276                &activity_type,
9277                HandlerValueKind::Input,
9278                error.to_string(),
9279            )
9280        });
9281        let mut call = ActivityCall {
9282            ctx: self.clone(),
9283            activity_type: activity_type.clone(),
9284            options,
9285            worker_session: None,
9286            args: Some(encoded),
9287            scheduled: false,
9288            local: false,
9289            local_result: None,
9290            parallel_group_path: Vec::new(),
9291        };
9292        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9293        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9294    }
9295
9296    /// Schedule and join a deterministic activity/child/timer group.
9297    ///
9298    /// Nested groups retain their input shape. Every durable leaf is scheduled
9299    /// before this future yields, results are assembled by declaration order,
9300    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9301    /// declaration path, stable group metadata, and completed siblings.
9302    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9303        ParallelCall::new(self.clone(), operations)
9304    }
9305
9306    /// Alias for [`WorkflowContext::parallel`].
9307    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9308        self.parallel(operations)
9309    }
9310
9311    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
9312    pub async fn parallel_avro_value(
9313        &self,
9314        operations: Vec<ParallelOperation>,
9315    ) -> Result<Vec<ParallelAvroResult>> {
9316        let mut call = self.parallel(operations);
9317        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9318    }
9319
9320    /// Start every durable operation and resume from the one winner persisted
9321    /// by Server. Non-winning operations continue and remain addressable.
9322    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
9323        let operations = operations
9324            .into_iter()
9325            .enumerate()
9326            .map(|(index, operation)| (SelectionKey::Index(index), operation))
9327            .collect();
9328        SelectCall::new(self.clone(), operations)
9329    }
9330
9331    /// Named-key variant of [`WorkflowContext::select`].
9332    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
9333    where
9334        K: Into<SelectionKey>,
9335    {
9336        SelectCall::new(
9337            self.clone(),
9338            operations
9339                .into_iter()
9340                .map(|(key, operation)| (key.into(), operation))
9341                .collect(),
9342        )
9343    }
9344
9345    /// Create a workflow-local deterministic compensation registry.
9346    pub fn saga(&self) -> Saga {
9347        Saga::new(self.clone())
9348    }
9349
9350    /// Whether cancellation has reached this replay's authored boundary.
9351    ///
9352    /// Server's current `/cancel` route is terminal and does not set this flag.
9353    /// A canonical service request remains pending until its committed delivery
9354    /// is consumed. Request observation alone does not authorize an exception.
9355    pub fn is_cancellation_requested(&self) -> Result<bool> {
9356        let state = self
9357            .state
9358            .lock()
9359            .map_err(|_| Error::WorkflowStatePoisoned)?;
9360        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9361            return Ok(state
9362                .scope_delivery
9363                .as_ref()
9364                .unwrap()
9365                .contexts
9366                .contains_key(&self.cancellation_scope_id));
9367        }
9368        Ok(state.cancel_requested
9369            || state
9370                .scope_delivery
9371                .as_ref()
9372                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
9373    }
9374
9375    /// Raise a typed cooperative cancellation at an author-controlled point.
9376    ///
9377    /// Passing this result to [`Saga::finish`] compensates already registered
9378    /// forward steps before the cancellation remains the initiating outcome.
9379    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
9380        let mut state = self
9381            .state
9382            .lock()
9383            .map_err(|_| Error::WorkflowStatePoisoned)?;
9384        if state.cancellation_shield_depth == 0 {
9385            if let Some(replay) = &state.scope_delivery {
9386                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
9387                    let delivered = replay
9388                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
9389                        .ok_or_else(|| {
9390                            Error::InvalidCooperativeCancellation(
9391                                "scoped request lacks its consumed original delivery".into(),
9392                            )
9393                        })?;
9394                    return Err(Error::CancellationScopeRequested(
9395                        CancellationScopeRequested {
9396                            context: context
9397                                .clone()
9398                                .with_replay(Some(Arc::downgrade(&self.state))),
9399                            delivery: delivered.boundary.clone(),
9400                        },
9401                    ));
9402                }
9403            }
9404        }
9405        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9406            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9407                return Ok(());
9408            }
9409            return Err(state.cancellation_error());
9410        }
9411        Ok(())
9412    }
9413
9414    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9415        SignalCall {
9416            ctx: self.clone(),
9417            signal_name: signal_name.into(),
9418            runtime_reserved_allowed: false,
9419            opened_wait: false,
9420            matched_pending: false,
9421            parallel_group_path: Vec::new(),
9422        }
9423    }
9424
9425    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9426        SignalCall {
9427            ctx: self.clone(),
9428            signal_name: signal_name.into(),
9429            runtime_reserved_allowed: true,
9430            opened_wait: false,
9431            matched_pending: false,
9432            parallel_group_path: Vec::new(),
9433        }
9434    }
9435
9436    pub async fn wait_signal_avro_value(
9437        &self,
9438        signal_name: impl Into<String>,
9439    ) -> Result<Vec<AvroValue>> {
9440        let mut call = self.wait_signal(signal_name);
9441        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9442    }
9443
9444    /// Return every committed signal argument list with the given name.
9445    ///
9446    /// This history-backed view is deterministic and is intended for
9447    /// condition predicates that must be re-evaluated after a signal while the
9448    /// workflow is blocked on [`WorkflowContext::wait_condition`].
9449    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
9450        self.signals_avro_value(signal_name)?
9451            .into_iter()
9452            .map(|arguments| {
9453                arguments
9454                    .into_iter()
9455                    .map(AvroValue::into_json)
9456                    .collect::<Result<Vec<_>>>()
9457            })
9458            .collect()
9459    }
9460
9461    /// Lossless fixed Avro Value view of committed signals with the given name.
9462    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9463        let state = self
9464            .state
9465            .lock()
9466            .map_err(|_| Error::WorkflowStatePoisoned)?;
9467        state
9468            .history_events
9469            .iter()
9470            .filter(|event| {
9471                event.event_type == "SignalReceived"
9472                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
9473            })
9474            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
9475            .collect()
9476    }
9477
9478    /// Return every committed update argument list with the given name.
9479    ///
9480    /// Accepted and applied records for the same update ID are de-duplicated.
9481    /// A Server task created after an update therefore replays the workflow and
9482    /// re-evaluates an open condition without application polling.
9483    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
9484        self.updates_avro_value(update_name)?
9485            .into_iter()
9486            .map(|arguments| {
9487                arguments
9488                    .into_iter()
9489                    .map(AvroValue::into_json)
9490                    .collect::<Result<Vec<_>>>()
9491            })
9492            .collect()
9493    }
9494
9495    /// Lossless fixed Avro Value view of committed updates with the given name.
9496    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9497        let state = self
9498            .state
9499            .lock()
9500            .map_err(|_| Error::WorkflowStatePoisoned)?;
9501        let mut seen = Vec::new();
9502        let mut updates = Vec::new();
9503        for event in state.history_events.iter() {
9504            if !matches!(
9505                event.event_type.as_str(),
9506                "UpdateAccepted" | "UpdateApplied"
9507            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
9508                || event.payload.get("arguments").is_none()
9509            {
9510                continue;
9511            }
9512            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
9513                if seen.iter().any(|recorded| recorded == update_id) {
9514                    continue;
9515                }
9516                seen.push(update_id.to_string());
9517            }
9518            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
9519        }
9520        Ok(updates)
9521    }
9522
9523    /// Wait for a deterministic predicate to become true or for its durable
9524    /// timeout to elapse.
9525    ///
9526    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
9527    /// predicate tokens automatically change the recorded definition
9528    /// fingerprint. Direct callers must provide an equally stable identity in
9529    /// [`ConditionWaitOptions`].
9530    pub fn wait_condition<F>(
9531        &self,
9532        options: ConditionWaitOptions,
9533        predicate: F,
9534    ) -> ConditionWaitCall
9535    where
9536        F: Fn() -> Result<bool> + Send + 'static,
9537    {
9538        ConditionWaitCall {
9539            ctx: self.clone(),
9540            options,
9541            predicate: Box::new(predicate),
9542            occurrence_id: None,
9543            opened_wait: false,
9544            parallel_group_path: Vec::new(),
9545        }
9546    }
9547
9548    /// Wait for server-backed durable time without blocking the worker executor.
9549    ///
9550    /// Polling this future emits one `start_timer` command and yields. The
9551    /// server records the deadline, so neither worker nor server restarts reset
9552    /// the wait. Replay resolves the future only from a `TimerScheduled` and
9553    /// `TimerFired` pair at the same position in the shared durable-command
9554    /// stream, with matching sequence, timer identity, and delay. Sub-second
9555    /// durations round up because protocol deadlines use whole seconds.
9556    ///
9557    /// ```no_run
9558    /// # use durable_workflow::{json, Client, Worker};
9559    /// # use std::time::Duration;
9560    /// # fn configure(client: Client) {
9561    /// let mut worker = Worker::new(client, "rust-workers");
9562    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
9563    ///     ctx.sleep(Duration::from_secs(5)).await?;
9564    ///     Ok(json!({"status": "timer fired"}))
9565    /// });
9566    /// # }
9567    /// ```
9568    pub fn sleep(&self, duration: Duration) -> TimerCall {
9569        let delay_seconds = duration
9570            .as_secs()
9571            .checked_add(u64::from(duration.subsec_nanos() > 0));
9572        TimerCall {
9573            ctx: self.clone(),
9574            delay_seconds,
9575            scheduled: false,
9576            matched_pending: false,
9577            parallel_group_path: Vec::new(),
9578        }
9579    }
9580
9581    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
9582    pub fn start_timer(&self, duration: Duration) -> TimerCall {
9583        self.sleep(duration)
9584    }
9585
9586    /// Evaluate a non-deterministic callback once and durably record its typed value.
9587    ///
9588    /// On replay the callback is not invoked: the value is decoded from the
9589    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
9590    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
9591    /// small values that must remain fixed for the lifetime of a workflow run.
9592    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
9593    where
9594        T: Serialize + DeserializeOwned,
9595        F: FnOnce() -> T,
9596    {
9597        {
9598            let mut state = self
9599                .state
9600                .lock()
9601                .map_err(|_| Error::WorkflowStatePoisoned)?;
9602            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9603                return match recorded {
9604                    RecordedCommand::SideEffect { sequence, value } => {
9605                        state.command_cursor += 1;
9606                        value.deserialize().map_err(|error| {
9607                            Error::NonDeterministicReplay(ReplayFailure::new(
9608                                "side_effect_type_mismatch",
9609                                Some(sequence),
9610                                Some(std::any::type_name::<T>().to_string()),
9611                                Some(error.to_string()),
9612                                "recorded side-effect value is incompatible with the requested Rust type",
9613                            ))
9614                        })
9615                    }
9616                    other => Err(command_mismatch(&other, "side effect")),
9617                };
9618            }
9619        }
9620
9621        let value = callback();
9622        let avro_value = AvroValue::from_serialize(&value)?;
9623        let mut state = self
9624            .state
9625            .lock()
9626            .map_err(|_| Error::WorkflowStatePoisoned)?;
9627        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
9628        state.commands.push(json!({
9629            "type": "record_side_effect",
9630            "result": result,
9631        }));
9632        Ok(value)
9633    }
9634
9635    /// Record or replay a lossless fixed Avro Value side effect.
9636    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
9637    where
9638        F: FnOnce() -> AvroValue,
9639    {
9640        {
9641            let mut state = self
9642                .state
9643                .lock()
9644                .map_err(|_| Error::WorkflowStatePoisoned)?;
9645            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9646                return match recorded {
9647                    RecordedCommand::SideEffect { value, .. } => {
9648                        state.command_cursor += 1;
9649                        Ok(value)
9650                    }
9651                    other => Err(command_mismatch(&other, "side effect")),
9652                };
9653            }
9654        }
9655
9656        let value = callback();
9657        let mut state = self
9658            .state
9659            .lock()
9660            .map_err(|_| Error::WorkflowStatePoisoned)?;
9661        let result = encode_typed_envelope(&value, &state.payload_codec)?;
9662        state.commands.push(json!({
9663            "type": "record_side_effect",
9664            "result": result,
9665        }));
9666        Ok(value)
9667    }
9668
9669    /// Append output items at a deterministic workflow command boundary.
9670    ///
9671    /// Stable idempotency keys are derived from the server-provided durable
9672    /// workflow command identity, command ordinal, and item index. Replay
9673    /// consumes the recorded side effect and never emits another append.
9674    pub fn append_workflow_stream(
9675        &self,
9676        stream_name: impl Into<String>,
9677        items: &[WorkflowStreamAppendItem],
9678        max_pending_items: Option<u64>,
9679    ) -> Result<()> {
9680        if items.is_empty() {
9681            return Err(Error::Codec(
9682                "workflow_stream_items_empty: append requires at least one item".to_string(),
9683            ));
9684        }
9685        if max_pending_items == Some(0) {
9686            return Err(Error::Codec(
9687                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
9688                    .to_string(),
9689            ));
9690        }
9691        let stream_name = stream_name.into();
9692        if stream_name.is_empty() {
9693            return Err(Error::Codec(
9694                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9695            ));
9696        }
9697
9698        let mut state = self
9699            .state
9700            .lock()
9701            .map_err(|_| Error::WorkflowStatePoisoned)?;
9702        let command_ordinal = state.workflow_stream_command_counter;
9703        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9704            state.workflow_stream_command_counter += 1;
9705            return match recorded {
9706                RecordedCommand::SideEffect { .. } => {
9707                    state.command_cursor += 1;
9708                    Ok(())
9709                }
9710                other => Err(command_mismatch(&other, "workflow stream append")),
9711            };
9712        }
9713
9714        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9715        state.workflow_stream_command_counter += 1;
9716        let wire_items = items
9717            .iter()
9718            .enumerate()
9719            .map(|(item_index, item)| {
9720                item.wire_value(Some(format!(
9721                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
9722                )))
9723            })
9724            .collect::<Vec<_>>();
9725        let mut directive = json!({
9726            "operation": "append",
9727            "stream_name": stream_name,
9728            "command_identity": identity,
9729            "command_ordinal": command_ordinal,
9730            "items": wire_items,
9731        });
9732        if let Some(max_pending_items) = max_pending_items {
9733            directive["max_pending_items"] = json!(max_pending_items);
9734        }
9735        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9736        state.commands.push(json!({
9737            "type": "record_side_effect",
9738            "result": result,
9739            "workflow_stream": directive,
9740        }));
9741        Ok(())
9742    }
9743
9744    /// Close a run-scoped output stream at a deterministic command boundary.
9745    pub fn close_workflow_stream(
9746        &self,
9747        stream_name: impl Into<String>,
9748        retention_seconds: Option<u64>,
9749    ) -> Result<()> {
9750        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
9751    }
9752
9753    /// Mark a run-scoped output stream errored at a deterministic command boundary.
9754    pub fn error_workflow_stream(
9755        &self,
9756        stream_name: impl Into<String>,
9757        error_reason: impl Into<String>,
9758        retention_seconds: Option<u64>,
9759    ) -> Result<()> {
9760        let error_reason = error_reason.into();
9761        if error_reason.is_empty() {
9762            return Err(Error::Codec(
9763                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
9764            ));
9765        }
9766        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
9767    }
9768
9769    fn finish_workflow_stream(
9770        &self,
9771        stream_name: String,
9772        error_reason: Option<String>,
9773        retention_seconds: Option<u64>,
9774    ) -> Result<()> {
9775        if stream_name.is_empty() {
9776            return Err(Error::Codec(
9777                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9778            ));
9779        }
9780        if retention_seconds == Some(0) {
9781            return Err(Error::Codec(
9782                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
9783            ));
9784        }
9785        let mut state = self
9786            .state
9787            .lock()
9788            .map_err(|_| Error::WorkflowStatePoisoned)?;
9789        let command_ordinal = state.workflow_stream_command_counter;
9790        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9791            state.workflow_stream_command_counter += 1;
9792            return match recorded {
9793                RecordedCommand::SideEffect { .. } => {
9794                    state.command_cursor += 1;
9795                    Ok(())
9796                }
9797                other => Err(command_mismatch(&other, "workflow stream close")),
9798            };
9799        }
9800        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9801        state.workflow_stream_command_counter += 1;
9802        let mut directive = json!({
9803            "operation": if error_reason.is_some() { "error" } else { "close" },
9804            "stream_name": stream_name,
9805            "command_identity": identity,
9806            "command_ordinal": command_ordinal,
9807        });
9808        if let Some(error_reason) = error_reason {
9809            directive["error_reason"] = json!(error_reason);
9810        }
9811        if let Some(retention_seconds) = retention_seconds {
9812            directive["retention_seconds"] = json!(retention_seconds);
9813        }
9814        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9815        state.commands.push(json!({
9816            "type": "record_side_effect",
9817            "result": result,
9818            "workflow_stream": directive,
9819        }));
9820        Ok(())
9821    }
9822
9823    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
9824        let identity = state.workflow_command_identity.as_str();
9825        if identity.is_empty() {
9826            return Err(Error::MissingWorkflowCommandIdentity);
9827        }
9828        Ok(identity)
9829    }
9830
9831    /// Validate, emit, or replay a typed workflow search-attribute update.
9832    ///
9833    /// The command is non-blocking within a workflow decision, but its
9834    /// `SearchAttributesUpserted` event occupies the same deterministic command
9835    /// stream as activities, timers, conditions, and other durable operations.
9836    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
9837        update.validate()?;
9838        let (attributes, attribute_types) = update.into_wire_parts();
9839        let mut state = self
9840            .state
9841            .lock()
9842            .map_err(|_| Error::WorkflowStatePoisoned)?;
9843
9844        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9845            return match recorded {
9846                RecordedCommand::SearchAttributes {
9847                    sequence,
9848                    attributes: recorded_attributes,
9849                    attribute_types: recorded_attribute_types,
9850                } => {
9851                    if recorded_attributes != attributes {
9852                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9853                            "search_attribute_value_mismatch",
9854                            Some(sequence),
9855                            Some(recorded_attributes.to_string()),
9856                            Some(attributes.to_string()),
9857                            "search-attribute values differ from the recorded durable command",
9858                        )));
9859                    }
9860                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
9861                        if recorded_types != attribute_types {
9862                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9863                                "search_attribute_type_mismatch",
9864                                Some(sequence),
9865                                Some(json!(recorded_types).to_string()),
9866                                Some(json!(attribute_types).to_string()),
9867                                "search-attribute declared types differ from the recorded durable command",
9868                            )));
9869                        }
9870                    }
9871                    state.command_cursor += 1;
9872                    Ok(())
9873                }
9874                other => Err(command_mismatch(&other, "search-attribute update")),
9875            };
9876        }
9877
9878        let mut command = serde_json::Map::from_iter([
9879            ("type".to_string(), json!("upsert_search_attributes")),
9880            ("attributes".to_string(), attributes),
9881        ]);
9882        if !attribute_types.is_empty() {
9883            command.insert("attribute_types".to_string(), json!(attribute_types));
9884        }
9885        state.commands.push(Value::Object(command));
9886        Ok(())
9887    }
9888
9889    /// Record a UUIDv4 once and return the same UUID on every replay.
9890    pub fn uuid_v4(&self) -> Result<Uuid> {
9891        self.side_effect(Uuid::new_v4)
9892    }
9893
9894    /// Select the newest supported version for a change, or replay the version
9895    /// already committed for that stable change ID.
9896    pub fn get_version(
9897        &self,
9898        change_id: impl Into<String>,
9899        min_supported: i32,
9900        max_supported: i32,
9901    ) -> Result<i32> {
9902        let change_id = change_id.into();
9903        if change_id.trim().is_empty() {
9904            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9905                "version_change_id_invalid",
9906                None,
9907                Some("non-empty change ID".to_string()),
9908                Some(change_id),
9909                "version markers require a stable non-empty change ID",
9910            )));
9911        }
9912        if min_supported > max_supported {
9913            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9914                "version_range_invalid",
9915                None,
9916                Some("min_supported <= max_supported".to_string()),
9917                Some(format!("{min_supported}..={max_supported}")),
9918                "version marker supported range is invalid",
9919            )));
9920        }
9921
9922        let mut state = self
9923            .state
9924            .lock()
9925            .map_err(|_| Error::WorkflowStatePoisoned)?;
9926        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
9927            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
9928            return Ok(version);
9929        }
9930
9931        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9932            return match recorded {
9933                RecordedCommand::VersionMarker {
9934                    sequence,
9935                    change_id: recorded_change_id,
9936                    version,
9937                    ..
9938                } => {
9939                    if recorded_change_id != change_id {
9940                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9941                            "version_change_id_mismatch",
9942                            Some(sequence),
9943                            Some(recorded_change_id),
9944                            Some(change_id),
9945                            "recorded version marker change ID differs from current workflow code",
9946                        )));
9947                    }
9948                    ensure_version_supported(
9949                        &change_id,
9950                        version,
9951                        min_supported,
9952                        max_supported,
9953                        sequence,
9954                    )?;
9955                    state.command_cursor += 1;
9956                    state.version_markers.insert(change_id, (version, sequence));
9957                    Ok(version)
9958                }
9959                other => Err(command_mismatch(
9960                    &other,
9961                    format!("version marker:{change_id}"),
9962                )),
9963            };
9964        }
9965
9966        let version = max_supported;
9967        state.commands.push(json!({
9968            "type": "record_version_marker",
9969            "change_id": change_id,
9970            "version": version,
9971            "min_supported": min_supported,
9972            "max_supported": max_supported,
9973        }));
9974        // Sequence numbers are assigned by the server. Zero identifies a marker
9975        // selected in this uncommitted decision batch for duplicate-call checks.
9976        state.version_markers.insert(change_id, (version, 0));
9977        Ok(version)
9978    }
9979
9980    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
9981    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
9982        Ok(self.get_version(change_id, -1, 1)? == 1)
9983    }
9984
9985    /// Keep a patch marker in history after the legacy branch has been removed.
9986    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
9987        self.get_version(change_id, -1, 1).map(|_| ())
9988    }
9989
9990    /// Merge non-indexed workflow memo metadata through durable history.
9991    ///
9992    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
9993    /// public Avro payload envelope consumed by Server and Cloud runtimes.
9994    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
9995        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
9996        let mut state = self
9997            .state
9998            .lock()
9999            .map_err(|_| Error::WorkflowStatePoisoned)?;
10000
10001        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10002            return match recorded {
10003                RecordedCommand::Memo {
10004                    sequence,
10005                    entries: recorded_entries,
10006                } => {
10007                    if recorded_entries != entries {
10008                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10009                            "memo_update_mismatch",
10010                            Some(sequence),
10011                            Some(format!("{recorded_entries:?}")),
10012                            Some(format!("{entries:?}")),
10013                            "recorded memo entries differ from the current workflow update",
10014                        )));
10015                    }
10016                    state.command_cursor += 1;
10017                    Ok(())
10018                }
10019                other => Err(command_mismatch(&other, "memo upsert")),
10020            };
10021        }
10022
10023        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10024        state.commands.push(json!({
10025            "type": "upsert_memo",
10026            "entries": entries_envelope,
10027        }));
10028        Ok(())
10029    }
10030
10031    /// Start a named durable child on an explicit queue and await its result.
10032    ///
10033    /// The command is recorded in the parent's sequence-ordered durable command
10034    /// stream. Replay keeps a scheduled child pending without emitting another
10035    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10036    /// values preserve the history payload codec and include both sides of the
10037    /// durable relationship; failures are returned as
10038    /// [`Error::ChildWorkflowFailed`].
10039    ///
10040    /// ```no_run
10041    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10042    /// # fn configure(client: Client) {
10043    /// let mut worker = Worker::new(client, "parent-workers");
10044    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10045    ///     let child = ctx
10046    ///         .start_child_workflow(
10047    ///             "fulfil-order",
10048    ///             ChildWorkflowOptions::new("fulfilment-workers")
10049    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10050    ///             json!([{"order_id": "order-42"}]),
10051    ///         )
10052    ///         .await?;
10053    ///     Ok(child.result)
10054    /// });
10055    /// # }
10056    /// ```
10057    pub fn start_child_workflow<T: Serialize>(
10058        &self,
10059        workflow_type: impl Into<String>,
10060        options: ChildWorkflowOptions,
10061        args: T,
10062    ) -> ChildWorkflowCall {
10063        ChildWorkflowCall {
10064            ctx: self.clone(),
10065            workflow_type: workflow_type.into(),
10066            options,
10067            args: Some(AvroValue::from_serialize(&args)),
10068            scheduled: false,
10069            matched_pending: false,
10070            parallel_group_path: Vec::new(),
10071        }
10072    }
10073
10074    pub async fn start_child_workflow_avro_value<T: Serialize>(
10075        &self,
10076        workflow_type: impl Into<String>,
10077        options: ChildWorkflowOptions,
10078        args: T,
10079    ) -> Result<ChildWorkflowAvroResult> {
10080        let mut call = self.start_child_workflow(workflow_type, options, args);
10081        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10082    }
10083
10084    fn take_commands(&self) -> Result<Vec<Value>> {
10085        let mut state = self
10086            .state
10087            .lock()
10088            .map_err(|_| Error::WorkflowStatePoisoned)?;
10089        Ok(std::mem::take(&mut state.commands))
10090    }
10091
10092    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10093        let mut state = self
10094            .state
10095            .lock()
10096            .map_err(|_| Error::WorkflowStatePoisoned)?;
10097
10098        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10099            return Err(command_mismatch(&recorded, "continue as new"));
10100        }
10101        if state.recorded_continue_as_new_sequence.is_some() {
10102            state.continue_as_new_consumed = true;
10103            return Ok(None);
10104        }
10105
10106        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10107        let mut command = serde_json::Map::from_iter([
10108            ("type".to_string(), json!("continue_as_new")),
10109            ("arguments".to_string(), arguments),
10110            ("queue".to_string(), json!(state.task_queue.clone())),
10111        ]);
10112        if let Some(workflow_type) = request.options.workflow_type {
10113            command.insert("workflow_type".to_string(), json!(workflow_type));
10114        }
10115        if let Some(task_queue) = request.options.task_queue {
10116            command.insert("queue".to_string(), json!(task_queue));
10117        }
10118        Ok(Some(Value::Object(command)))
10119    }
10120
10121    fn matched_recorded_pending(&self) -> Result<bool> {
10122        let state = self
10123            .state
10124            .lock()
10125            .map_err(|_| Error::WorkflowStatePoisoned)?;
10126        Ok(state.matched_recorded_pending)
10127    }
10128
10129    fn ensure_history_consumed(&self) -> Result<()> {
10130        let state = self
10131            .state
10132            .lock()
10133            .map_err(|_| Error::WorkflowStatePoisoned)?;
10134        if let Some(replay) = &state.scope_delivery {
10135            if let Some((&sequence, _)) = replay
10136                .canonical
10137                .deliveries
10138                .iter()
10139                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10140            {
10141                return Err(invalid_recorded_history(
10142                    "cancellation_scope_delivery_unconsumed",
10143                    sequence,
10144                    "original scoped delivery",
10145                    "workflow completion",
10146                    "workflow completed without consuming its committed scope delivery",
10147                ));
10148            }
10149        }
10150        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10151            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10152                "recorded_commands_unconsumed",
10153                Some(command.sequence()),
10154                Some(command.shape().to_string()),
10155                Some("workflow completion".to_string()),
10156                "workflow completed before consuming all recorded durable commands",
10157            )));
10158        }
10159        if let Some(delivery) = state
10160            .cancellation_history
10161            .delivery
10162            .as_ref()
10163            .filter(|_| !state.cancellation_consumed)
10164        {
10165            return Err(invalid_recorded_history(
10166                "cooperative_cancellation_unconsumed",
10167                delivery.sequence,
10168                "committed cancellation call",
10169                "workflow completion",
10170                "workflow completed without reaching its committed cancellation boundary",
10171            ));
10172        }
10173        if let Some(sequence) = state
10174            .recorded_continue_as_new_sequence
10175            .filter(|_| !state.continue_as_new_consumed)
10176        {
10177            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10178                "recorded_continue_as_new_unconsumed",
10179                Some(sequence),
10180                Some("continue as new".to_string()),
10181                Some("workflow completion".to_string()),
10182                "workflow completed without consuming its recorded continue-as-new transition",
10183            )));
10184        }
10185        Ok(())
10186    }
10187}
10188
10189fn contiguous_message_stream_count(
10190    pending: &[MessageStreamMessage],
10191    cursor: u64,
10192    max_items: usize,
10193) -> usize {
10194    pending
10195        .iter()
10196        .take(max_items)
10197        .enumerate()
10198        .take_while(|(offset, message)| {
10199            u64::try_from(*offset)
10200                .ok()
10201                .and_then(|offset| cursor.checked_add(offset + 1))
10202                == Some(message.position)
10203        })
10204        .count()
10205}
10206
10207fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10208    matches!(
10209        event.event_type.as_str(),
10210        "ActivityScheduled"
10211            | "TimerScheduled"
10212            | "ChildWorkflowScheduled"
10213            | "SignalWaitOpened"
10214            | "ConditionWaitOpened"
10215            | "SearchAttributesUpserted"
10216            | "SideEffectRecorded"
10217            | "VersionMarkerRecorded"
10218            | "MemoUpserted"
10219            | "WorkflowContinuedAsNew"
10220    )
10221}
10222
10223#[derive(Debug)]
10224struct WorkflowState {
10225    workflow_id: Option<String>,
10226    run_id: Option<String>,
10227    task_queue: String,
10228    payload_codec: String,
10229    history_events: Arc<Vec<HistoryEvent>>,
10230    history_budget: WorkflowHistoryBudget,
10231    cancel_requested: bool,
10232    cancellation_history: CancellationHistory,
10233    cancellation_consumed: bool,
10234    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10235    cancellation_shield_depth: u64,
10236    cancellation_delivery_enabled: bool,
10237    cancellation_delivery_intent: Option<CancellationDelivery>,
10238    cancellation_delivery_command_count: usize,
10239    allow_cancellation_scope_authoring: bool,
10240    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10241    cancellation_scope_memberships: BTreeMap<u64, String>,
10242    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10243    resume_signal: Option<ResumeSignal>,
10244    recorded_commands: Vec<RecordedCommand>,
10245    selection_markers: Vec<SelectionMarker>,
10246    selection_marker_cursor: usize,
10247    cancelled_selection_members: Vec<SelectionCancellation>,
10248    recorded_continue_as_new_sequence: Option<u64>,
10249    continue_as_new_consumed: bool,
10250    command_cursor: usize,
10251    condition_wait_occurrence_counter: u64,
10252    matched_recorded_pending: bool,
10253    version_markers: HashMap<String, (i32, u64)>,
10254    workflow_command_identity: String,
10255    workflow_stream_command_counter: u64,
10256    commands: Vec<Value>,
10257    local_activity_requests: Vec<local_activity::Request>,
10258    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
10259    message_stream_cursors: HashMap<String, u64>,
10260    message_stream_waits: HashMap<String, u64>,
10261}
10262
10263impl WorkflowState {
10264    #[cfg(test)]
10265    fn new(
10266        history: Vec<HistoryEvent>,
10267        task_queue: String,
10268        payload_codec: String,
10269        resume_signal: Option<ResumeSignal>,
10270    ) -> Result<Self> {
10271        Self::new_with_identity(
10272            history,
10273            None,
10274            None,
10275            task_queue,
10276            payload_codec,
10277            resume_signal,
10278        )
10279    }
10280
10281    fn new_with_identity(
10282        history: Vec<HistoryEvent>,
10283        workflow_id: Option<String>,
10284        run_id: Option<String>,
10285        task_queue: String,
10286        payload_codec: String,
10287        resume_signal: Option<ResumeSignal>,
10288    ) -> Result<Self> {
10289        Self::new_with_identity_and_scopes(
10290            history,
10291            workflow_id,
10292            run_id,
10293            task_queue,
10294            payload_codec,
10295            resume_signal,
10296            false,
10297        )
10298    }
10299
10300    fn new_with_identity_and_scopes(
10301        history: Vec<HistoryEvent>,
10302        workflow_id: Option<String>,
10303        run_id: Option<String>,
10304        task_queue: String,
10305        payload_codec: String,
10306        resume_signal: Option<ResumeSignal>,
10307        allow_cancellation_scope_authoring: bool,
10308    ) -> Result<Self> {
10309        Self::new_with_identity_and_scope_delivery(
10310            history,
10311            workflow_id,
10312            run_id,
10313            task_queue,
10314            payload_codec,
10315            resume_signal,
10316            allow_cancellation_scope_authoring,
10317            false,
10318        )
10319    }
10320
10321    fn new_with_identity_and_scope_delivery(
10322        history: Vec<HistoryEvent>,
10323        workflow_id: Option<String>,
10324        run_id: Option<String>,
10325        task_queue: String,
10326        payload_codec: String,
10327        resume_signal: Option<ResumeSignal>,
10328        allow_cancellation_scope_authoring: bool,
10329        allow_cancellation_scope_delivery: bool,
10330    ) -> Result<Self> {
10331        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10332            &history,
10333            allow_cancellation_scope_authoring,
10334            allow_cancellation_scope_delivery,
10335        )?;
10336        let scopes = if allow_cancellation_scope_authoring {
10337            cancellation_scope::CancellationScopeHistory::read(
10338                &history,
10339                run_id.as_deref().unwrap_or_default(),
10340            )?
10341        } else {
10342            cancellation_scope::CancellationScopeHistory::default()
10343        };
10344        let cancellation_history = CancellationHistory::from_events(
10345            &history,
10346            run_id.as_deref().unwrap_or_default(),
10347            None,
10348        )?;
10349        if allow_cancellation_scope_authoring
10350            && cancellation_history.request.is_some()
10351            && !allow_cancellation_scope_delivery
10352        {
10353            return Err(Error::CancellationScopeExecutionUnavailable);
10354        }
10355        let scope_delivery = if allow_cancellation_scope_delivery {
10356            Some(cancellation_scope_replay::ScopeReplay::read(
10357                &history,
10358                &scopes,
10359                run_id.as_deref().unwrap_or_default(),
10360                workflow_id.as_deref().unwrap_or_default(),
10361            )?)
10362        } else {
10363            None
10364        };
10365        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
10366            &history,
10367            &payload_codec,
10368            WorkflowIdentity {
10369                workflow_id: workflow_id.clone(),
10370                run_id: run_id.clone(),
10371            },
10372        )?)?;
10373        for (sequence, opening) in &scopes.openings {
10374            if recorded_commands
10375                .iter()
10376                .any(|command| command.sequence() == *sequence)
10377            {
10378                return Err(invalid_recorded_history(
10379                    "invalid_cancellation_scope_history",
10380                    *sequence,
10381                    "distinct authored scope opening",
10382                    "operation collision",
10383                    "scope opening collides with a command",
10384                ));
10385            }
10386            recorded_commands.push(RecordedCommand::CancellationScope {
10387                sequence: *sequence,
10388                scope_id: opening.scope_id.clone(),
10389                parent_scope_id: opening.parent_scope_id.clone(),
10390                shield_parent: opening.shield_parent,
10391            });
10392        }
10393        recorded_commands.sort_by_key(RecordedCommand::sequence);
10394        if let Some(replay) = &scope_delivery {
10395            replay.bind_commands(&mut recorded_commands)?;
10396        }
10397        let selection_markers = recorded_selection_markers(&history)?;
10398        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
10399        let recorded_continue_as_new = history
10400            .iter()
10401            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
10402            .collect::<Vec<_>>();
10403        if recorded_continue_as_new.len() > 1 {
10404            return Err(invalid_recorded_history(
10405                "duplicate_continue_as_new_transition",
10406                recorded_continue_as_new
10407                    .last()
10408                    .and_then(|event| durable_event_sequence(event))
10409                    .unwrap_or(0),
10410                "one WorkflowContinuedAsNew event",
10411                &format!(
10412                    "{} WorkflowContinuedAsNew events",
10413                    recorded_continue_as_new.len()
10414                ),
10415                "workflow history records one continue-as-new transition more than once",
10416            ));
10417        }
10418        let recorded_continue_as_new_sequence = recorded_continue_as_new
10419            .first()
10420            .map(|event| {
10421                durable_event_sequence(event).ok_or_else(|| {
10422                    Error::NonDeterministicReplay(ReplayFailure::new(
10423                        "continue_as_new_sequence_missing",
10424                        None,
10425                        Some("recorded transition sequence".to_string()),
10426                        Some("missing sequence".to_string()),
10427                        "WorkflowContinuedAsNew history is missing its recorded sequence",
10428                    ))
10429                })
10430            })
10431            .transpose()?;
10432        let mut message_stream_cursors = HashMap::new();
10433        for event in &history {
10434            if !matches!(
10435                event.event_type.as_str(),
10436                "SignalReceived" | "SignalApplied"
10437            ) || event.payload.get("signal_name").and_then(Value::as_str)
10438                != Some(MESSAGE_STREAM_SIGNAL)
10439            {
10440                continue;
10441            }
10442            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
10443            if arguments.len() != 1 {
10444                continue;
10445            }
10446            let envelope = arguments[0].clone().into_json()?;
10447            let Some(envelope) = envelope.as_object() else {
10448                continue;
10449            };
10450            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
10451            {
10452                continue;
10453            }
10454            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10455                continue;
10456            };
10457            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10458            else {
10459                continue;
10460            };
10461            let cursor = message_stream_cursors
10462                .entry(stream_name.to_string())
10463                .or_insert(0);
10464            *cursor = (*cursor).max(through_position);
10465        }
10466        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
10467        let cancel_requested = history.iter().any(|event| {
10468            matches!(
10469                event.event_type.as_str(),
10470                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
10471            )
10472        });
10473        let cancellation_clock = cancellation_history
10474            .request
10475            .as_ref()
10476            .and_then(|request| request.context.as_ref())
10477            .map(|_| {
10478                cancellation_replay_clock::ReplayClock::new(
10479                    &history,
10480                    &recorded_commands,
10481                    cancellation_history.delivery_index,
10482                )
10483            })
10484            .or_else(|| {
10485                scope_delivery.as_ref().map(|_| {
10486                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
10487                })
10488            });
10489        Ok(Self {
10490            workflow_command_identity: String::new(),
10491            workflow_stream_command_counter: 0,
10492            workflow_id,
10493            run_id,
10494            task_queue,
10495            payload_codec,
10496            history_events: Arc::new(history),
10497            history_budget: WorkflowHistoryBudget {
10498                event_count,
10499                ..WorkflowHistoryBudget::default()
10500            },
10501            cancel_requested,
10502            cancellation_history,
10503            cancellation_consumed: false,
10504            cancellation_clock,
10505            cancellation_shield_depth: 0,
10506            cancellation_delivery_enabled: false,
10507            cancellation_delivery_intent: None,
10508            cancellation_delivery_command_count: 0,
10509            allow_cancellation_scope_authoring,
10510            cancellation_scope_opening: None,
10511            cancellation_scope_memberships: scopes.memberships,
10512            scope_delivery,
10513            resume_signal,
10514            recorded_commands,
10515            selection_markers,
10516            selection_marker_cursor: 0,
10517            cancelled_selection_members,
10518            recorded_continue_as_new_sequence,
10519            continue_as_new_consumed: false,
10520            command_cursor: 0,
10521            condition_wait_occurrence_counter: 0,
10522            matched_recorded_pending: false,
10523            version_markers: HashMap::new(),
10524            commands: Vec::new(),
10525            local_activity_requests: Vec::new(),
10526            message_stream_messages: HashMap::new(),
10527            message_stream_cursors,
10528            message_stream_waits: HashMap::new(),
10529        })
10530    }
10531}
10532
10533enum MessageStreamDelivery {
10534    Message(MessageStreamMessage),
10535    Cursor {
10536        stream_name: String,
10537        through_position: u64,
10538    },
10539}
10540
10541fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
10542    if arguments.len() != 1 {
10543        return Ok(None);
10544    }
10545    let envelope = arguments
10546        .into_iter()
10547        .next()
10548        .expect("one argument was checked");
10549    let Some(envelope) = envelope.as_object() else {
10550        return Ok(None);
10551    };
10552    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10553        return Ok(None);
10554    };
10555    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
10556        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10557        else {
10558            return Ok(None);
10559        };
10560        return Ok(Some(MessageStreamDelivery::Cursor {
10561            stream_name: stream_name.to_string(),
10562            through_position,
10563        }));
10564    }
10565    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
10566        return Ok(None);
10567    }
10568    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
10569        return Ok(None);
10570    };
10571    let Some(position) = envelope
10572        .get("position")
10573        .and_then(Value::as_u64)
10574        .filter(|value| *value > 0)
10575    else {
10576        return Ok(None);
10577    };
10578    let Some(payload_envelope) = envelope.get("payload_envelope") else {
10579        return Ok(None);
10580    };
10581    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
10582    else {
10583        return Ok(None);
10584    };
10585    let decoded = decode_avro_value(&payload_envelope)?;
10586    let AvroValue::Array(values) = decoded else {
10587        return Ok(None);
10588    };
10589    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
10590        stream_name: stream_name.to_string(),
10591        message_id: message_id.to_string(),
10592        position,
10593        arguments: values,
10594    })))
10595}
10596
10597#[derive(Clone, Debug)]
10598enum RecordedCommand {
10599    CancellationScope {
10600        sequence: u64,
10601        scope_id: String,
10602        parent_scope_id: String,
10603        shield_parent: bool,
10604    },
10605    CancellationGroup {
10606        sequence: u64,
10607        span: u64,
10608        original: Vec<RecordedCommand>,
10609    },
10610    CancellationBoundary {
10611        sequence: u64,
10612        call_kind: CancellationCallKind,
10613        original: Option<Box<RecordedCommand>>,
10614    },
10615    Activity {
10616        sequence: u64,
10617        activity_type: Option<String>,
10618        cancellation_policy: String,
10619        options: Option<RecordedActivityOptions>,
10620        outcome: Option<ActivityOutcome>,
10621        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10622    },
10623    Timer {
10624        sequence: u64,
10625        delay_seconds: u64,
10626        fired: bool,
10627        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10628    },
10629    ChildWorkflow {
10630        sequence: u64,
10631        workflow_type: Option<String>,
10632        policies: RecordedChildPolicies,
10633        outcome: Option<ChildWorkflowOutcome>,
10634        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10635    },
10636    SignalWait {
10637        sequence: u64,
10638        signal_name: String,
10639        value: Option<Vec<AvroValue>>,
10640        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10641    },
10642    ConditionWait {
10643        sequence: u64,
10644        occurrence_id: String,
10645        condition_key: Option<String>,
10646        predicate_identity: String,
10647        timeout_seconds: Option<u64>,
10648        result: Option<ConditionWaitResult>,
10649        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10650    },
10651    SearchAttributes {
10652        sequence: u64,
10653        attributes: Value,
10654        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
10655    },
10656    SideEffect {
10657        sequence: u64,
10658        value: AvroValue,
10659    },
10660    VersionMarker {
10661        sequence: u64,
10662        change_id: String,
10663        version: i32,
10664    },
10665    Memo {
10666        sequence: u64,
10667        entries: AvroValue,
10668    },
10669}
10670
10671#[derive(Clone, Debug, PartialEq, Eq)]
10672struct SelectionMarker {
10673    selection_group_id: String,
10674    selection_group_base_sequence: u64,
10675    selection_group_size: usize,
10676    member_key: SelectionKey,
10677    member_index: usize,
10678    member_base_sequence: u64,
10679    member_size: usize,
10680    operation_kind: String,
10681    operation_identity: String,
10682    outcome: String,
10683    resolution_event_id: String,
10684    resolution_event_type: String,
10685}
10686
10687#[derive(Clone, Debug, PartialEq, Eq)]
10688struct SelectionCancellation {
10689    selection_group_id: String,
10690    member_key: SelectionKey,
10691    member_index: usize,
10692    member_base_sequence: u64,
10693    member_size: usize,
10694    operation_kind: String,
10695    operation_identity: String,
10696}
10697
10698fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
10699    let mut markers: Vec<SelectionMarker> = Vec::new();
10700    for event in events
10701        .iter()
10702        .filter(|event| event.event_type == "SelectionResolved")
10703    {
10704        let payload = &event.payload;
10705        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
10706        let group_size = required_selection_usize(payload, "selection_group_size")?;
10707        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
10708        let member_size = required_selection_usize(payload, "member_size")?;
10709        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
10710        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
10711            invalid_recorded_history(
10712                "selection_marker_invalid",
10713                base_sequence,
10714                "non-empty selection_group_id",
10715                &payload.to_string(),
10716                "selection winner history is missing its durable group identity",
10717            )
10718        })?;
10719        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
10720        if group_id != expected_group_id {
10721            return Err(invalid_recorded_history(
10722                "selection_marker_invalid",
10723                base_sequence,
10724                &expected_group_id,
10725                &group_id,
10726                "selection winner history contains an incompatible group identity",
10727            ));
10728        }
10729        let group_end = base_sequence
10730            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
10731            .unwrap_or(u64::MAX);
10732        let member_end = member_base_sequence
10733            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
10734            .unwrap_or(u64::MAX);
10735        if member_index >= group_size
10736            || member_base_sequence < base_sequence
10737            || member_end > group_end
10738        {
10739            return Err(invalid_recorded_history(
10740                "selection_marker_invalid",
10741                base_sequence,
10742                "winner member within selection group bounds",
10743                &payload.to_string(),
10744                "selection winner history contains an invalid member range",
10745            ));
10746        }
10747        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
10748            invalid_recorded_history(
10749                "selection_marker_invalid",
10750                base_sequence,
10751                "selection operation kind",
10752                &payload.to_string(),
10753                "selection winner history is missing its operation kind",
10754            )
10755        })?;
10756        if !matches!(
10757            operation_kind.as_str(),
10758            "activity" | "child" | "timer" | "signal" | "condition" | "group"
10759        ) {
10760            return Err(invalid_recorded_history(
10761                "selection_marker_invalid",
10762                base_sequence,
10763                "activity, child, timer, signal, condition, or group",
10764                &operation_kind,
10765                "selection winner history contains an unsupported operation kind",
10766            ));
10767        }
10768        let operation_identity =
10769            payload_string(payload, "operation_identity").ok_or_else(|| {
10770                invalid_recorded_history(
10771                    "selection_marker_invalid",
10772                    base_sequence,
10773                    "non-empty operation identity",
10774                    &payload.to_string(),
10775                    "selection winner history is missing its durable operation identity",
10776                )
10777            })?;
10778        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
10779            invalid_recorded_history(
10780                "selection_marker_invalid",
10781                base_sequence,
10782                "completed or failed selection outcome",
10783                &payload.to_string(),
10784                "selection winner history is missing its outcome",
10785            )
10786        })?;
10787        if !matches!(outcome.as_str(), "completed" | "failed") {
10788            return Err(invalid_recorded_history(
10789                "selection_marker_invalid",
10790                base_sequence,
10791                "completed or failed selection outcome",
10792                &outcome,
10793                "selection winner history contains an unsupported outcome",
10794            ));
10795        }
10796        let marker = SelectionMarker {
10797            selection_group_id: group_id,
10798            selection_group_base_sequence: base_sequence,
10799            selection_group_size: group_size,
10800            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
10801            member_index,
10802            member_base_sequence,
10803            member_size,
10804            operation_kind,
10805            operation_identity,
10806            outcome,
10807            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
10808                || {
10809                    invalid_recorded_history(
10810                        "selection_marker_invalid",
10811                        base_sequence,
10812                        "durable resolution_event_id",
10813                        &payload.to_string(),
10814                        "selection winner history is missing its terminal event identity",
10815                    )
10816                },
10817            )?,
10818            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
10819                || {
10820                    invalid_recorded_history(
10821                        "selection_marker_invalid",
10822                        base_sequence,
10823                        "durable resolution_event_type",
10824                        &payload.to_string(),
10825                        "selection winner history is missing its terminal event type",
10826                    )
10827                },
10828            )?,
10829        };
10830        if let Some(existing) = markers
10831            .iter()
10832            .find(|existing| existing.selection_group_id == marker.selection_group_id)
10833        {
10834            if existing != &marker {
10835                return Err(invalid_recorded_history(
10836                    "selection_marker_conflict",
10837                    base_sequence,
10838                    &format!("one winner for {}", marker.selection_group_id),
10839                    &payload.to_string(),
10840                    "selection history records conflicting winners for one durable group",
10841                ));
10842            }
10843            continue;
10844        }
10845        markers.push(marker);
10846    }
10847    Ok(markers)
10848}
10849
10850fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
10851    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
10852    for event in events
10853        .iter()
10854        .filter(|event| event.event_type == "SelectionOperationCancelled")
10855    {
10856        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
10857            invalid_recorded_history(
10858                "selection_cancellation_invalid",
10859                0,
10860                "non-empty selection_group_id",
10861                &event.payload.to_string(),
10862                "selection cancellation history is missing its group identity",
10863            )
10864        })?;
10865        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
10866        let marker = SelectionCancellation {
10867            selection_group_id: group_id,
10868            member_key: selection_key_from_value(
10869                event.payload.get("member_key"),
10870                member_base_sequence,
10871            )?,
10872            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
10873            member_base_sequence,
10874            member_size: required_selection_usize(&event.payload, "member_size")?,
10875            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
10876                invalid_recorded_history(
10877                    "selection_cancellation_invalid",
10878                    member_base_sequence,
10879                    "selection operation kind",
10880                    &event.payload.to_string(),
10881                    "selection cancellation is missing its operation kind",
10882                )
10883            })?,
10884            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
10885                || {
10886                    invalid_recorded_history(
10887                        "selection_cancellation_invalid",
10888                        member_base_sequence,
10889                        "selection operation identity",
10890                        &event.payload.to_string(),
10891                        "selection cancellation is missing its operation identity",
10892                    )
10893                },
10894            )?,
10895        };
10896        if let Some(existing) = cancelled.iter().find(|recorded| {
10897            recorded.selection_group_id == marker.selection_group_id
10898                && recorded.member_base_sequence == marker.member_base_sequence
10899        }) {
10900            if existing != &marker {
10901                return Err(invalid_recorded_history(
10902                    "selection_cancellation_conflict",
10903                    member_base_sequence,
10904                    "one stable SelectionOperationCancelled marker",
10905                    &event.payload.to_string(),
10906                    "selection cancellation history contains conflicting member metadata",
10907                ));
10908            }
10909        } else {
10910            cancelled.push(marker);
10911        }
10912    }
10913    Ok(cancelled)
10914}
10915
10916fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
10917    payload
10918        .get(field)
10919        .and_then(value_as_u64)
10920        .filter(|value| *value > 0)
10921        .ok_or_else(|| {
10922            invalid_recorded_history(
10923                "selection_marker_invalid",
10924                0,
10925                &format!("positive integer {field}"),
10926                &payload.to_string(),
10927                "selection history contains invalid durable identity metadata",
10928            )
10929        })
10930}
10931
10932fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
10933    required_selection_usize_allow_zero(payload, field).and_then(|value| {
10934        if value > 0 {
10935            Ok(value)
10936        } else {
10937            Err(invalid_recorded_history(
10938                "selection_marker_invalid",
10939                0,
10940                &format!("positive integer {field}"),
10941                &payload.to_string(),
10942                "selection history contains invalid durable identity metadata",
10943            ))
10944        }
10945    })
10946}
10947
10948fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
10949    payload
10950        .get(field)
10951        .and_then(value_as_u64)
10952        .and_then(|value| usize::try_from(value).ok())
10953        .ok_or_else(|| {
10954            invalid_recorded_history(
10955                "selection_marker_invalid",
10956                0,
10957                &format!("non-negative integer {field}"),
10958                &payload.to_string(),
10959                "selection history contains invalid durable identity metadata",
10960            )
10961        })
10962}
10963
10964#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
10965struct RecordedActivityOptions {
10966    task_queue: RecordedSnapshotValue<Option<String>>,
10967    execution_mode: RecordedSnapshotValue<Option<String>>,
10968    retry_policy: ActivityRetrySnapshot,
10969    worker_session: Option<Value>,
10970}
10971
10972#[derive(Clone, Debug)]
10973struct RecordedChildPolicies {
10974    parent_close_policy: String,
10975    cancellation_policy: String,
10976}
10977
10978fn recorded_activity_cancellation_policy(
10979    events: &[&HistoryEvent],
10980    sequence: u64,
10981) -> Result<String> {
10982    let mut policy: Option<String> = None;
10983    for event in events.iter().filter(|event| {
10984        matches!(
10985            event.event_type.as_str(),
10986            "ActivityScheduled"
10987                | "ActivityStarted"
10988                | "ActivityCompleted"
10989                | "ActivityFailed"
10990                | "ActivityTimedOut"
10991                | "ActivityCancelled"
10992        )
10993    }) {
10994        for source in [Some(&event.payload), event.payload.get("activity")]
10995            .into_iter()
10996            .flatten()
10997        {
10998            let Some(value) = source.get("cancellation_policy") else {
10999                continue;
11000            };
11001            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11002                value.as_str()
11003            else {
11004                return Err(invalid_recorded_history(
11005                    "invalid_activity_cancellation_policy_history",
11006                    sequence,
11007                    "supported Activity cancellation policy",
11008                    &value.to_string(),
11009                    "Activity history contains an invalid cancellation policy",
11010                ));
11011            };
11012            if let Some(previous) = policy.as_deref() {
11013                if previous != incoming {
11014                    return Err(invalid_recorded_history(
11015                        "activity_cancellation_policy_history_conflict",
11016                        sequence,
11017                        previous,
11018                        incoming,
11019                        "Activity cancellation policy changed between history events",
11020                    ));
11021                }
11022            }
11023            policy = Some(incoming.to_string());
11024        }
11025        policy.get_or_insert_with(|| "try_cancel".to_string());
11026    }
11027    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11028}
11029
11030fn recorded_child_policy_value<'a>(
11031    payload: &'a Value,
11032    field: &str,
11033    sequence: u64,
11034) -> Result<Option<&'a str>> {
11035    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11036        return Ok(None);
11037    };
11038    let valid = match (field, value.as_str()) {
11039        (
11040            "parent_close_policy",
11041            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11042        ) => true,
11043        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11044            true
11045        }
11046        _ => false,
11047    };
11048    if !valid {
11049        return Err(invalid_recorded_history(
11050            "invalid_child_workflow_policy_history",
11051            sequence,
11052            "supported child workflow policy",
11053            &value.to_string(),
11054            "child workflow history contains an invalid policy",
11055        ));
11056    }
11057    Ok(value.as_str())
11058}
11059
11060fn recorded_child_policies(
11061    events: &[&HistoryEvent],
11062    scheduled: &HistoryEvent,
11063    sequence: u64,
11064) -> Result<RecordedChildPolicies> {
11065    let parent_close_policy =
11066        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11067            .unwrap_or("abandon")
11068            .to_string();
11069    let cancellation_policy =
11070        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11071            .unwrap_or("abandon")
11072            .to_string();
11073    for event in events {
11074        for (field, expected) in [
11075            ("parent_close_policy", parent_close_policy.as_str()),
11076            ("cancellation_policy", cancellation_policy.as_str()),
11077        ] {
11078            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11079                if actual != expected {
11080                    return Err(invalid_recorded_history(
11081                        "child_workflow_policy_history_conflict",
11082                        sequence,
11083                        expected,
11084                        actual,
11085                        "child workflow policy changed between history events",
11086                    ));
11087                }
11088            }
11089        }
11090    }
11091    Ok(RecordedChildPolicies {
11092        parent_close_policy,
11093        cancellation_policy,
11094    })
11095}
11096
11097fn ensure_child_policies_match(
11098    sequence: u64,
11099    recorded: &RecordedChildPolicies,
11100    current: &ChildWorkflowOptions,
11101) -> Result<()> {
11102    for (field, expected, actual) in [
11103        (
11104            "parent_close_policy",
11105            recorded.parent_close_policy.as_str(),
11106            current.parent_close_policy.as_str(),
11107        ),
11108        (
11109            "cancellation_policy",
11110            recorded.cancellation_policy.as_str(),
11111            current.cancellation_policy.as_str(),
11112        ),
11113    ] {
11114        if expected != actual {
11115            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11116                "child_workflow_policy_changed",
11117                Some(sequence),
11118                Some(expected.to_string()),
11119                Some(actual.to_string()),
11120                format!("child workflow {field} changed during replay"),
11121            )));
11122        }
11123    }
11124    Ok(())
11125}
11126
11127#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11128enum RecordedSnapshotValue<T> {
11129    /// Older history did not persist this field, so it cannot constrain replay.
11130    Unknown,
11131    Known(T),
11132}
11133
11134impl<T: PartialEq> RecordedSnapshotValue<T> {
11135    fn matches_current(&self, current: &Self) -> bool {
11136        match self {
11137            Self::Unknown => true,
11138            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11139        }
11140    }
11141}
11142
11143#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11144struct ActivityRetrySnapshot {
11145    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11146    max_attempts: RecordedSnapshotValue<Option<u64>>,
11147    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11148    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11149    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11150    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11151    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11152    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11153}
11154
11155impl ActivityRetrySnapshot {
11156    fn matches_current(&self, current: &Self) -> bool {
11157        self.snapshot_version
11158            .matches_current(&current.snapshot_version)
11159            && self.max_attempts.matches_current(&current.max_attempts)
11160            && self
11161                .backoff_seconds
11162                .matches_current(&current.backoff_seconds)
11163            && self
11164                .start_to_close_timeout
11165                .matches_current(&current.start_to_close_timeout)
11166            && self
11167                .schedule_to_start_timeout
11168                .matches_current(&current.schedule_to_start_timeout)
11169            && self
11170                .schedule_to_close_timeout
11171                .matches_current(&current.schedule_to_close_timeout)
11172            && self
11173                .heartbeat_timeout
11174                .matches_current(&current.heartbeat_timeout)
11175            && self
11176                .non_retryable_error_types
11177                .matches_current(&current.non_retryable_error_types)
11178    }
11179}
11180
11181fn recorded_optional_u64(
11182    object: Option<&serde_json::Map<String, Value>>,
11183    field: &str,
11184) -> RecordedSnapshotValue<Option<u64>> {
11185    match object.and_then(|object| object.get(field)) {
11186        None => RecordedSnapshotValue::Unknown,
11187        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11188        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11189    }
11190}
11191
11192fn recorded_optional_string(
11193    object: &serde_json::Map<String, Value>,
11194    field: &str,
11195) -> RecordedSnapshotValue<Option<String>> {
11196    match object.get(field) {
11197        None => RecordedSnapshotValue::Unknown,
11198        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11199        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11200    }
11201}
11202
11203fn recorded_activity_execution_mode(
11204    events: &[&HistoryEvent],
11205    sequence: u64,
11206) -> Result<RecordedSnapshotValue<Option<String>>> {
11207    let mut recorded = RecordedSnapshotValue::Unknown;
11208    for event in events {
11209        for object in [
11210            event.payload.as_object(),
11211            event.payload.get("activity").and_then(Value::as_object),
11212        ]
11213        .into_iter()
11214        .flatten()
11215        {
11216            let mode = match object.get("execution_mode") {
11217                None => None,
11218                Some(Value::Null) => Some(None),
11219                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11220                Some(_) => {
11221                    return Err(invalid_recorded_history(
11222                        "activity_execution_mode_invalid",
11223                        sequence,
11224                        "null or a non-empty execution mode",
11225                        "invalid execution_mode",
11226                        "activity history contains an invalid execution mode",
11227                    ))
11228                }
11229            };
11230            let legacy_mode = match object.get("local_activity") {
11231                None => None,
11232                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11233                Some(_) => {
11234                    return Err(invalid_recorded_history(
11235                        "activity_execution_mode_invalid",
11236                        sequence,
11237                        "boolean local_activity",
11238                        "invalid local_activity",
11239                        "activity history contains an invalid local-activity marker",
11240                    ))
11241                }
11242            };
11243            for mode in [mode, legacy_mode].into_iter().flatten() {
11244                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
11245                {
11246                    return Err(invalid_recorded_history(
11247                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
11248                        "activity lifecycle events at one workflow sequence disagree on execution mode",
11249                    ));
11250                }
11251                recorded = RecordedSnapshotValue::Known(mode);
11252            }
11253        }
11254    }
11255    Ok(recorded)
11256}
11257
11258fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
11259    let policy = policy.and_then(Value::as_object);
11260    let backoff_seconds = policy
11261        .and_then(|policy| policy.get("backoff_seconds"))
11262        .and_then(Value::as_array)
11263        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11264        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
11265    let mut non_retryable_error_types = Vec::new();
11266    for error_type in policy
11267        .and_then(|policy| policy.get("non_retryable_error_types"))
11268        .and_then(Value::as_array)
11269        .into_iter()
11270        .flatten()
11271        .filter_map(Value::as_str)
11272        .map(str::trim)
11273        .filter(|error_type| !error_type.is_empty())
11274    {
11275        if !non_retryable_error_types
11276            .iter()
11277            .any(|recorded| recorded == error_type)
11278        {
11279            non_retryable_error_types.push(error_type.to_string());
11280        }
11281    }
11282
11283    ActivityRetrySnapshot {
11284        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
11285        max_attempts: recorded_optional_u64(policy, "max_attempts"),
11286        backoff_seconds,
11287        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
11288        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
11289        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
11290        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
11291        non_retryable_error_types: if policy
11292            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
11293        {
11294            RecordedSnapshotValue::Known(non_retryable_error_types)
11295        } else {
11296            RecordedSnapshotValue::Unknown
11297        },
11298    }
11299}
11300
11301fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
11302    let policy = options.retry_policy.as_ref();
11303    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
11304        Some(Value::Null) => None,
11305        Some(value) => value_as_u64(value),
11306        None => Some(1),
11307    };
11308    let backoff_seconds = policy
11309        .and_then(|policy| policy.get("backoff_seconds"))
11310        .and_then(Value::as_array)
11311        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11312        .unwrap_or_default();
11313    let non_retryable_error_types = policy
11314        .and_then(|policy| policy.get("non_retryable_error_types"))
11315        .and_then(Value::as_array)
11316        .into_iter()
11317        .flatten()
11318        .filter_map(Value::as_str)
11319        .map(str::to_string)
11320        .collect();
11321
11322    ActivityRetrySnapshot {
11323        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
11324        max_attempts: RecordedSnapshotValue::Known(max_attempts),
11325        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
11326        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
11327        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
11328        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
11329        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
11330        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
11331    }
11332}
11333
11334fn activity_options_description(options: &RecordedActivityOptions) -> String {
11335    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
11336}
11337
11338impl RecordedCommand {
11339    fn sequence(&self) -> u64 {
11340        match self {
11341            Self::CancellationGroup { sequence, .. }
11342            | Self::CancellationScope { sequence, .. }
11343            | Self::CancellationBoundary { sequence, .. }
11344            | Self::Activity { sequence, .. }
11345            | Self::Timer { sequence, .. }
11346            | Self::ChildWorkflow { sequence, .. }
11347            | Self::SignalWait { sequence, .. }
11348            | Self::ConditionWait { sequence, .. }
11349            | Self::SearchAttributes { sequence, .. }
11350            | Self::SideEffect { sequence, .. }
11351            | Self::VersionMarker { sequence, .. }
11352            | Self::Memo { sequence, .. } => *sequence,
11353        }
11354    }
11355
11356    fn shape(&self) -> &'static str {
11357        match self {
11358            Self::CancellationScope { .. } => "cancellation scope",
11359            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
11360                "cooperative cancellation"
11361            }
11362            Self::Activity { .. } => "activity",
11363            Self::Timer { .. } => "timer",
11364            Self::ChildWorkflow { .. } => "child workflow",
11365            Self::SignalWait { .. } => "signal wait",
11366            Self::ConditionWait { .. } => "condition wait",
11367            Self::SearchAttributes { .. } => "search-attribute update",
11368            Self::SideEffect { .. } => "side effect",
11369            Self::VersionMarker { .. } => "version marker",
11370            Self::Memo { .. } => "memo upsert",
11371        }
11372    }
11373}
11374
11375fn ensure_version_supported(
11376    change_id: &str,
11377    version: i32,
11378    min_supported: i32,
11379    max_supported: i32,
11380    sequence: u64,
11381) -> Result<()> {
11382    if (min_supported..=max_supported).contains(&version) {
11383        return Ok(());
11384    }
11385    Err(Error::NonDeterministicReplay(ReplayFailure::new(
11386        "version_marker_incompatible_range",
11387        (sequence != 0).then_some(sequence),
11388        Some(format!("{min_supported}..={max_supported}")),
11389        Some(format!("{change_id}:{version}")),
11390        "recorded workflow version is outside the range supported by current code",
11391    )))
11392}
11393
11394#[derive(Clone, Debug)]
11395struct ResumeSignal {
11396    signal_name: String,
11397    arguments: Vec<AvroValue>,
11398}
11399
11400const MAX_PARALLEL_OPERATIONS: usize = 1000;
11401
11402fn parallel_group_prefix(kind: &str) -> &'static str {
11403    match kind {
11404        "activity" => "parallel-activities",
11405        "child" => "parallel-children",
11406        "timer" => "parallel-timers",
11407        _ => "parallel-calls",
11408    }
11409}
11410
11411fn parallel_group_entry(
11412    base_sequence: u64,
11413    size: usize,
11414    index: usize,
11415    kind: &str,
11416) -> ParallelGroupMetadata {
11417    ParallelGroupMetadata {
11418        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
11419        parallel_group_kind: kind.to_string(),
11420        parallel_group_base_sequence: base_sequence,
11421        parallel_group_size: size,
11422        parallel_group_index: index,
11423        parallel_group_mode: None,
11424        selection_member_key: None,
11425        selection_member_index: None,
11426        selection_member_base_sequence: None,
11427        selection_member_size: None,
11428        selection_member_kind: None,
11429    }
11430}
11431
11432struct SelectionMemberMetadata {
11433    key: SelectionKey,
11434    index: usize,
11435    base_sequence: u64,
11436    size: usize,
11437    kind: String,
11438}
11439
11440fn selection_group_entry(
11441    base_sequence: u64,
11442    size: usize,
11443    index: usize,
11444    kind: &str,
11445    member: &SelectionMemberMetadata,
11446) -> ParallelGroupMetadata {
11447    ParallelGroupMetadata {
11448        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
11449        parallel_group_kind: kind.to_string(),
11450        parallel_group_base_sequence: base_sequence,
11451        parallel_group_size: size,
11452        parallel_group_index: index,
11453        parallel_group_mode: Some("select".to_string()),
11454        selection_member_key: Some(member.key.clone()),
11455        selection_member_index: Some(member.index),
11456        selection_member_base_sequence: Some(member.base_sequence),
11457        selection_member_size: Some(member.size),
11458        selection_member_kind: Some(member.kind.clone()),
11459    }
11460}
11461
11462fn apply_parallel_group_path(
11463    command: &mut serde_json::Map<String, Value>,
11464    path: &[ParallelGroupMetadata],
11465) {
11466    let Some(inner) = path.last() else {
11467        return;
11468    };
11469    command.insert(
11470        "parallel_group_id".to_string(),
11471        json!(inner.parallel_group_id),
11472    );
11473    command.insert(
11474        "parallel_group_kind".to_string(),
11475        json!(inner.parallel_group_kind),
11476    );
11477    command.insert(
11478        "parallel_group_base_sequence".to_string(),
11479        json!(inner.parallel_group_base_sequence),
11480    );
11481    command.insert(
11482        "parallel_group_size".to_string(),
11483        json!(inner.parallel_group_size),
11484    );
11485    command.insert(
11486        "parallel_group_index".to_string(),
11487        json!(inner.parallel_group_index),
11488    );
11489    if let Some(mode) = &inner.parallel_group_mode {
11490        command.insert("parallel_group_mode".to_string(), json!(mode));
11491    }
11492    if let Some(key) = &inner.selection_member_key {
11493        command.insert("selection_member_key".to_string(), json!(key));
11494    }
11495    if let Some(index) = inner.selection_member_index {
11496        command.insert("selection_member_index".to_string(), json!(index));
11497    }
11498    if let Some(base_sequence) = inner.selection_member_base_sequence {
11499        command.insert(
11500            "selection_member_base_sequence".to_string(),
11501            json!(base_sequence),
11502        );
11503    }
11504    if let Some(size) = inner.selection_member_size {
11505        command.insert("selection_member_size".to_string(), json!(size));
11506    }
11507    if let Some(kind) = &inner.selection_member_kind {
11508        command.insert("selection_member_kind".to_string(), json!(kind));
11509    }
11510    command.insert("parallel_group_path".to_string(), json!(path));
11511}
11512
11513fn ensure_parallel_path_matches(
11514    sequence: u64,
11515    recorded: Option<&[ParallelGroupMetadata]>,
11516    expected: &[ParallelGroupMetadata],
11517) -> Result<()> {
11518    match (recorded, expected.is_empty()) {
11519        (None, true) => Ok(()),
11520        (Some(recorded), false) if recorded == expected => Ok(()),
11521        (None, false) => Err(invalid_recorded_history(
11522            "parallel_group_metadata_missing",
11523            sequence,
11524            &serde_json::to_string(expected).unwrap_or_default(),
11525            "<missing>",
11526            "recorded parallel member is missing its durable group path",
11527        )),
11528        (Some(recorded), true) => Err(invalid_recorded_history(
11529            "parallel_group_shape_mismatch",
11530            sequence,
11531            "sequential command",
11532            &serde_json::to_string(recorded).unwrap_or_default(),
11533            "recorded command belonged to a parallel group but current code schedules it sequentially",
11534        )),
11535        (Some(recorded), false) => Err(invalid_recorded_history(
11536            "parallel_group_shape_mismatch",
11537            sequence,
11538            &serde_json::to_string(recorded).unwrap_or_default(),
11539            &serde_json::to_string(expected).unwrap_or_default(),
11540            "recorded parallel-group identity or path changed during replay",
11541        )),
11542    }
11543}
11544
11545#[derive(Clone, Debug)]
11546enum ParallelShape {
11547    Leaf,
11548    Group(Vec<ParallelShape>),
11549}
11550
11551struct ParallelDescriptor {
11552    operation: ParallelOperation,
11553    offset: usize,
11554    member_path: Vec<usize>,
11555    group_path: Vec<ParallelGroupMetadata>,
11556}
11557
11558fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
11559    operations
11560        .iter()
11561        .map(|operation| match operation {
11562            ParallelOperation::Group(children) => parallel_leaf_count(children),
11563            _ => 1,
11564        })
11565        .sum()
11566}
11567
11568fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
11569    match operation {
11570        ParallelOperation::Activity { .. } => Some("activity"),
11571        ParallelOperation::ChildWorkflow { .. } => Some("child"),
11572        ParallelOperation::Timer(_) => Some("timer"),
11573        ParallelOperation::Signal(_) => Some("signal"),
11574        ParallelOperation::Condition { .. } => Some("condition"),
11575        ParallelOperation::Group(children) => parallel_group_kind(children),
11576    }
11577}
11578
11579fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
11580    let mut kind = None;
11581    for operation in operations {
11582        let Some(operation_kind) = parallel_operation_kind(operation) else {
11583            continue;
11584        };
11585        match kind {
11586            None => kind = Some(operation_kind),
11587            Some(current) if current == operation_kind => {}
11588            Some(_) => return Some("mixed"),
11589        }
11590    }
11591    kind
11592}
11593
11594fn validate_parallel_operations(
11595    operations: &[ParallelOperation],
11596    member_path: &mut Vec<usize>,
11597    root: bool,
11598) -> Result<()> {
11599    let leaves = parallel_leaf_count(operations);
11600    if leaves > MAX_PARALLEL_OPERATIONS {
11601        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11602            reason: "fan_out_limit_exceeded",
11603            member_path: member_path.clone(),
11604            message: format!(
11605                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
11606            ),
11607        }));
11608    }
11609    if !root && operations.is_empty() {
11610        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11611            reason: "nested_group_empty",
11612            member_path: member_path.clone(),
11613            message: "a nested group must contain at least one durable leaf".to_string(),
11614        }));
11615    }
11616
11617    for (index, operation) in operations.iter().enumerate() {
11618        member_path.push(index);
11619        match operation {
11620            ParallelOperation::Activity {
11621                options, arguments, ..
11622            } => {
11623                options
11624                    .validate()
11625                    .map_err(|error| Error::InvalidActivityOptions(error))?;
11626                if let Err(error) = arguments {
11627                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11628                        reason: "arguments_invalid",
11629                        member_path: member_path.clone(),
11630                        message: error.to_string(),
11631                    }));
11632                }
11633            }
11634            ParallelOperation::ChildWorkflow {
11635                options, arguments, ..
11636            } => {
11637                validate_parallel_child_options(options)?;
11638                if let Err(error) = arguments {
11639                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11640                        reason: "arguments_invalid",
11641                        member_path: member_path.clone(),
11642                        message: error.to_string(),
11643                    }));
11644                }
11645            }
11646            ParallelOperation::Timer(duration)
11647                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
11648            {
11649                return Err(Error::TimerDurationOverflow);
11650            }
11651            ParallelOperation::Timer(_) => {}
11652            ParallelOperation::Signal(signal_name) => {
11653                validate_user_signal_name(signal_name)?;
11654                if signal_name.trim().is_empty() {
11655                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11656                        reason: "signal_name_empty",
11657                        member_path: member_path.clone(),
11658                        message: "signal wait name must not be empty".to_string(),
11659                    }));
11660                }
11661            }
11662            ParallelOperation::Condition { options, .. } => {
11663                options.validate()?;
11664            }
11665            ParallelOperation::Group(children) => {
11666                validate_parallel_operations(children, member_path, false)?;
11667            }
11668        }
11669        member_path.pop();
11670    }
11671    Ok(())
11672}
11673
11674fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
11675    if options.task_queue.trim().is_empty() {
11676        return Err(Error::InvalidChildWorkflowOptions(
11677            "task_queue must not be empty".to_string(),
11678        ));
11679    }
11680    for (name, value) in [
11681        (
11682            "execution_timeout_seconds",
11683            options.execution_timeout_seconds,
11684        ),
11685        ("run_timeout_seconds", options.run_timeout_seconds),
11686    ] {
11687        if value == Some(0) {
11688            return Err(Error::InvalidChildWorkflowOptions(format!(
11689                "{name} must be at least 1"
11690            )));
11691        }
11692    }
11693    if options
11694        .retry_policy
11695        .as_ref()
11696        .is_some_and(|policy| policy.max_attempts == Some(0))
11697    {
11698        return Err(Error::InvalidChildWorkflowOptions(
11699            "retry_policy.max_attempts must be at least 1".to_string(),
11700        ));
11701    }
11702    Ok(())
11703}
11704
11705fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
11706    ParallelShape::Group(
11707        operations
11708            .iter()
11709            .map(|operation| match operation {
11710                ParallelOperation::Group(children) => parallel_shape(children),
11711                _ => ParallelShape::Leaf,
11712            })
11713            .collect(),
11714    )
11715}
11716
11717fn parallel_descriptors(
11718    operations: Vec<ParallelOperation>,
11719    base_sequence: u64,
11720) -> Result<Vec<ParallelDescriptor>> {
11721    let size = parallel_leaf_count(&operations);
11722    let kind = parallel_group_kind(&operations).unwrap_or("activity");
11723    let mut descriptors = Vec::with_capacity(size);
11724    let mut cursor = 0;
11725
11726    for (index, operation) in operations.into_iter().enumerate() {
11727        match operation {
11728            ParallelOperation::Group(children) => {
11729                let child_base = base_sequence
11730                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
11731                    .ok_or(Error::TimerDurationOverflow)?;
11732                for mut descriptor in parallel_descriptors(children, child_base)? {
11733                    let outer_index = cursor + descriptor.offset;
11734                    descriptor.group_path.insert(
11735                        0,
11736                        parallel_group_entry(base_sequence, size, outer_index, kind),
11737                    );
11738                    descriptor.member_path.insert(0, index);
11739                    descriptor.offset = outer_index;
11740                    descriptors.push(descriptor);
11741                }
11742                cursor = descriptors.len();
11743            }
11744            operation => {
11745                descriptors.push(ParallelDescriptor {
11746                    operation,
11747                    offset: cursor,
11748                    member_path: vec![index],
11749                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
11750                });
11751                cursor += 1;
11752            }
11753        }
11754    }
11755    Ok(descriptors)
11756}
11757
11758enum ParallelLeafCall {
11759    Activity(ActivityCall),
11760    ChildWorkflow(ChildWorkflowCall),
11761    Timer(TimerCall),
11762    Signal(SignalCall),
11763    Condition(ConditionWaitCall),
11764}
11765
11766fn parallel_leaf_call(
11767    ctx: &WorkflowContext,
11768    operation: ParallelOperation,
11769    parallel_group_path: Vec<ParallelGroupMetadata>,
11770) -> ParallelLeafCall {
11771    match operation {
11772        ParallelOperation::Activity {
11773            activity_type,
11774            options,
11775            arguments,
11776        } => ParallelLeafCall::Activity(ActivityCall {
11777            ctx: ctx.clone(),
11778            activity_type,
11779            options,
11780            worker_session: None,
11781            args: Some(arguments),
11782            scheduled: false,
11783            local: false,
11784            local_result: None,
11785            parallel_group_path,
11786        }),
11787        ParallelOperation::ChildWorkflow {
11788            workflow_type,
11789            options,
11790            arguments,
11791        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
11792            ctx: ctx.clone(),
11793            workflow_type,
11794            options,
11795            args: Some(arguments),
11796            scheduled: false,
11797            matched_pending: false,
11798            parallel_group_path,
11799        }),
11800        ParallelOperation::Timer(duration) => {
11801            let delay_seconds = duration
11802                .as_secs()
11803                .checked_add(u64::from(duration.subsec_nanos() > 0));
11804            ParallelLeafCall::Timer(TimerCall {
11805                ctx: ctx.clone(),
11806                delay_seconds,
11807                scheduled: false,
11808                matched_pending: false,
11809                parallel_group_path,
11810            })
11811        }
11812        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
11813            ctx: ctx.clone(),
11814            signal_name,
11815            runtime_reserved_allowed: false,
11816            opened_wait: false,
11817            matched_pending: false,
11818            parallel_group_path,
11819        }),
11820        ParallelOperation::Condition { options, predicate } => {
11821            ParallelLeafCall::Condition(ConditionWaitCall {
11822                ctx: ctx.clone(),
11823                options,
11824                predicate,
11825                occurrence_id: None,
11826                opened_wait: false,
11827                parallel_group_path,
11828            })
11829        }
11830        ParallelOperation::Group(_) => {
11831            unreachable!("parallel descriptors contain only durable leaves")
11832        }
11833    }
11834}
11835
11836impl ParallelLeafCall {
11837    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
11838        match self {
11839            Self::Activity(call) => Pin::new(call)
11840                .poll_avro_value(cx)
11841                .map_ok(ParallelAvroResult::Activity),
11842            Self::ChildWorkflow(call) => Pin::new(call)
11843                .poll_avro_value(cx)
11844                .map_ok(ParallelAvroResult::ChildWorkflow),
11845            Self::Timer(call) => Pin::new(call)
11846                .poll(cx)
11847                .map_ok(|()| ParallelAvroResult::Timer),
11848            Self::Signal(call) => Pin::new(call)
11849                .poll_avro_value(cx)
11850                .map_ok(ParallelAvroResult::Signal),
11851            Self::Condition(call) => Pin::new(call)
11852                .poll(cx)
11853                .map_ok(ParallelAvroResult::Condition),
11854        }
11855    }
11856}
11857
11858struct ParallelLeaf {
11859    call: ParallelLeafCall,
11860    sequence: u64,
11861    member_path: Vec<usize>,
11862    group_path: Vec<ParallelGroupMetadata>,
11863    result: Option<ParallelAvroResult>,
11864}
11865
11866/// Future returned by [`WorkflowContext::parallel`].
11867pub struct ParallelCall {
11868    ctx: WorkflowContext,
11869    operations: Option<Vec<ParallelOperation>>,
11870    shape: Option<ParallelShape>,
11871    leaves: Vec<ParallelLeaf>,
11872    pending_scope_delivery: bool,
11873    worker_session: Option<WorkerSessionOptions>,
11874}
11875
11876impl ParallelCall {
11877    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
11878        Self {
11879            ctx,
11880            operations: Some(operations),
11881            shape: None,
11882            leaves: Vec::new(),
11883            pending_scope_delivery: false,
11884            worker_session: None,
11885        }
11886    }
11887
11888    fn initialize(&mut self) -> Result<()> {
11889        if let Some(session) = &self.worker_session {
11890            session.to_wire()?;
11891        }
11892        let operations = self.operations.take().unwrap_or_default();
11893        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
11894        self.shape = Some(parallel_shape(&operations));
11895        if operations.is_empty() {
11896            return Ok(());
11897        }
11898
11899        let base_sequence = {
11900            let state = self
11901                .ctx
11902                .state
11903                .lock()
11904                .map_err(|_| Error::WorkflowStatePoisoned)?;
11905            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
11906                recorded.sequence()
11907            } else {
11908                let last = state
11909                    .recorded_commands
11910                    .last()
11911                    .map(RecordedCommand::sequence)
11912                    .unwrap_or(0);
11913                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
11914                    .and_then(|sequence| sequence.checked_add(1))
11915                    .ok_or_else(|| {
11916                        Error::InvalidParallelGroup(ParallelGroupError {
11917                            reason: "sequence_overflow",
11918                            member_path: Vec::new(),
11919                            message: "parallel group sequence identity overflowed u64".to_string(),
11920                        })
11921                    })?
11922            }
11923        };
11924
11925        let descriptors = parallel_descriptors(operations, base_sequence)?;
11926        {
11927            let mut state = self
11928                .ctx
11929                .state
11930                .lock()
11931                .map_err(|_| Error::WorkflowStatePoisoned)?;
11932            let cursor = state.command_cursor;
11933            self.ctx.validate_scope_membership(&mut state, cursor)?;
11934            if state.prepare_parallel_scope_cancellation(&descriptors)? {
11935                self.pending_scope_delivery = true;
11936                return Ok(());
11937            }
11938            state.expand_cancellation_group(&descriptors)?;
11939            state.prepare_group_cancellation(&descriptors)?;
11940        }
11941        self.leaves = descriptors
11942            .into_iter()
11943            .map(|descriptor| {
11944                let mut call = parallel_leaf_call(
11945                    &self.ctx,
11946                    descriptor.operation,
11947                    descriptor.group_path.clone(),
11948                );
11949                if let (Some(session), ParallelLeafCall::Activity(activity)) =
11950                    (&self.worker_session, &mut call)
11951                {
11952                    activity.worker_session = Some(session.clone());
11953                }
11954                ParallelLeaf {
11955                    call,
11956                    sequence: base_sequence + descriptor.offset as u64,
11957                    member_path: descriptor.member_path,
11958                    group_path: descriptor.group_path,
11959                    result: None,
11960                }
11961            })
11962            .collect();
11963        Ok(())
11964    }
11965
11966    fn poll_avro_value(
11967        mut self: Pin<&mut Self>,
11968        cx: &mut TaskContext<'_>,
11969    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
11970        if self.operations.is_some() {
11971            if let Err(error) = self.initialize() {
11972                return Poll::Ready(Err(error));
11973            }
11974        }
11975        if self.pending_scope_delivery {
11976            return Poll::Pending;
11977        }
11978        if self.leaves.is_empty() {
11979            return Poll::Ready(Ok(Vec::new()));
11980        }
11981
11982        let mut failures = Vec::new();
11983        let mut pending = false;
11984        for (index, leaf) in self.leaves.iter_mut().enumerate() {
11985            if leaf.result.is_some() {
11986                continue;
11987            }
11988            match leaf.call.poll_avro_value(cx) {
11989                Poll::Ready(Ok(result)) => leaf.result = Some(result),
11990                Poll::Ready(Err(error)) => failures.push((index, error)),
11991                Poll::Pending => pending = true,
11992            }
11993        }
11994
11995        if !failures.is_empty() {
11996            if let Some(position) = failures
11997                .iter()
11998                .position(|(_, error)| workflow_task_integrity_error(error))
11999            {
12000                return Poll::Ready(Err(failures.remove(position).1));
12001            }
12002            if self
12003                .ctx
12004                .state
12005                .lock()
12006                .map_err(|_| Error::WorkflowStatePoisoned)?
12007                .cancellation_delivery_intent
12008                .is_some()
12009            {
12010                return Poll::Pending;
12011            }
12012            if let Some(position) = failures
12013                .iter()
12014                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12015            {
12016                return Poll::Ready(Err(failures.remove(position).1));
12017            }
12018            failures.sort_by_key(|(index, _)| *index);
12019            let (failed_index, cause) = failures.remove(0);
12020            let failed = &self.leaves[failed_index];
12021            let completed = self
12022                .leaves
12023                .iter()
12024                .filter_map(|leaf| {
12025                    leaf.result
12026                        .clone()
12027                        .and_then(|result| result.into_json_result().ok())
12028                        .map(|result| ParallelCompletion {
12029                            member_path: leaf.member_path.clone(),
12030                            result,
12031                        })
12032                })
12033                .collect();
12034            let group_id = failed
12035                .group_path
12036                .first()
12037                .map(|entry| entry.parallel_group_id.clone())
12038                .unwrap_or_default();
12039            let sequences = self
12040                .leaves
12041                .iter()
12042                .map(|leaf| leaf.sequence)
12043                .collect::<Vec<_>>();
12044            self.ctx
12045                .state
12046                .lock()
12047                .map_err(|_| Error::WorkflowStatePoisoned)?
12048                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12049            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12050                group_id,
12051                member_path: failed.member_path.clone(),
12052                group_path: failed.group_path.clone(),
12053                completed,
12054                cause: Box::new(cause),
12055            })));
12056        }
12057        if pending
12058            || self
12059                .ctx
12060                .state
12061                .lock()
12062                .map_err(|_| Error::WorkflowStatePoisoned)?
12063                .cancellation_delivery_intent
12064                .is_some()
12065        {
12066            return Poll::Pending;
12067        }
12068
12069        let mut flat_results = self
12070            .leaves
12071            .iter_mut()
12072            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12073            .collect::<Vec<_>>()
12074            .into_iter();
12075        let results = parallel_results_for_shape(
12076            self.shape.as_ref().expect("initialized parallel shape"),
12077            &mut flat_results,
12078        );
12079        let sequences = self
12080            .leaves
12081            .iter()
12082            .map(|leaf| leaf.sequence)
12083            .collect::<Vec<_>>();
12084        self.ctx
12085            .state
12086            .lock()
12087            .map_err(|_| Error::WorkflowStatePoisoned)?
12088            .advance_cancellation_sequences(&sequences, None);
12089        Poll::Ready(Ok(match results {
12090            ParallelAvroResult::Group(results) => results,
12091            ParallelAvroResult::Activity(_)
12092            | ParallelAvroResult::ChildWorkflow(_)
12093            | ParallelAvroResult::Timer
12094            | ParallelAvroResult::Signal(_)
12095            | ParallelAvroResult::Condition(_) => {
12096                unreachable!("root parallel shape is a group")
12097            }
12098        }))
12099    }
12100}
12101
12102fn parallel_results_for_shape(
12103    shape: &ParallelShape,
12104    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12105) -> ParallelAvroResult {
12106    match shape {
12107        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12108        ParallelShape::Group(children) => ParallelAvroResult::Group(
12109            children
12110                .iter()
12111                .map(|child| parallel_results_for_shape(child, flat_results))
12112                .collect(),
12113        ),
12114    }
12115}
12116
12117impl Future for ParallelCall {
12118    type Output = Result<Vec<ParallelResult>>;
12119
12120    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12121        self.poll_avro_value(cx)
12122            .map_ok(|results| {
12123                results
12124                    .into_iter()
12125                    .map(ParallelAvroResult::into_json_result)
12126                    .collect::<Result<Vec<_>>>()
12127            })
12128            .map_ok(|result| result)
12129            .flatten_result()
12130    }
12131}
12132
12133#[derive(Clone, Debug)]
12134struct SelectionMemberPlan {
12135    key: SelectionKey,
12136    index: usize,
12137    base_sequence: u64,
12138    size: usize,
12139    kind: String,
12140    shape: ParallelShape,
12141    leaf_start: usize,
12142}
12143
12144fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12145    match operation {
12146        ParallelOperation::Activity { .. } => "activity",
12147        ParallelOperation::ChildWorkflow { .. } => "child",
12148        ParallelOperation::Timer(_) => "timer",
12149        ParallelOperation::Signal(_) => "signal",
12150        ParallelOperation::Condition { .. } => "condition",
12151        ParallelOperation::Group(_) => "group",
12152    }
12153}
12154
12155fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12156    match operation {
12157        ParallelOperation::Group(children) => parallel_shape(children),
12158        _ => ParallelShape::Leaf,
12159    }
12160}
12161
12162fn selection_descriptors(
12163    operations: Vec<(SelectionKey, ParallelOperation)>,
12164    base_sequence: u64,
12165) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12166    if operations.is_empty() {
12167        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12168            reason: "selection_empty",
12169            member_path: Vec::new(),
12170            message: "durable selection requires at least one operation".to_string(),
12171        }));
12172    }
12173    let operation_refs = operations
12174        .iter()
12175        .map(|(_, operation)| operation)
12176        .collect::<Vec<_>>();
12177    let total_size = operation_refs
12178        .iter()
12179        .map(|operation| match operation {
12180            ParallelOperation::Group(children) => parallel_leaf_count(children),
12181            _ => 1,
12182        })
12183        .sum::<usize>();
12184    if total_size > MAX_PARALLEL_OPERATIONS {
12185        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12186            reason: "fan_out_limit_exceeded",
12187            member_path: Vec::new(),
12188            message: format!(
12189                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12190            ),
12191        }));
12192    }
12193    let group_kind = {
12194        let mut kind = None;
12195        for operation in &operation_refs {
12196            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12197            match kind {
12198                None => kind = Some(operation_kind),
12199                Some(current) if current == operation_kind => {}
12200                Some(_) => {
12201                    kind = Some("mixed");
12202                    break;
12203                }
12204            }
12205        }
12206        kind.unwrap_or("mixed")
12207    };
12208
12209    let mut descriptors = Vec::with_capacity(total_size);
12210    let mut members = Vec::with_capacity(operations.len());
12211    let mut cursor = 0usize;
12212    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12213    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12214        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12215            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12216                reason: "selection_key_invalid",
12217                member_path: vec![member_index],
12218                message: "selection member keys must be non-empty strings or non-negative integers"
12219                    .to_string(),
12220            }));
12221        }
12222        if seen_keys.contains(&key) {
12223            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12224                reason: "selection_key_duplicate",
12225                member_path: vec![member_index],
12226                message: format!("selection member key {key:?} is duplicated"),
12227            }));
12228        }
12229        seen_keys.push(key.clone());
12230        let member_size = match &operation {
12231            ParallelOperation::Group(children) => parallel_leaf_count(children),
12232            _ => 1,
12233        };
12234        if member_size == 0 {
12235            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12236                reason: "selection_member_empty",
12237                member_path: vec![member_index],
12238                message: "a selection member must contain at least one durable leaf".to_string(),
12239            }));
12240        }
12241        let member_base = base_sequence
12242            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12243            .ok_or(Error::TimerDurationOverflow)?;
12244        let member_kind = selection_operation_kind(&operation).to_string();
12245        let member_shape = selection_operation_shape(&operation);
12246        let leaf_start = descriptors.len();
12247        match operation {
12248            ParallelOperation::Group(children) => {
12249                validate_parallel_operations(&children, &mut vec![member_index], false)?;
12250                for mut descriptor in parallel_descriptors(children, member_base)? {
12251                    let flat_index = cursor + descriptor.offset;
12252                    descriptor.group_path.insert(
12253                        0,
12254                        selection_group_entry(
12255                            base_sequence,
12256                            total_size,
12257                            flat_index,
12258                            group_kind,
12259                            &SelectionMemberMetadata {
12260                                key: key.clone(),
12261                                index: member_index,
12262                                base_sequence: member_base,
12263                                size: member_size,
12264                                kind: member_kind.clone(),
12265                            },
12266                        ),
12267                    );
12268                    descriptor.member_path.insert(0, member_index);
12269                    descriptor.offset = flat_index;
12270                    descriptors.push(descriptor);
12271                }
12272            }
12273            operation => {
12274                validate_parallel_operations(
12275                    std::slice::from_ref(&operation),
12276                    &mut Vec::new(),
12277                    true,
12278                )?;
12279                descriptors.push(ParallelDescriptor {
12280                    operation,
12281                    offset: cursor,
12282                    member_path: vec![member_index],
12283                    group_path: vec![selection_group_entry(
12284                        base_sequence,
12285                        total_size,
12286                        cursor,
12287                        group_kind,
12288                        &SelectionMemberMetadata {
12289                            key: key.clone(),
12290                            index: member_index,
12291                            base_sequence: member_base,
12292                            size: member_size,
12293                            kind: member_kind.clone(),
12294                        },
12295                    )],
12296                });
12297            }
12298        }
12299        members.push(SelectionMemberPlan {
12300            key,
12301            index: member_index,
12302            base_sequence: member_base,
12303            size: member_size,
12304            kind: member_kind,
12305            shape: member_shape,
12306            leaf_start,
12307        });
12308        cursor += member_size;
12309    }
12310    Ok((descriptors, members))
12311}
12312
12313struct SelectionLeaf {
12314    call: ParallelLeafCall,
12315    outcome: Option<Result<ParallelAvroResult>>,
12316}
12317
12318/// Stable reference to one member of a durable selection group.
12319#[derive(Clone)]
12320pub struct DurableOperationHandle {
12321    ctx: WorkflowContext,
12322    pub key: SelectionKey,
12323    pub index: usize,
12324    pub kind: String,
12325    pub identity: String,
12326    pub base_sequence: u64,
12327    pub size: usize,
12328    pub selection_group_id: String,
12329    shape: ParallelShape,
12330}
12331
12332impl std::fmt::Debug for DurableOperationHandle {
12333    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12334        formatter
12335            .debug_struct("DurableOperationHandle")
12336            .field("key", &self.key)
12337            .field("index", &self.index)
12338            .field("kind", &self.kind)
12339            .field("identity", &self.identity)
12340            .field("base_sequence", &self.base_sequence)
12341            .field("size", &self.size)
12342            .field("selection_group_id", &self.selection_group_id)
12343            .finish()
12344    }
12345}
12346
12347impl DurableOperationHandle {
12348    /// Await this member after another member has already won the selection.
12349    pub fn await_result(&self) -> DurableOperationAwaitCall {
12350        DurableOperationAwaitCall {
12351            handle: self.clone(),
12352        }
12353    }
12354
12355    /// Request cancellation without affecting siblings. The future resolves
12356    /// to unit; only `SelectionOperationCancelled` history proves cancellation
12357    /// beat a concurrently committed terminal result.
12358    pub fn cancel(&self) -> CancelDurableOperationCall {
12359        CancelDurableOperationCall {
12360            handle: self.clone(),
12361            emitted: false,
12362        }
12363    }
12364}
12365
12366/// The one winner committed for a durable selection group.
12367#[derive(Debug)]
12368pub struct SelectionResult {
12369    pub key: SelectionKey,
12370    pub index: usize,
12371    pub kind: String,
12372    pub identity: String,
12373    pub value: Option<ParallelResult>,
12374    pub failure: Option<Error>,
12375    pub winner: DurableOperationHandle,
12376    pub handles: Vec<DurableOperationHandle>,
12377}
12378
12379impl SelectionResult {
12380    pub fn succeeded(&self) -> bool {
12381        self.failure.is_none()
12382    }
12383
12384    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
12385        self.handles.iter().find(|handle| &handle.key == key)
12386    }
12387
12388    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
12389        self.handles
12390            .iter()
12391            .filter(|handle| handle.index != self.index)
12392            .collect()
12393    }
12394
12395    pub fn into_result(self) -> Result<ParallelResult> {
12396        match (self.value, self.failure) {
12397            (Some(value), None) => Ok(value),
12398            (_, Some(error)) => Err(error),
12399            _ => Err(Error::WorkerLoop(
12400                "selection result contained neither a value nor a failure".to_string(),
12401            )),
12402        }
12403    }
12404}
12405
12406/// Future returned by [`WorkflowContext::select`].
12407pub struct SelectCall {
12408    ctx: WorkflowContext,
12409    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
12410    members: Vec<SelectionMemberPlan>,
12411    leaves: Vec<SelectionLeaf>,
12412    group_id: Option<String>,
12413}
12414
12415impl SelectCall {
12416    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
12417        Self {
12418            ctx,
12419            operations: Some(operations),
12420            members: Vec::new(),
12421            leaves: Vec::new(),
12422            group_id: None,
12423        }
12424    }
12425
12426    fn initialize(&mut self) -> Result<()> {
12427        let operations = self.operations.take().unwrap_or_default();
12428        let base_sequence = {
12429            let state = self
12430                .ctx
12431                .state
12432                .lock()
12433                .map_err(|_| Error::WorkflowStatePoisoned)?;
12434            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
12435                state.recorded_commands.get(state.command_cursor)
12436            {
12437                *sequence
12438            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
12439            {
12440                marker.selection_group_base_sequence
12441            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12442                recorded.sequence()
12443            } else {
12444                let last = state
12445                    .recorded_commands
12446                    .last()
12447                    .map(RecordedCommand::sequence)
12448                    .unwrap_or(0);
12449                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12450                    .and_then(|sequence| sequence.checked_add(1))
12451                    .ok_or(Error::TimerDurationOverflow)?
12452            }
12453        };
12454        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
12455        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
12456        {
12457            let mut state = self
12458                .ctx
12459                .state
12460                .lock()
12461                .map_err(|_| Error::WorkflowStatePoisoned)?;
12462            state.expand_cancellation_group(&descriptors)?;
12463            state.prepare_group_cancellation(&descriptors)?;
12464        }
12465        self.leaves = descriptors
12466            .into_iter()
12467            .map(|descriptor| SelectionLeaf {
12468                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
12469                outcome: None,
12470            })
12471            .collect();
12472        self.members = members;
12473        self.group_id = Some(group_id);
12474        Ok(())
12475    }
12476}
12477
12478impl Future for SelectCall {
12479    type Output = Result<SelectionResult>;
12480
12481    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12482        if self.operations.is_some() {
12483            if let Err(error) = self.initialize() {
12484                return Poll::Ready(Err(error));
12485            }
12486        }
12487
12488        for leaf in &mut self.leaves {
12489            if leaf.outcome.is_some() {
12490                continue;
12491            }
12492            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
12493                if outcome
12494                    .as_ref()
12495                    .err()
12496                    .is_some_and(workflow_task_integrity_error)
12497                {
12498                    return Poll::Ready(outcome.map(|_| unreachable!()));
12499                }
12500                leaf.outcome = Some(outcome);
12501            }
12502        }
12503
12504        if self
12505            .ctx
12506            .state
12507            .lock()
12508            .map_err(|_| Error::WorkflowStatePoisoned)?
12509            .cancellation_delivery_intent
12510            .is_some()
12511        {
12512            return Poll::Pending;
12513        }
12514
12515        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
12516            matches!(
12517                leaf.outcome,
12518                Some(Err(Error::CooperativeCancellationRequested(_)))
12519            )
12520        }) {
12521            return Poll::Ready(
12522                leaf.outcome
12523                    .take()
12524                    .expect("matched cancellation")
12525                    .map(|_| unreachable!()),
12526            );
12527        }
12528
12529        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
12530        let selection_member_range = self
12531            .members
12532            .first()
12533            .map(|member| member.base_sequence)
12534            .zip(self.leaves.len().try_into().ok())
12535            .map(|(base_sequence, size): (u64, u64)| {
12536                base_sequence..base_sequence.saturating_add(size)
12537            });
12538        let marker = {
12539            let mut state = match self.ctx.state.lock() {
12540                Ok(state) => state,
12541                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12542            };
12543            let marker = state
12544                .selection_markers
12545                .get(state.selection_marker_cursor)
12546                .cloned();
12547            if marker.is_none()
12548                && all_members_terminal
12549                && selection_member_range.as_ref().is_some_and(|member_range| {
12550                    state
12551                        .recorded_commands
12552                        .iter()
12553                        .any(|command| member_range.contains(&command.sequence()))
12554                })
12555            {
12556                // Terminal member history can be committed before the server's
12557                // SelectionResolved marker becomes visible to this task. That
12558                // marker is the durable barrier the selection is still waiting
12559                // on, so an otherwise commandless replay remains legitimately
12560                // pending instead of failing as an untracked yield.
12561                state.matched_recorded_pending = true;
12562            }
12563            marker
12564        };
12565        let Some(marker) = marker else {
12566            return Poll::Pending;
12567        };
12568        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
12569            || marker.selection_group_size != self.leaves.len()
12570            || self.members.first().map(|member| member.base_sequence)
12571                != Some(marker.selection_group_base_sequence)
12572        {
12573            return Poll::Ready(Err(invalid_recorded_history(
12574                "selection_group_shape_mismatch",
12575                marker.selection_group_base_sequence,
12576                self.group_id
12577                    .as_deref()
12578                    .unwrap_or("initialized selection group"),
12579                &marker.selection_group_id,
12580                "recorded selection group differs from current workflow code",
12581            )));
12582        }
12583        let Some(member_position) = self.members.iter().position(|member| {
12584            member.key == marker.member_key
12585                && member.index == marker.member_index
12586                && member.base_sequence == marker.member_base_sequence
12587                && member.size == marker.member_size
12588                && member.kind == marker.operation_kind
12589        }) else {
12590            return Poll::Ready(Err(invalid_recorded_history(
12591                "selection_member_shape_mismatch",
12592                marker.member_base_sequence,
12593                "winner member matching current workflow code",
12594                &format!("{:?}", marker.member_key),
12595                "recorded selection winner differs from the authored member identity",
12596            )));
12597        };
12598        let member = self.members[member_position].clone();
12599        let (handles, resolution_sequence) = {
12600            let mut state = match self.ctx.state.lock() {
12601                Ok(state) => state,
12602                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12603            };
12604            let identities = self
12605                .members
12606                .iter()
12607                .map(|candidate| {
12608                    selection_operation_identity(
12609                        &state,
12610                        &candidate.kind,
12611                        candidate.base_sequence,
12612                        candidate.size,
12613                    )
12614                })
12615                .collect::<Vec<_>>();
12616            if let Some((position, missing)) = identities
12617                .iter()
12618                .enumerate()
12619                .find(|(_, identity)| identity.is_empty())
12620                .map(|(position, identity)| (position, identity.clone()))
12621            {
12622                let candidate = &self.members[position];
12623                return Poll::Ready(Err(invalid_recorded_history(
12624                    "selection_operation_identity_missing",
12625                    candidate.base_sequence,
12626                    &format!(
12627                        "durable {} resource identity from scheduled/open history",
12628                        candidate.kind
12629                    ),
12630                    &missing,
12631                    "selection member history is missing its canonical durable identity",
12632                )));
12633            }
12634            let expected_winner_identity = &identities[member_position];
12635            let resolution_sequence = match validated_selection_resolution_sequence(
12636                &state,
12637                &marker,
12638                &member,
12639                expected_winner_identity,
12640            ) {
12641                Ok(sequence) => sequence,
12642                Err(error) => return Poll::Ready(Err(error)),
12643            };
12644            let handles = self
12645                .members
12646                .iter()
12647                .zip(identities)
12648                .map(|(member, identity)| DurableOperationHandle {
12649                    ctx: self.ctx.clone(),
12650                    key: member.key.clone(),
12651                    index: member.index,
12652                    kind: member.kind.clone(),
12653                    identity,
12654                    base_sequence: member.base_sequence,
12655                    size: member.size,
12656                    selection_group_id: marker.selection_group_id.clone(),
12657                    shape: member.shape.clone(),
12658                })
12659                .collect::<Vec<_>>();
12660            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
12661                return Poll::Ready(Err(error));
12662            }
12663            state.selection_marker_cursor += 1;
12664            (handles, resolution_sequence)
12665        };
12666
12667        let mut winner_failure = None;
12668        let mut flat_results = Vec::with_capacity(member.size);
12669        if marker.outcome == "failed" {
12670            let resolution_offset = match resolution_sequence
12671                .checked_sub(member.base_sequence)
12672                .and_then(|offset| usize::try_from(offset).ok())
12673            {
12674                Some(offset) if offset < member.size => offset,
12675                _ => {
12676                    return Poll::Ready(Err(invalid_recorded_history(
12677                        "selection_resolution_event_mismatch",
12678                        member.base_sequence,
12679                        "failure event within selected member bounds",
12680                        &resolution_sequence.to_string(),
12681                        "selection failure event is outside the authored member",
12682                    )))
12683                }
12684            };
12685            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
12686            match leaf.outcome.take() {
12687                Some(Err(error)) => winner_failure = Some(error),
12688                _ => {
12689                    return Poll::Ready(Err(invalid_recorded_history(
12690                        "selection_winner_outcome_mismatch",
12691                        member.base_sequence,
12692                        "exact failed terminal history referenced by SelectionResolved",
12693                        "missing or successful resolution event",
12694                        "selection winner marker disagrees with terminal operation history",
12695                    )))
12696                }
12697            }
12698        } else {
12699            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
12700                match leaf.outcome.take() {
12701                    Some(Ok(result)) => flat_results.push(result),
12702                    Some(Err(_)) => {
12703                        return Poll::Ready(Err(invalid_recorded_history(
12704                            "selection_winner_outcome_mismatch",
12705                            member.base_sequence,
12706                            "fully completed nested selection member",
12707                            "failed durable leaf",
12708                            "completed selection winner contains a failed leaf",
12709                        )))
12710                    }
12711                    None => {
12712                        return Poll::Ready(Err(invalid_recorded_history(
12713                            "selection_winner_unresolved",
12714                            member.base_sequence,
12715                            "terminal history for every completed winner leaf",
12716                            "pending member history",
12717                            "completed SelectionResolved member has an unfinished durable barrier",
12718                        )))
12719                    }
12720                }
12721            }
12722        }
12723        let value = if winner_failure.is_none() {
12724            let mut flat_results = flat_results.into_iter();
12725            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
12726            match value.into_json_result() {
12727                Ok(value) => Some(value),
12728                Err(error) => return Poll::Ready(Err(error)),
12729            }
12730        } else {
12731            None
12732        };
12733        let winner = handles[member_position].clone();
12734        self.ctx
12735            .state
12736            .lock()
12737            .map_err(|_| Error::WorkflowStatePoisoned)?
12738            .advance_cancellation_selection(&marker.selection_group_id);
12739        Poll::Ready(Ok(SelectionResult {
12740            key: winner.key.clone(),
12741            index: winner.index,
12742            kind: winner.kind.clone(),
12743            identity: winner.identity.clone(),
12744            value,
12745            failure: winner_failure,
12746            winner,
12747            handles,
12748        }))
12749    }
12750}
12751
12752fn selection_operation_identity(
12753    state: &WorkflowState,
12754    kind: &str,
12755    base_sequence: u64,
12756    size: usize,
12757) -> String {
12758    if kind == "group" {
12759        return format!("group:{base_sequence}:{size}");
12760    }
12761    let fields: &[&str] = match kind {
12762        "activity" => &["activity_execution_id"],
12763        "child" => &["child_workflow_run_id"],
12764        "timer" => &["timer_id"],
12765        "signal" => &["signal_wait_id"],
12766        "condition" => &["condition_wait_id"],
12767        _ => &[],
12768    };
12769    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
12770        for event in state
12771            .history_events
12772            .iter()
12773            .filter(|event| durable_event_sequence(event) == Some(sequence))
12774        {
12775            for field in fields {
12776                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
12777                    if !identity.is_empty() {
12778                        return identity.to_string();
12779                    }
12780                }
12781            }
12782        }
12783    }
12784    String::new()
12785}
12786
12787fn validated_selection_resolution_sequence(
12788    state: &WorkflowState,
12789    marker: &SelectionMarker,
12790    member: &SelectionMemberPlan,
12791    expected_identity: &str,
12792) -> Result<u64> {
12793    if expected_identity.is_empty() {
12794        return Err(invalid_recorded_history(
12795            "selection_operation_identity_missing",
12796            member.base_sequence,
12797            &format!(
12798                "durable {} resource identity from scheduled/open history",
12799                member.kind
12800            ),
12801            "missing operation identity",
12802            "selection member history is missing its canonical durable identity",
12803        ));
12804    }
12805    if marker.operation_identity != expected_identity {
12806        return Err(invalid_recorded_history(
12807            "selection_operation_identity_mismatch",
12808            member.base_sequence,
12809            expected_identity,
12810            &marker.operation_identity,
12811            "selection winner identity does not match durable scheduled/open history",
12812        ));
12813    }
12814
12815    let failure_types = [
12816        "ActivityFailed",
12817        "ActivityCancelled",
12818        "ActivityTimedOut",
12819        "ChildRunFailed",
12820        "ChildRunCancelled",
12821        "ChildRunTerminated",
12822    ];
12823    let success_types = [
12824        "ActivityCompleted",
12825        "ChildRunCompleted",
12826        "TimerFired",
12827        "SignalApplied",
12828        "ConditionWaitSatisfied",
12829        "ConditionWaitTimedOut",
12830    ];
12831    let terminal_types: &[&str] = if marker.outcome == "failed" {
12832        &failure_types
12833    } else {
12834        &success_types
12835    };
12836    let mut candidates = Vec::new();
12837    let member_commands = (member.base_sequence
12838        ..member.base_sequence.saturating_add(member.size as u64))
12839        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
12840        .map(|command| (command.sequence(), command))
12841        .collect::<BTreeMap<_, _>>();
12842    let mut resolved_conditions = BTreeSet::new();
12843    for event in state.history_events.iter() {
12844        let Some(sequence) = durable_event_sequence(event) else {
12845            continue;
12846        };
12847        let Some(command) = member_commands.get(&sequence) else {
12848            continue;
12849        };
12850        if !terminal_types.contains(&event.event_type.as_str()) {
12851            continue;
12852        }
12853        if matches!(command, RecordedCommand::ConditionWait { .. }) {
12854            if !matches!(
12855                event.event_type.as_str(),
12856                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
12857            ) && !(event.event_type == "TimerFired"
12858                && event.payload.get("timer_kind").and_then(Value::as_str)
12859                    == Some("condition_timeout"))
12860            {
12861                continue;
12862            }
12863            if !resolved_conditions.insert(sequence) {
12864                continue;
12865            }
12866        }
12867        let event_id = event
12868            .raw
12869            .get("id")
12870            .or_else(|| event.raw.get("event_id"))
12871            .and_then(Value::as_str)
12872            .filter(|value| !value.is_empty())
12873            .ok_or_else(|| {
12874                invalid_recorded_history(
12875                    "selection_resolution_event_id_missing",
12876                    member.base_sequence,
12877                    "terminal selection history with a durable event id",
12878                    &event.payload.to_string(),
12879                    "selection terminal history cannot be bound to its winner marker",
12880                )
12881            })?;
12882        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
12883    }
12884    let resolution = if marker.outcome == "failed" {
12885        candidates.first()
12886    } else {
12887        candidates.last()
12888    };
12889    let Some((event_id, event_type, sequence)) = resolution else {
12890        return Err(invalid_recorded_history(
12891            "selection_resolution_event_missing",
12892            member.base_sequence,
12893            "terminal history for the selected member",
12894            &format!("{:?}", marker.member_key),
12895            "selection winner marker has no matching durable terminal event",
12896        ));
12897    };
12898    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
12899        return Err(invalid_recorded_history(
12900            "selection_resolution_event_mismatch",
12901            member.base_sequence,
12902            &format!("{event_type}:{event_id}"),
12903            &format!(
12904                "{}:{}",
12905                marker.resolution_event_type, marker.resolution_event_id
12906            ),
12907            "selection winner marker does not reference the event that made its member terminal",
12908        ));
12909    }
12910    Ok(*sequence)
12911}
12912
12913fn selection_member_recorded_command(
12914    state: &WorkflowState,
12915    authored_sequence: u64,
12916) -> Option<&RecordedCommand> {
12917    let original = state
12918        .recorded_commands
12919        .iter()
12920        .find(|command| command.sequence() == authored_sequence)?;
12921    let RecordedCommand::ConditionWait {
12922        occurrence_id,
12923        parallel_group_path: Some(_),
12924        ..
12925    } = original
12926    else {
12927        return Some(original);
12928    };
12929    // Decoding proves each physical reopen has the same authored identity and
12930    // group path after a satisfied predecessor. Only its latest wait can make
12931    // this logical member terminal.
12932    state
12933        .recorded_commands
12934        .iter()
12935        .filter(|command| {
12936            matches!(command, RecordedCommand::ConditionWait {
12937                occurrence_id: candidate, ..
12938            } if candidate == occurrence_id)
12939        })
12940        .max_by_key(|command| command.sequence())
12941}
12942
12943fn recorded_selection_member_outcome(
12944    state: &WorkflowState,
12945    handle: &DurableOperationHandle,
12946) -> Result<Option<ParallelResult>> {
12947    for event in state.history_events.iter() {
12948        let Some(sequence) = durable_event_sequence(event) else {
12949            continue;
12950        };
12951        if sequence < handle.base_sequence
12952            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
12953            || !matches!(
12954                event.event_type.as_str(),
12955                "ActivityFailed"
12956                    | "ActivityCancelled"
12957                    | "ActivityTimedOut"
12958                    | "ChildRunFailed"
12959                    | "ChildRunCancelled"
12960                    | "ChildRunTerminated"
12961            )
12962        {
12963            continue;
12964        }
12965        let Some(command) = state
12966            .recorded_commands
12967            .iter()
12968            .find(|command| command.sequence() == sequence)
12969        else {
12970            continue;
12971        };
12972        match command {
12973            RecordedCommand::Activity {
12974                outcome: Some(Err(failure)),
12975                ..
12976            } => return Err(Error::ActivityFailed(failure.clone())),
12977            RecordedCommand::ChildWorkflow {
12978                outcome: Some(Err(failure)),
12979                ..
12980            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
12981            _ => {}
12982        }
12983    }
12984
12985    let mut results = Vec::with_capacity(handle.size);
12986    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
12987        let Some(command) = selection_member_recorded_command(state, sequence) else {
12988            return Ok(None);
12989        };
12990        let result = match command {
12991            RecordedCommand::Activity { outcome, .. } => match outcome {
12992                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
12993                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
12994                None => return Ok(None),
12995            },
12996            RecordedCommand::Timer { fired, .. } => {
12997                if !fired {
12998                    return Ok(None);
12999                }
13000                ParallelAvroResult::Timer
13001            }
13002            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13003                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13004                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13005                None => return Ok(None),
13006            },
13007            RecordedCommand::SignalWait { value, .. } => match value {
13008                Some(value) => ParallelAvroResult::Signal(value.clone()),
13009                None => return Ok(None),
13010            },
13011            RecordedCommand::ConditionWait { result, .. } => match result {
13012                Some(result) => ParallelAvroResult::Condition(*result),
13013                None => return Ok(None),
13014            },
13015            other => {
13016                return Err(command_mismatch(
13017                    other,
13018                    format!("selected {} member", handle.kind),
13019                ))
13020            }
13021        };
13022        results.push(result);
13023    }
13024    let mut results = results.into_iter();
13025    parallel_results_for_shape(&handle.shape, &mut results)
13026        .into_json_result()
13027        .map(Some)
13028}
13029
13030fn recorded_selection_member_is_terminal(
13031    state: &WorkflowState,
13032    handle: &DurableOperationHandle,
13033) -> bool {
13034    let mut completed = 0usize;
13035    let mut all_completed = true;
13036    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13037        let Some(command) = selection_member_recorded_command(state, sequence) else {
13038            all_completed = false;
13039            continue;
13040        };
13041        let terminal = match command {
13042            RecordedCommand::Activity {
13043                outcome: Some(Err(_)),
13044                ..
13045            }
13046            | RecordedCommand::ChildWorkflow {
13047                outcome: Some(Err(_)),
13048                ..
13049            } => return true,
13050            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13051            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13052            RecordedCommand::Timer { fired, .. } => *fired,
13053            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13054            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13055            RecordedCommand::SearchAttributes { .. }
13056            | RecordedCommand::CancellationScope { .. }
13057            | RecordedCommand::SideEffect { .. }
13058            | RecordedCommand::VersionMarker { .. }
13059            | RecordedCommand::Memo { .. }
13060            | RecordedCommand::CancellationBoundary { .. }
13061            | RecordedCommand::CancellationGroup { .. } => false,
13062        };
13063        if !terminal {
13064            all_completed = false;
13065            continue;
13066        }
13067        completed += 1;
13068    }
13069    all_completed && completed == handle.size
13070}
13071
13072fn selection_cancellation_for_handle(
13073    state: &WorkflowState,
13074    handle: &DurableOperationHandle,
13075) -> Result<bool> {
13076    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13077        recorded.selection_group_id == handle.selection_group_id
13078            && recorded.member_base_sequence == handle.base_sequence
13079    }) else {
13080        return Ok(false);
13081    };
13082    validate_selection_cancellation_marker(marker, handle)?;
13083    Ok(true)
13084}
13085
13086fn validate_selection_cancellations_for_handles(
13087    state: &WorkflowState,
13088    handles: &[DurableOperationHandle],
13089) -> Result<()> {
13090    let Some(group_id) = handles
13091        .first()
13092        .map(|handle| handle.selection_group_id.as_str())
13093    else {
13094        return Ok(());
13095    };
13096    for marker in state
13097        .cancelled_selection_members
13098        .iter()
13099        .filter(|marker| marker.selection_group_id == group_id)
13100    {
13101        let Some(handle) = handles
13102            .iter()
13103            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13104        else {
13105            return Err(invalid_recorded_history(
13106                "selection_cancellation_member_mismatch",
13107                marker.member_base_sequence,
13108                "SelectionOperationCancelled matching an authored selection handle",
13109                &format!("{marker:?}"),
13110                "selection cancellation member base does not name an authored member",
13111            ));
13112        };
13113        validate_selection_cancellation_marker(marker, handle)?;
13114    }
13115    Ok(())
13116}
13117
13118fn validate_selection_cancellation_marker(
13119    marker: &SelectionCancellation,
13120    handle: &DurableOperationHandle,
13121) -> Result<()> {
13122    if marker.selection_group_id != handle.selection_group_id
13123        || marker.member_key != handle.key
13124        || marker.member_index != handle.index
13125        || marker.member_base_sequence != handle.base_sequence
13126        || marker.member_size != handle.size
13127        || marker.operation_kind != handle.kind
13128        || marker.operation_identity != handle.identity
13129    {
13130        return Err(invalid_recorded_history(
13131            "selection_cancellation_member_mismatch",
13132            handle.base_sequence,
13133            "SelectionOperationCancelled matching the authored selection handle",
13134            &format!("{marker:?}"),
13135            "selection cancellation history targets different authored member metadata",
13136        ));
13137    }
13138    Ok(())
13139}
13140
13141/// Future returned by [`DurableOperationHandle::await_result`].
13142pub struct DurableOperationAwaitCall {
13143    handle: DurableOperationHandle,
13144}
13145
13146impl Future for DurableOperationAwaitCall {
13147    type Output = Result<ParallelResult>;
13148
13149    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13150        let mut state = match self.handle.ctx.state.lock() {
13151            Ok(state) => state,
13152            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13153        };
13154        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13155            return Poll::Ready(Err(error));
13156        }
13157        match state.prepare_selection_handle_cancellation(&self.handle) {
13158            Ok(true) => return Poll::Pending,
13159            Ok(false) => {}
13160            Err(error) => return Poll::Ready(Err(error)),
13161        }
13162        match selection_cancellation_for_handle(&state, &self.handle) {
13163            Err(error) => return Poll::Ready(Err(error)),
13164            Ok(false) => {}
13165            Ok(true) => {
13166                state.advance_cancellation_receipt(
13167                    &self.handle.selection_group_id,
13168                    self.handle.base_sequence,
13169                );
13170                return Poll::Ready(Err(Error::DurableOperationCancelled(
13171                    DurableOperationCancelled {
13172                        selection_group_id: self.handle.selection_group_id.clone(),
13173                        member_key: self.handle.key.clone(),
13174                        member_index: self.handle.index,
13175                        operation_kind: self.handle.kind.clone(),
13176                        operation_identity: self.handle.identity.clone(),
13177                    },
13178                )));
13179            }
13180        }
13181        match recorded_selection_member_outcome(&state, &self.handle) {
13182            Ok(Some(result)) => {
13183                state.advance_cancellation_handle(&self.handle, false);
13184                Poll::Ready(Ok(result))
13185            }
13186            Ok(None) => Poll::Pending,
13187            Err(error) => {
13188                if !workflow_task_integrity_error(&error) {
13189                    state.advance_cancellation_handle(&self.handle, true);
13190                }
13191                Poll::Ready(Err(error))
13192            }
13193        }
13194    }
13195}
13196
13197fn validate_selection_delivery_handle(
13198    state: &WorkflowState,
13199    handle: &DurableOperationHandle,
13200) -> Result<()> {
13201    let path = state
13202        .recorded_commands
13203        .iter()
13204        .find(|command| command.sequence() == handle.base_sequence)
13205        .and_then(|command| match command {
13206            RecordedCommand::Activity {
13207                parallel_group_path,
13208                ..
13209            }
13210            | RecordedCommand::ChildWorkflow {
13211                parallel_group_path,
13212                ..
13213            }
13214            | RecordedCommand::Timer {
13215                parallel_group_path,
13216                ..
13217            }
13218            | RecordedCommand::SignalWait {
13219                parallel_group_path,
13220                ..
13221            }
13222            | RecordedCommand::ConditionWait {
13223                parallel_group_path,
13224                ..
13225            } => parallel_group_path.as_ref(),
13226            _ => None,
13227        })
13228        .and_then(|path| path.first());
13229    let matches = path.is_some_and(|entry| {
13230        entry.parallel_group_mode.as_deref() == Some("select")
13231            && entry.parallel_group_id == handle.selection_group_id
13232            && entry.selection_member_key.as_ref() == Some(&handle.key)
13233            && entry.selection_member_index == Some(handle.index)
13234            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13235            && entry.selection_member_size == Some(handle.size)
13236            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13237    });
13238    if !matches
13239        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13240            != handle.identity
13241    {
13242        return Err(invalid_recorded_history(
13243            "cooperative_cancellation_call_mismatch",
13244            handle.base_sequence,
13245            "selection handle matching its authored durable identity",
13246            &format!("{handle:?}"),
13247            "selection handle identity or member metadata changed before cancellation replay",
13248        ));
13249    }
13250    Ok(())
13251}
13252
13253/// Future returned by [`DurableOperationHandle::cancel`].
13254pub struct CancelDurableOperationCall {
13255    handle: DurableOperationHandle,
13256    emitted: bool,
13257}
13258
13259impl Future for CancelDurableOperationCall {
13260    type Output = Result<()>;
13261
13262    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13263        let ctx = self.handle.ctx.clone();
13264        let mut state = match ctx.state.lock() {
13265            Ok(state) => state,
13266            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13267        };
13268        match selection_cancellation_for_handle(&state, &self.handle) {
13269            Err(error) => return Poll::Ready(Err(error)),
13270            Ok(true) => {
13271                state.advance_cancellation_receipt(
13272                    &self.handle.selection_group_id,
13273                    self.handle.base_sequence,
13274                );
13275                return Poll::Ready(Ok(()));
13276            }
13277            Ok(false) => {}
13278        }
13279        if recorded_selection_member_is_terminal(&state, &self.handle) {
13280            return Poll::Ready(Ok(()));
13281        }
13282        if !self.emitted {
13283            state.commands.push(json!({
13284                "type": "cancel_selection_operation",
13285                "selection_group_id": self.handle.selection_group_id,
13286                "member_key": self.handle.key,
13287                "member_index": self.handle.index,
13288                "member_base_sequence": self.handle.base_sequence,
13289                "member_size": self.handle.size,
13290                "operation_kind": self.handle.kind,
13291                "operation_identity": self.handle.identity,
13292            }));
13293            self.emitted = true;
13294        }
13295        // The cancellation command is only a request. Do not expose workflow
13296        // state after cancel until committed SelectionOperationCancelled
13297        // history proves that the request won the race with member completion.
13298        Poll::Pending
13299    }
13300}
13301
13302trait PollNestedResultExt<T> {
13303    fn flatten_result(self) -> Poll<Result<T>>;
13304}
13305
13306impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
13307    fn flatten_result(self) -> Poll<Result<T>> {
13308        match self {
13309            Poll::Ready(Ok(result)) => Poll::Ready(result),
13310            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13311            Poll::Pending => Poll::Pending,
13312        }
13313    }
13314}
13315
13316struct SagaCompensation {
13317    activity_type: String,
13318    options: ActivityOptions,
13319    arguments: AvroValue,
13320    registration_order: usize,
13321}
13322
13323/// Workflow-local deterministic saga compensation helper.
13324///
13325/// Register each compensation only after its forward step succeeds. Passing
13326/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
13327/// reverse registration order after any failure, including cooperative
13328/// cancellation. Each compensation is an ordinary durable activity, so replay,
13329/// duplicate delivery, and worker restart use existing history semantics.
13330pub struct Saga {
13331    ctx: WorkflowContext,
13332    compensations: Vec<SagaCompensation>,
13333}
13334
13335impl Saga {
13336    fn new(ctx: WorkflowContext) -> Self {
13337        Self {
13338            ctx,
13339            compensations: Vec::new(),
13340        }
13341    }
13342
13343    pub fn add_compensation<T: Serialize>(
13344        &mut self,
13345        activity_type: impl Into<String>,
13346        args: T,
13347    ) -> Result<&mut Self> {
13348        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
13349    }
13350
13351    pub fn add_compensation_with_options<T: Serialize>(
13352        &mut self,
13353        activity_type: impl Into<String>,
13354        options: ActivityOptions,
13355        args: T,
13356    ) -> Result<&mut Self> {
13357        let activity_type = activity_type.into();
13358        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
13359            return Err(Error::Codec(
13360                "saga compensation activity type must be non-empty without surrounding whitespace"
13361                    .to_string(),
13362            ));
13363        }
13364        options.validate().map_err(Error::InvalidActivityOptions)?;
13365        let arguments = AvroValue::from_serialize(&args)?;
13366        let registration_order = self.compensations.len() + 1;
13367        self.compensations.push(SagaCompensation {
13368            activity_type,
13369            options,
13370            arguments,
13371            registration_order,
13372        });
13373        Ok(self)
13374    }
13375
13376    /// Compensate `initiating_failure` and return the failure that must remain.
13377    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
13378        let _shield = match self.ctx.cancellation_shield() {
13379            Ok(shield) => shield,
13380            Err(error) => return error,
13381        };
13382        while let Some(compensation) = self.compensations.pop() {
13383            if let Err(compensation_failure) = self
13384                .ctx
13385                .activity_with_options(
13386                    compensation.activity_type.clone(),
13387                    compensation.options,
13388                    compensation.arguments,
13389                )
13390                .await
13391            {
13392                if workflow_task_integrity_error(&compensation_failure) {
13393                    return compensation_failure;
13394                }
13395                return Error::SagaCompensationFailed(SagaCompensationFailure {
13396                    initiating_failure: Box::new(initiating_failure),
13397                    compensation_failure: Box::new(compensation_failure),
13398                    compensation_activity_type: compensation.activity_type,
13399                    compensation_registration_order: compensation.registration_order,
13400                });
13401            }
13402        }
13403        initiating_failure
13404    }
13405
13406    /// Return a successful forward value or compensate and preserve its failure.
13407    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
13408        match outcome {
13409            Ok(value) => Ok(value),
13410            Err(error) => Err(self.compensate(error).await),
13411        }
13412    }
13413}
13414
13415pub struct ActivityCall {
13416    ctx: WorkflowContext,
13417    activity_type: String,
13418    options: ActivityOptions,
13419    worker_session: Option<WorkerSessionOptions>,
13420    args: Option<Result<AvroValue>>,
13421    scheduled: bool,
13422    local: bool,
13423    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
13424    parallel_group_path: Vec<ParallelGroupMetadata>,
13425}
13426
13427impl ActivityCall {
13428    fn poll_avro_value(
13429        mut self: Pin<&mut Self>,
13430        _cx: &mut TaskContext<'_>,
13431    ) -> Poll<Result<AvroValue>> {
13432        let ctx = self.ctx.clone();
13433        let mut state = match ctx.state.lock() {
13434            Ok(state) => state,
13435            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13436        };
13437
13438        if let Some(result) = &self.local_result {
13439            return match result.lock() {
13440                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
13441                    Poll::Ready(result.map_err(Error::ActivityFailed))
13442                }),
13443                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13444            };
13445        }
13446        if self.scheduled {
13447            return Poll::Pending;
13448        }
13449
13450        let options = match self.options.validate() {
13451            Ok(options) => options,
13452            Err(error) => {
13453                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
13454            }
13455        };
13456        if self.local {
13457            if self.worker_session.is_some() {
13458                return Poll::Ready(Err(Error::WorkerLoop(
13459                    "local activities cannot use worker-session routing".into(),
13460                )));
13461            }
13462            if let Err(error) = local_activity::validate(&options) {
13463                return Poll::Ready(Err(error));
13464            }
13465        }
13466        let session = match self
13467            .worker_session
13468            .as_ref()
13469            .map(WorkerSessionOptions::to_wire)
13470            .transpose()
13471        {
13472            Ok(value) => value,
13473            Err(error) => return Poll::Ready(Err(error)),
13474        };
13475        let session_queue = session
13476            .as_ref()
13477            .and_then(|session| session["queue"].as_str());
13478        let task_queue = options
13479            .task_queue
13480            .clone()
13481            .or_else(|| session_queue.map(str::to_owned))
13482            .unwrap_or_else(|| state.task_queue.clone());
13483        if session_queue.is_some_and(|queue| queue != task_queue) {
13484            return Poll::Ready(Err(Error::WorkerLoop(
13485                "worker-session queue must match the activity task queue".into(),
13486            )));
13487        }
13488        let current_recorded_options = RecordedActivityOptions {
13489            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
13490            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
13491            retry_policy: current_activity_retry_snapshot(&options),
13492            worker_session: session,
13493        };
13494
13495        let cursor = state.command_cursor;
13496        let call_kind = if self.local {
13497            CancellationCallKind::LocalActivity
13498        } else {
13499            CancellationCallKind::Activity
13500        };
13501        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13502            return Poll::Ready(Err(error));
13503        }
13504        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
13505            Ok(recorded) => recorded,
13506            Err(error) => return Poll::Ready(Err(error)),
13507        };
13508        if let Some(recorded) = recorded {
13509            let sequence = recorded.sequence();
13510            match recorded {
13511                RecordedCommand::Activity {
13512                    activity_type,
13513                    cancellation_policy,
13514                    options: recorded_options,
13515                    outcome,
13516                    parallel_group_path,
13517                    ..
13518                } => {
13519                    let current_policy = options
13520                        .cancellation_policy
13521                        .unwrap_or(CancellationPolicy::TryCancel)
13522                        .as_str();
13523                    if cancellation_policy != current_policy {
13524                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13525                            ReplayFailure::new(
13526                                "activity_cancellation_policy_changed",
13527                                Some(sequence),
13528                                Some(cancellation_policy),
13529                                Some(current_policy.to_string()),
13530                                "Activity cancellation policy changed during replay",
13531                            ),
13532                        )));
13533                    }
13534                    if let Err(error) = ensure_parallel_path_matches(
13535                        sequence,
13536                        parallel_group_path.as_deref(),
13537                        &self.parallel_group_path,
13538                    ) {
13539                        return Poll::Ready(Err(error));
13540                    }
13541                    if let Some(recorded_type) = activity_type {
13542                        if recorded_type != self.activity_type {
13543                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13544                                ReplayFailure::new(
13545                                    "recorded_command_detail_mismatch",
13546                                    Some(sequence),
13547                                    Some(format!("activity:{recorded_type}")),
13548                                    Some(format!("activity:{}", self.activity_type)),
13549                                    "recorded activity type differs from the current workflow command",
13550                                ),
13551                            )));
13552                        }
13553                    }
13554                    if let Some(recorded_options) = recorded_options {
13555                        if recorded_options.worker_session
13556                            != current_recorded_options.worker_session
13557                        {
13558                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
13559                                "activity_worker_session_mismatch", Some(sequence),
13560                                Some(activity_options_description(&recorded_options)),
13561                                Some(activity_options_description(&current_recorded_options)),
13562                                "recorded worker-session routing differs from the current activity",
13563                            ))));
13564                        }
13565                        if !recorded_options
13566                            .task_queue
13567                            .matches_current(&current_recorded_options.task_queue)
13568                        {
13569                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13570                                ReplayFailure::new(
13571                                    "activity_task_queue_mismatch",
13572                                    Some(sequence),
13573                                    Some(activity_options_description(&recorded_options)),
13574                                    Some(activity_options_description(&current_recorded_options)),
13575                                    "recorded activity task queue differs from the current workflow command",
13576                                ),
13577                            )));
13578                        }
13579                        if (self.local
13580                            && matches!(
13581                                recorded_options.execution_mode,
13582                                RecordedSnapshotValue::Unknown
13583                            ))
13584                            || !recorded_options
13585                                .execution_mode
13586                                .matches_current(&current_recorded_options.execution_mode)
13587                        {
13588                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13589                                ReplayFailure::new(
13590                                    "activity_execution_mode_mismatch",
13591                                    Some(sequence),
13592                                    Some(activity_options_description(&recorded_options)),
13593                                    Some(activity_options_description(&current_recorded_options)),
13594                                    "recorded activity execution mode differs from the current workflow command",
13595                                ),
13596                            )));
13597                        }
13598                        if !recorded_options
13599                            .retry_policy
13600                            .matches_current(&current_recorded_options.retry_policy)
13601                        {
13602                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13603                                ReplayFailure::new(
13604                                    "activity_retry_policy_mismatch",
13605                                    Some(sequence),
13606                                    Some(activity_options_description(&recorded_options)),
13607                                    Some(activity_options_description(&current_recorded_options)),
13608                                    "recorded activity retry policy differs from the current workflow command",
13609                                ),
13610                            )));
13611                        }
13612                    }
13613                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
13614                        return Poll::Ready(Err(error));
13615                    }
13616                    match state.prepare_scalar_cancellation(
13617                        cursor,
13618                        call_kind,
13619                        &self.parallel_group_path,
13620                    ) {
13621                        Ok(true) => {
13622                            self.scheduled = true;
13623                            return Poll::Pending;
13624                        }
13625                        Ok(false) => {}
13626                        Err(error) => return Poll::Ready(Err(error)),
13627                    }
13628                    state.command_cursor += 1;
13629                    if let Some(outcome) = outcome {
13630                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13631                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
13632                    }
13633                    state.matched_recorded_pending = true;
13634                    self.scheduled = true;
13635                    return Poll::Pending;
13636                }
13637                other => {
13638                    return Poll::Ready(Err(command_mismatch(
13639                        &other,
13640                        format!("activity:{}", self.activity_type),
13641                    )));
13642                }
13643            }
13644        }
13645
13646        if !self.scheduled {
13647            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
13648                Ok(args) => args,
13649                Err(error) => return Poll::Ready(Err(error)),
13650            };
13651            let arguments = normalize_avro_arguments(args);
13652            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
13653                Ok(envelope) => envelope,
13654                Err(error) => return Poll::Ready(Err(error)),
13655            };
13656
13657            let mut command = serde_json::Map::from_iter([
13658                (
13659                    "type".to_string(),
13660                    json!(if self.local {
13661                        "record_local_activity"
13662                    } else {
13663                        "schedule_activity"
13664                    }),
13665                ),
13666                (
13667                    "activity_type".to_string(),
13668                    json!(self.activity_type.clone()),
13669                ),
13670                ("queue".to_string(), json!(task_queue)),
13671                ("arguments".to_string(), envelope),
13672            ]);
13673            for (field, value) in [
13674                ("start_to_close_timeout", options.start_to_close_timeout),
13675                (
13676                    "schedule_to_start_timeout",
13677                    options.schedule_to_start_timeout,
13678                ),
13679                (
13680                    "schedule_to_close_timeout",
13681                    options.schedule_to_close_timeout,
13682                ),
13683                ("heartbeat_timeout", options.heartbeat_timeout),
13684            ] {
13685                if let Some(value) = value {
13686                    command.insert(field.to_string(), json!(value));
13687                }
13688            }
13689            if let Some(retry_policy) = &options.retry_policy {
13690                command.insert("retry_policy".to_string(), retry_policy.clone());
13691            }
13692            if let Some(policy) = options.cancellation_policy {
13693                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
13694            }
13695            if let Some(session) = current_recorded_options.worker_session {
13696                command.insert("worker_session".into(), session);
13697            }
13698            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13699            ctx.apply_scope_membership(&mut command);
13700            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
13701                Ok(true) => {
13702                    self.scheduled = true;
13703                    return Poll::Pending;
13704                }
13705                Ok(false) => {}
13706                Err(error) => return Poll::Ready(Err(error)),
13707            }
13708            if self.local {
13709                command.remove("queue");
13710                command.insert("execution_mode".into(), json!("local"));
13711                let result = Arc::new(Mutex::new(None));
13712                let command_index = state.commands.len();
13713                state.local_activity_requests.push(local_activity::Request {
13714                    command_index,
13715                    options,
13716                    arguments,
13717                    result: result.clone(),
13718                });
13719                self.local_result = Some(result);
13720            }
13721            state.commands.push(Value::Object(command));
13722            self.scheduled = true;
13723        }
13724
13725        Poll::Pending
13726    }
13727}
13728
13729impl Future for ActivityCall {
13730    type Output = Result<Value>;
13731
13732    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13733        match self.poll_avro_value(cx) {
13734            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
13735            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13736            Poll::Pending => Poll::Pending,
13737        }
13738    }
13739}
13740
13741/// Future returned by [`WorkflowContext::sleep`].
13742pub struct TimerCall {
13743    ctx: WorkflowContext,
13744    delay_seconds: Option<u64>,
13745    scheduled: bool,
13746    matched_pending: bool,
13747    parallel_group_path: Vec<ParallelGroupMetadata>,
13748}
13749
13750impl Future for TimerCall {
13751    type Output = Result<()>;
13752
13753    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13754        if self.matched_pending {
13755            return Poll::Pending;
13756        }
13757
13758        let ctx = self.ctx.clone();
13759        let Some(requested_delay) = self.delay_seconds else {
13760            return Poll::Ready(Err(Error::TimerDurationOverflow));
13761        };
13762        let mut state = match ctx.state.lock() {
13763            Ok(state) => state,
13764            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13765        };
13766
13767        let cursor = state.command_cursor;
13768        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13769            return Poll::Ready(Err(error));
13770        }
13771        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
13772        {
13773            Ok(recorded) => recorded,
13774            Err(error) => return Poll::Ready(Err(error)),
13775        };
13776        if let Some(recorded) = recorded {
13777            match recorded {
13778                RecordedCommand::Timer {
13779                    sequence,
13780                    delay_seconds,
13781                    fired,
13782                    parallel_group_path,
13783                    ..
13784                } => {
13785                    if let Err(error) =
13786                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
13787                    {
13788                        return Poll::Ready(Err(error));
13789                    }
13790                    if let Err(error) = ensure_parallel_path_matches(
13791                        sequence,
13792                        parallel_group_path.as_deref(),
13793                        &self.parallel_group_path,
13794                    ) {
13795                        return Poll::Ready(Err(error));
13796                    }
13797                    if delay_seconds != requested_delay {
13798                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13799                            ReplayFailure::new(
13800                                "timer_delay_mismatch",
13801                                Some(sequence),
13802                                Some(format!("timer:{delay_seconds}s")),
13803                                Some(format!("timer:{requested_delay}s")),
13804                                "recorded timer delay differs from the current workflow command",
13805                            ),
13806                        )));
13807                    }
13808                    if let Err(error) =
13809                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
13810                    {
13811                        return Poll::Ready(Err(error));
13812                    }
13813                    match state.prepare_scalar_cancellation(
13814                        cursor,
13815                        CancellationCallKind::Timer,
13816                        &self.parallel_group_path,
13817                    ) {
13818                        Ok(true) => {
13819                            self.scheduled = true;
13820                            self.matched_pending = true;
13821                            return Poll::Pending;
13822                        }
13823                        Ok(false) => {}
13824                        Err(error) => return Poll::Ready(Err(error)),
13825                    }
13826                    state.command_cursor += 1;
13827                    if fired {
13828                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13829                        return Poll::Ready(Ok(()));
13830                    }
13831                    state.matched_recorded_pending = true;
13832                    self.scheduled = true;
13833                    self.matched_pending = true;
13834                    return Poll::Pending;
13835                }
13836                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
13837            }
13838        }
13839
13840        if !self.scheduled {
13841            let mut command = serde_json::Map::from_iter([
13842                ("type".to_string(), json!("start_timer")),
13843                ("delay_seconds".to_string(), json!(requested_delay)),
13844            ]);
13845            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
13846                Ok(Some(proof)) => {
13847                    command.insert("cancellation_cleanup".into(), proof);
13848                }
13849                Ok(None) => {}
13850                Err(error) => return Poll::Ready(Err(error)),
13851            }
13852            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13853            ctx.apply_scope_membership(&mut command);
13854            match state.prepare_scalar_cancellation(
13855                cursor,
13856                CancellationCallKind::Timer,
13857                &self.parallel_group_path,
13858            ) {
13859                Ok(true) => {
13860                    self.scheduled = true;
13861                    self.matched_pending = true;
13862                    return Poll::Pending;
13863                }
13864                Ok(false) => {}
13865                Err(error) => return Poll::Ready(Err(error)),
13866            }
13867            state.commands.push(Value::Object(command));
13868            self.scheduled = true;
13869        }
13870
13871        Poll::Pending
13872    }
13873}
13874
13875/// Future returned by [`WorkflowContext::wait_condition`].
13876pub struct ConditionWaitCall {
13877    ctx: WorkflowContext,
13878    options: ConditionWaitOptions,
13879    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
13880    occurrence_id: Option<String>,
13881    opened_wait: bool,
13882    parallel_group_path: Vec<ParallelGroupMetadata>,
13883}
13884
13885impl Future for ConditionWaitCall {
13886    type Output = Result<ConditionWaitResult>;
13887
13888    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13889        if self.opened_wait {
13890            return Poll::Pending;
13891        }
13892
13893        let options = match self.options.validate() {
13894            Ok(options) => options,
13895            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
13896        };
13897        let ctx = self.ctx.clone();
13898        let occurrence_id = match self.occurrence_id.as_ref() {
13899            Some(occurrence_id) => occurrence_id.clone(),
13900            None => {
13901                let mut state = match ctx.state.lock() {
13902                    Ok(state) => state,
13903                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13904                };
13905                let ordinal = state.condition_wait_occurrence_counter;
13906                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
13907                    Some(next) => next,
13908                    None => {
13909                        return Poll::Ready(Err(Error::WorkerLoop(
13910                            "condition wait occurrence counter overflowed".to_string(),
13911                        )))
13912                    }
13913                };
13914                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
13915                drop(state);
13916                self.occurrence_id = Some(occurrence_id.clone());
13917                occurrence_id
13918            }
13919        };
13920
13921        let recorded_result = {
13922            let mut state = match ctx.state.lock() {
13923                Ok(state) => state,
13924                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13925            };
13926            let initial_cursor = state.command_cursor;
13927            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
13928                return Poll::Ready(Err(error));
13929            }
13930            let recorded = match state
13931                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
13932            {
13933                Ok(recorded) => recorded,
13934                Err(error) => return Poll::Ready(Err(error)),
13935            };
13936            let Some(recorded) = recorded else {
13937                drop(state);
13938                return self.poll_new_condition(options);
13939            };
13940            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
13941                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
13942            }
13943
13944            let mut cursor = state.command_cursor;
13945            let mut result = None;
13946            let mut pending_delivery = false;
13947            loop {
13948                if cursor > initial_cursor
13949                    && matches!(
13950                        state.recorded_commands.get(cursor),
13951                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
13952                    )
13953                {
13954                    break;
13955                }
13956                let recorded = match state
13957                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
13958                {
13959                    Ok(recorded) => recorded,
13960                    Err(error) => return Poll::Ready(Err(error)),
13961                };
13962                let Some(RecordedCommand::ConditionWait {
13963                    sequence,
13964                    occurrence_id: ref recorded_occurrence_id,
13965                    ref condition_key,
13966                    ref predicate_identity,
13967                    timeout_seconds,
13968                    result: recorded_result,
13969                    ref parallel_group_path,
13970                    ..
13971                }) = recorded
13972                else {
13973                    break;
13974                };
13975
13976                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
13977                    break;
13978                }
13979                if let Err(error) = ensure_parallel_path_matches(
13980                    sequence,
13981                    parallel_group_path.as_deref(),
13982                    &self.parallel_group_path,
13983                ) {
13984                    return Poll::Ready(Err(error));
13985                }
13986                if let Err(error) = validate_recorded_condition_wait(
13987                    sequence,
13988                    recorded_occurrence_id,
13989                    condition_key.as_deref(),
13990                    predicate_identity,
13991                    timeout_seconds,
13992                    &occurrence_id,
13993                    &options,
13994                ) {
13995                    return Poll::Ready(Err(error));
13996                }
13997                if result == Some(ConditionWaitResult::TimedOut) {
13998                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
13999                        "condition_wait_reopened_after_timeout",
14000                        Some(sequence),
14001                        Some("timed-out condition is terminal".to_string()),
14002                        Some("another physical wait-open".to_string()),
14003                        "condition history reopened one logical wait after its durable timeout",
14004                    ))));
14005                }
14006                if let Err(error) =
14007                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14008                {
14009                    return Poll::Ready(Err(error));
14010                }
14011                match state.prepare_scalar_cancellation(
14012                    cursor,
14013                    CancellationCallKind::Condition,
14014                    &self.parallel_group_path,
14015                ) {
14016                    Ok(pending) => pending_delivery |= pending,
14017                    Err(error) => return Poll::Ready(Err(error)),
14018                }
14019                result = recorded_result;
14020                if result.is_some() {
14021                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14022                }
14023                cursor += 1;
14024            }
14025            state.command_cursor = cursor;
14026            if pending_delivery {
14027                self.opened_wait = true;
14028                return Poll::Pending;
14029            }
14030            result
14031        };
14032
14033        if let Some(result) = recorded_result {
14034            return Poll::Ready(Ok(result));
14035        }
14036
14037        self.poll_open_condition(options, true)
14038    }
14039}
14040
14041impl ConditionWaitCall {
14042    fn poll_new_condition(
14043        self: Pin<&mut Self>,
14044        options: ValidatedConditionWaitOptions,
14045    ) -> Poll<Result<ConditionWaitResult>> {
14046        self.poll_open_condition(options, false)
14047    }
14048
14049    fn poll_open_condition(
14050        mut self: Pin<&mut Self>,
14051        options: ValidatedConditionWaitOptions,
14052        recorded_wait: bool,
14053    ) -> Poll<Result<ConditionWaitResult>> {
14054        {
14055            let ctx = self.ctx.clone();
14056            let mut state = match ctx.state.lock() {
14057                Ok(state) => state,
14058                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14059            };
14060            let cursor = state.command_cursor;
14061            match state.prepare_scalar_cancellation(
14062                cursor,
14063                CancellationCallKind::Condition,
14064                &self.parallel_group_path,
14065            ) {
14066                Ok(true) => {
14067                    self.opened_wait = true;
14068                    return Poll::Pending;
14069                }
14070                Ok(false) => {}
14071                Err(error) => return Poll::Ready(Err(error)),
14072            }
14073        }
14074        let selection_member = self
14075            .parallel_group_path
14076            .first()
14077            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14078        match (self.predicate)() {
14079            Ok(true) if !selection_member || recorded_wait => {
14080                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14081            }
14082            Ok(_) => {}
14083            Err(error) => return Poll::Ready(Err(error)),
14084        }
14085        if options.timeout_seconds == Some(0) && !selection_member {
14086            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14087        }
14088
14089        let ctx = self.ctx.clone();
14090        let mut state = match ctx.state.lock() {
14091            Ok(state) => state,
14092            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14093        };
14094        let mut command = serde_json::Map::from_iter([
14095            ("type".to_string(), json!("open_condition_wait")),
14096            (
14097                "condition_wait_occurrence_id".to_string(),
14098                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14099            ),
14100            ("condition_key".to_string(), json!(options.condition_key)),
14101            (
14102                "condition_definition_fingerprint".to_string(),
14103                json!(options.predicate_identity),
14104            ),
14105        ]);
14106        if let Some(timeout_seconds) = options.timeout_seconds {
14107            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14108        }
14109        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14110        ctx.apply_scope_membership(&mut command);
14111        state.commands.push(Value::Object(command));
14112        drop(state);
14113        self.opened_wait = true;
14114        Poll::Pending
14115    }
14116}
14117
14118fn validate_recorded_condition_wait(
14119    sequence: u64,
14120    recorded_occurrence_id: &str,
14121    recorded_key: Option<&str>,
14122    recorded_predicate_identity: &str,
14123    recorded_timeout_seconds: Option<u64>,
14124    current_occurrence_id: &str,
14125    current: &ValidatedConditionWaitOptions,
14126) -> Result<()> {
14127    if recorded_occurrence_id != current_occurrence_id {
14128        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14129            "condition_wait_occurrence_mismatch",
14130            Some(sequence),
14131            Some(recorded_occurrence_id.to_string()),
14132            Some(current_occurrence_id.to_string()),
14133            "recorded condition occurrence differs from the current authored wait position",
14134        )));
14135    }
14136    if recorded_key != Some(current.condition_key.as_str()) {
14137        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14138            "condition_wait_key_mismatch",
14139            Some(sequence),
14140            recorded_key.map(str::to_string),
14141            Some(current.condition_key.clone()),
14142            "recorded condition identity differs from the current workflow wait",
14143        )));
14144    }
14145    if recorded_predicate_identity != current.predicate_identity {
14146        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14147            "condition_wait_predicate_mismatch",
14148            Some(sequence),
14149            Some(recorded_predicate_identity.to_string()),
14150            Some(current.predicate_identity.clone()),
14151            "recorded condition predicate behavior differs from current workflow code",
14152        )));
14153    }
14154    if recorded_timeout_seconds != current.timeout_seconds {
14155        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14156            "condition_wait_timeout_mismatch",
14157            Some(sequence),
14158            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14159            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14160            "recorded condition timeout differs from the current workflow wait",
14161        )));
14162    }
14163    Ok(())
14164}
14165
14166/// Future returned by [`WorkflowContext::start_child_workflow`].
14167pub struct ChildWorkflowCall {
14168    ctx: WorkflowContext,
14169    workflow_type: String,
14170    options: ChildWorkflowOptions,
14171    args: Option<Result<AvroValue>>,
14172    scheduled: bool,
14173    matched_pending: bool,
14174    parallel_group_path: Vec<ParallelGroupMetadata>,
14175}
14176
14177impl ChildWorkflowCall {
14178    fn poll_avro_value(
14179        mut self: Pin<&mut Self>,
14180        _cx: &mut TaskContext<'_>,
14181    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14182        if self.matched_pending {
14183            return Poll::Pending;
14184        }
14185
14186        let ctx = self.ctx.clone();
14187        let mut state = match ctx.state.lock() {
14188            Ok(state) => state,
14189            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14190        };
14191
14192        let cursor = state.command_cursor;
14193        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14194            return Poll::Ready(Err(error));
14195        }
14196        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14197        {
14198            Ok(recorded) => recorded,
14199            Err(error) => return Poll::Ready(Err(error)),
14200        };
14201        if let Some(recorded) = recorded {
14202            let sequence = recorded.sequence();
14203            match recorded {
14204                RecordedCommand::ChildWorkflow {
14205                    workflow_type,
14206                    policies,
14207                    outcome,
14208                    parallel_group_path,
14209                    ..
14210                } => {
14211                    if let Err(error) = ensure_parallel_path_matches(
14212                        sequence,
14213                        parallel_group_path.as_deref(),
14214                        &self.parallel_group_path,
14215                    ) {
14216                        return Poll::Ready(Err(error));
14217                    }
14218                    if let Some(recorded_type) = workflow_type {
14219                        if recorded_type != self.workflow_type {
14220                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14221                                ReplayFailure::new(
14222                                    "recorded_command_detail_mismatch",
14223                                    Some(sequence),
14224                                    Some(format!("child workflow:{recorded_type}")),
14225                                    Some(format!("child workflow:{}", self.workflow_type)),
14226                                    "recorded child workflow type differs from the current workflow command",
14227                                ),
14228                            )));
14229                        }
14230                    }
14231                    if let Err(error) =
14232                        ensure_child_policies_match(sequence, &policies, &self.options)
14233                    {
14234                        return Poll::Ready(Err(error));
14235                    }
14236                    if let Err(error) =
14237                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14238                    {
14239                        return Poll::Ready(Err(error));
14240                    }
14241                    match state.prepare_scalar_cancellation(
14242                        cursor,
14243                        CancellationCallKind::Child,
14244                        &self.parallel_group_path,
14245                    ) {
14246                        Ok(true) => {
14247                            self.scheduled = true;
14248                            self.matched_pending = true;
14249                            return Poll::Pending;
14250                        }
14251                        Ok(false) => {}
14252                        Err(error) => return Poll::Ready(Err(error)),
14253                    }
14254                    state.command_cursor += 1;
14255                    if let Some(outcome) = outcome {
14256                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14257                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
14258                    }
14259                    state.matched_recorded_pending = true;
14260                    self.scheduled = true;
14261                    self.matched_pending = true;
14262                    return Poll::Pending;
14263                }
14264                other => {
14265                    return Poll::Ready(Err(command_mismatch(
14266                        &other,
14267                        format!("child workflow:{}", self.workflow_type),
14268                    )));
14269                }
14270            }
14271        }
14272
14273        if !self.scheduled {
14274            if self.options.task_queue.trim().is_empty() {
14275                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14276                    "task_queue must not be empty".to_string(),
14277                )));
14278            }
14279            for (name, value) in [
14280                (
14281                    "execution_timeout_seconds",
14282                    self.options.execution_timeout_seconds,
14283                ),
14284                ("run_timeout_seconds", self.options.run_timeout_seconds),
14285            ] {
14286                if value == Some(0) {
14287                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
14288                        "{name} must be at least 1"
14289                    ))));
14290                }
14291            }
14292
14293            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14294                Ok(args) => args,
14295                Err(error) => return Poll::Ready(Err(error)),
14296            };
14297            let arguments = match encode_typed_envelope(
14298                &normalize_avro_arguments(args),
14299                &state.payload_codec,
14300            ) {
14301                Ok(arguments) => arguments,
14302                Err(error) => return Poll::Ready(Err(error)),
14303            };
14304            let mut command = json!({
14305                "type": "start_child_workflow",
14306                "workflow_type": self.workflow_type,
14307                "queue": self.options.task_queue,
14308                "parent_close_policy": self.options.parent_close_policy.as_str(),
14309                "arguments": arguments,
14310            });
14311            let object = command
14312                .as_object_mut()
14313                .expect("child workflow command is always an object");
14314            if self.options.cancellation_policy != CancellationPolicy::Abandon {
14315                object.insert(
14316                    "cancellation_policy".to_string(),
14317                    json!(self.options.cancellation_policy.as_str()),
14318                );
14319            }
14320            if let Some(policy) = &self.options.retry_policy {
14321                let mut retry_policy = serde_json::Map::new();
14322                if let Some(max_attempts) = policy.max_attempts {
14323                    if max_attempts == 0 {
14324                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14325                            "retry_policy.max_attempts must be at least 1".to_string(),
14326                        )));
14327                    }
14328                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
14329                }
14330                if !policy.backoff_seconds.is_empty() {
14331                    retry_policy
14332                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
14333                }
14334                if !policy.non_retryable_error_types.is_empty() {
14335                    retry_policy.insert(
14336                        "non_retryable_error_types".to_string(),
14337                        json!(policy.non_retryable_error_types),
14338                    );
14339                }
14340                if retry_policy.is_empty() {
14341                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14342                        "retry_policy must configure at least one field".to_string(),
14343                    )));
14344                }
14345                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
14346            }
14347            if let Some(seconds) = self.options.execution_timeout_seconds {
14348                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
14349            }
14350            if let Some(seconds) = self.options.run_timeout_seconds {
14351                object.insert("run_timeout_seconds".to_string(), json!(seconds));
14352            }
14353            apply_parallel_group_path(object, &self.parallel_group_path);
14354            ctx.apply_scope_membership(object);
14355            match state.prepare_scalar_cancellation(
14356                cursor,
14357                CancellationCallKind::Child,
14358                &self.parallel_group_path,
14359            ) {
14360                Ok(true) => {
14361                    self.scheduled = true;
14362                    self.matched_pending = true;
14363                    return Poll::Pending;
14364                }
14365                Ok(false) => {}
14366                Err(error) => return Poll::Ready(Err(error)),
14367            }
14368            state.commands.push(command);
14369            self.scheduled = true;
14370        }
14371
14372        Poll::Pending
14373    }
14374}
14375
14376impl Future for ChildWorkflowCall {
14377    type Output = Result<ChildWorkflowResult>;
14378
14379    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14380        match self.poll_avro_value(cx) {
14381            Poll::Ready(Ok(result)) => match result.result.into_json() {
14382                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
14383                    parent: result.parent,
14384                    child: result.child,
14385                    child_workflow_type: result.child_workflow_type,
14386                    result: projected,
14387                })),
14388                Err(error) => Poll::Ready(Err(error)),
14389            },
14390            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14391            Poll::Pending => Poll::Pending,
14392        }
14393    }
14394}
14395
14396fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
14397    Error::NonDeterministicReplay(ReplayFailure::new(
14398        "recorded_command_mismatch",
14399        Some(recorded.sequence()),
14400        Some(recorded.shape().to_string()),
14401        Some(actual.into()),
14402        "current workflow command does not match the recorded durable command sequence",
14403    ))
14404}
14405
14406pub struct SignalCall {
14407    ctx: WorkflowContext,
14408    signal_name: String,
14409    runtime_reserved_allowed: bool,
14410    opened_wait: bool,
14411    matched_pending: bool,
14412    parallel_group_path: Vec<ParallelGroupMetadata>,
14413}
14414
14415impl SignalCall {
14416    fn poll_avro_value(
14417        mut self: Pin<&mut Self>,
14418        _cx: &mut TaskContext<'_>,
14419    ) -> Poll<Result<Vec<AvroValue>>> {
14420        if self.matched_pending {
14421            return Poll::Pending;
14422        }
14423        if !self.runtime_reserved_allowed {
14424            if let Err(error) = validate_user_signal_name(&self.signal_name) {
14425                return Poll::Ready(Err(error));
14426            }
14427        }
14428
14429        let ctx = self.ctx.clone();
14430        let mut state = match ctx.state.lock() {
14431            Ok(state) => state,
14432            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14433        };
14434
14435        let cursor = state.command_cursor;
14436        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14437            return Poll::Ready(Err(error));
14438        }
14439        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
14440        {
14441            Ok(recorded) => recorded,
14442            Err(error) => return Poll::Ready(Err(error)),
14443        };
14444        if let Some(recorded) = recorded {
14445            match recorded {
14446                RecordedCommand::SignalWait {
14447                    sequence,
14448                    signal_name,
14449                    value,
14450                    parallel_group_path,
14451                } => {
14452                    if let Err(error) = ensure_parallel_path_matches(
14453                        sequence,
14454                        parallel_group_path.as_deref(),
14455                        &self.parallel_group_path,
14456                    ) {
14457                        return Poll::Ready(Err(error));
14458                    }
14459                    if signal_name != self.signal_name {
14460                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14461                            ReplayFailure::new(
14462                                "recorded_command_detail_mismatch",
14463                                Some(sequence),
14464                                Some(format!("signal wait:{signal_name}")),
14465                                Some(format!("signal wait:{}", self.signal_name)),
14466                                "recorded signal name differs from the current workflow command",
14467                            ),
14468                        )));
14469                    }
14470
14471                    if let Err(error) =
14472                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
14473                    {
14474                        return Poll::Ready(Err(error));
14475                    }
14476                    match state.prepare_scalar_cancellation(
14477                        cursor,
14478                        CancellationCallKind::Signal,
14479                        &self.parallel_group_path,
14480                    ) {
14481                        Ok(true) => {
14482                            self.opened_wait = true;
14483                            self.matched_pending = true;
14484                            return Poll::Pending;
14485                        }
14486                        Ok(false) => {}
14487                        Err(error) => return Poll::Ready(Err(error)),
14488                    }
14489                    state.command_cursor += 1;
14490                    if let Some(value) = value {
14491                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14492                        return Poll::Ready(Ok(value));
14493                    }
14494                    if state
14495                        .resume_signal
14496                        .as_ref()
14497                        .is_some_and(|signal| signal.signal_name == self.signal_name)
14498                    {
14499                        let signal = state
14500                            .resume_signal
14501                            .take()
14502                            .expect("matching resume signal is present");
14503                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
14504                        return Poll::Ready(Ok(signal.arguments));
14505                    }
14506
14507                    state.matched_recorded_pending = true;
14508                    self.opened_wait = true;
14509                    self.matched_pending = true;
14510                    return Poll::Pending;
14511                }
14512                other => {
14513                    return Poll::Ready(Err(command_mismatch(
14514                        &other,
14515                        format!("signal wait:{}", self.signal_name),
14516                    )));
14517                }
14518            }
14519        }
14520
14521        match state.prepare_scalar_cancellation(
14522            cursor,
14523            CancellationCallKind::Signal,
14524            &self.parallel_group_path,
14525        ) {
14526            Ok(true) => {
14527                self.opened_wait = true;
14528                self.matched_pending = true;
14529                return Poll::Pending;
14530            }
14531            Ok(false) => {}
14532            Err(error) => return Poll::Ready(Err(error)),
14533        }
14534
14535        if state
14536            .resume_signal
14537            .as_ref()
14538            .is_some_and(|signal| signal.signal_name == self.signal_name)
14539        {
14540            let signal = state
14541                .resume_signal
14542                .take()
14543                .expect("matching resume signal is present");
14544            state.unavailable_cancellation_boundary(&self.parallel_group_path);
14545            return Poll::Ready(Ok(signal.arguments));
14546        }
14547
14548        if !self.opened_wait {
14549            let mut command = serde_json::Map::from_iter([
14550                ("type".to_string(), json!("open_signal_wait")),
14551                ("signal_name".to_string(), json!(self.signal_name)),
14552            ]);
14553            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14554            ctx.apply_scope_membership(&mut command);
14555            state.commands.push(Value::Object(command));
14556            self.opened_wait = true;
14557        }
14558
14559        Poll::Pending
14560    }
14561}
14562
14563impl Future for SignalCall {
14564    type Output = Result<Vec<Value>>;
14565
14566    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14567        match self.poll_avro_value(cx) {
14568            Poll::Ready(Ok(values)) => Poll::Ready(
14569                values
14570                    .into_iter()
14571                    .map(AvroValue::into_json)
14572                    .collect::<Result<Vec<_>>>(),
14573            ),
14574            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14575            Poll::Pending => Poll::Pending,
14576        }
14577    }
14578}
14579
14580#[derive(Clone, Debug)]
14581pub struct ActivityContext {
14582    client: Client,
14583    pub task_id: String,
14584    pub activity_attempt_id: String,
14585    pub lease_owner: String,
14586    pub activity_type: String,
14587    pub attempt_number: u64,
14588    pub task_queue: String,
14589    pub worker_id: String,
14590    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
14591    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
14592    worker_session: Option<WorkerSession>,
14593}
14594
14595impl ActivityContext {
14596    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
14597        if let Some(heartbeats) = &self.local_heartbeats {
14598            return heartbeats
14599                .lock()
14600                .map_err(|_| Error::WorkflowStatePoisoned)?
14601                .record(details);
14602        }
14603        if let Some(guard) = &self.claim_guard {
14604            return guard.heartbeat(self, details).await;
14605        }
14606        if let Some(session) = &self.worker_session {
14607            if !session.active() {
14608                return Err(Error::ActivityExecutionAbandoned(
14609                    "worker-session lease or TTL is no longer active".into(),
14610                ));
14611            }
14612            let result = self
14613                .client
14614                .heartbeat_activity_task_value(
14615                    &self.task_id,
14616                    &self.activity_attempt_id,
14617                    &self.lease_owner,
14618                    details,
14619                )
14620                .await;
14621            return worker_session::settle_activity_heartbeat(
14622                session,
14623                result,
14624                &self.task_id,
14625                &self.activity_attempt_id,
14626                &self.lease_owner,
14627            );
14628        }
14629        self.client
14630            .heartbeat_activity_task(
14631                &self.task_id,
14632                &self.activity_attempt_id,
14633                &self.lease_owner,
14634                details,
14635            )
14636            .await
14637    }
14638}
14639
14640fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
14641    validate_payload_codec(codec)?;
14642    match value {
14643        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
14644            value, codec,
14645        )?)),
14646        None => Ok(AvroValue::Array(Vec::new())),
14647    }
14648}
14649
14650fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
14651    let Some(signal_name) = task
14652        .signal_name
14653        .as_deref()
14654        .filter(|value| !value.is_empty())
14655    else {
14656        return Ok(None);
14657    };
14658    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
14659    let AvroValue::Array(arguments) = decoded else {
14660        unreachable!("normalize_avro_arguments always returns an array");
14661    };
14662
14663    Ok(Some(ResumeSignal {
14664        signal_name: signal_name.to_string(),
14665        arguments,
14666    }))
14667}
14668
14669fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
14670    validate_payload_codec(&task.payload_codec)?;
14671    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
14672    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
14673    for event in &task.history_events {
14674        validate_history_event_payloads(event, &task.payload_codec)?;
14675    }
14676    Ok(())
14677}
14678
14679fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
14680    validate_payload_codec(&task.payload_codec)?;
14681    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
14682}
14683
14684fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
14685    validate_payload_codec(&task.payload_codec)?;
14686    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
14687    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
14688    for event in &task.history_events {
14689        validate_history_event_payloads(event, &task.payload_codec)?;
14690    }
14691
14692    let Some(export) = task.history_export.as_ref() else {
14693        return Ok(());
14694    };
14695    let export_codec = match export.get("payloads") {
14696        Some(payloads) => declared_payload_codec(payloads, "codec")?,
14697        None => None,
14698    }
14699    .unwrap_or(&task.payload_codec);
14700    validate_payload_codec(export_codec)?;
14701
14702    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
14703        for event in events {
14704            let event_type = event
14705                .get("event_type")
14706                .or_else(|| event.get("type"))
14707                .and_then(Value::as_str)
14708                .unwrap_or_default();
14709            if let Some(payload) = event.get("payload") {
14710                validate_history_payloads(event_type, payload, export_codec)?;
14711            }
14712        }
14713    }
14714    for signal in export
14715        .get("signals")
14716        .and_then(Value::as_array)
14717        .into_iter()
14718        .flatten()
14719    {
14720        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
14721        validate_payload_codec(codec)?;
14722        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
14723    }
14724    for activity in export
14725        .get("activities")
14726        .and_then(Value::as_array)
14727        .into_iter()
14728        .flatten()
14729    {
14730        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
14731        validate_payload_codec(codec)?;
14732        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
14733        validate_optional_inbound_payload(activity.get("result"), codec)?;
14734    }
14735    Ok(())
14736}
14737
14738fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
14739    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
14740}
14741
14742fn validate_history_payloads(
14743    event_type: &str,
14744    payload: &Value,
14745    fallback_codec: &str,
14746) -> Result<()> {
14747    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
14748    validate_payload_codec(codec)?;
14749    for field in history_payload_fields(event_type) {
14750        validate_optional_inbound_payload(payload.get(*field), codec)?;
14751    }
14752    Ok(())
14753}
14754
14755const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
14756
14757fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
14758    match event_type {
14759        "ActivityCompleted" => &["result"],
14760        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
14761        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
14762        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
14763        "ChildRunCompleted" => &["result", "output"],
14764        "WorkflowCompleted" => &["output"],
14765        "ServiceCallStarted"
14766        | "ServiceCallCompleted"
14767        | "ServiceCallFailed"
14768        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
14769        _ => &[],
14770    }
14771}
14772
14773fn signal_history_payload(payload: &Value) -> Option<&Value> {
14774    SIGNAL_HISTORY_PAYLOAD_FIELDS
14775        .iter()
14776        .find_map(|field| payload.get(*field))
14777}
14778
14779fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
14780    match value.get(field) {
14781        None => Ok(None),
14782        Some(Value::String(codec)) => Ok(Some(codec)),
14783        Some(_) => Err(invalid_payload_envelope()),
14784    }
14785}
14786
14787fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
14788    validate_payload_codec(codec)?;
14789    if let Some(value) = value.filter(|value| !value.is_null()) {
14790        decode_wire_avro_value(value, codec)?;
14791    }
14792    Ok(())
14793}
14794
14795fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
14796    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
14797        invalid_recorded_history(
14798            "parallel_group_metadata_invalid",
14799            sequence,
14800            "non-empty parallel_group_id",
14801            &payload.to_string(),
14802            "parallel-group history is missing its stable identity",
14803        )
14804    })?;
14805    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
14806        invalid_recorded_history(
14807            "parallel_group_metadata_invalid",
14808            sequence,
14809            "activity, child, timer, signal, condition, or mixed group kind",
14810            &payload.to_string(),
14811            "parallel-group history is missing its group kind",
14812        )
14813    })?;
14814    if !matches!(
14815        kind.as_str(),
14816        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
14817    ) {
14818        return Err(invalid_recorded_history(
14819            "parallel_group_metadata_invalid",
14820            sequence,
14821            "activity, child, timer, signal, condition, or mixed group kind",
14822            &kind,
14823            "parallel-group history contains an unsupported group kind",
14824        ));
14825    }
14826    let base_sequence = payload
14827        .get("parallel_group_base_sequence")
14828        .and_then(value_as_u64)
14829        .filter(|value| *value > 0)
14830        .ok_or_else(|| {
14831            invalid_recorded_history(
14832                "parallel_group_metadata_invalid",
14833                sequence,
14834                "positive parallel_group_base_sequence",
14835                &payload.to_string(),
14836                "parallel-group history contains an invalid base sequence",
14837            )
14838        })?;
14839    let size = payload
14840        .get("parallel_group_size")
14841        .and_then(value_as_u64)
14842        .and_then(|value| usize::try_from(value).ok())
14843        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
14844        .ok_or_else(|| {
14845            invalid_recorded_history(
14846                "parallel_group_metadata_invalid",
14847                sequence,
14848                "bounded positive parallel_group_size",
14849                &payload.to_string(),
14850                "parallel-group history contains an invalid group size",
14851            )
14852        })?;
14853    let index = payload
14854        .get("parallel_group_index")
14855        .and_then(value_as_u64)
14856        .and_then(|value| usize::try_from(value).ok())
14857        .filter(|value| *value < size)
14858        .ok_or_else(|| {
14859            invalid_recorded_history(
14860                "parallel_group_metadata_invalid",
14861                sequence,
14862                "parallel_group_index within group bounds",
14863                &payload.to_string(),
14864                "parallel-group history contains an invalid member index",
14865            )
14866        })?;
14867    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
14868        return Err(invalid_recorded_history(
14869            "parallel_group_metadata_invalid",
14870            sequence,
14871            "base sequence plus member index equals workflow sequence",
14872            &payload.to_string(),
14873            "parallel-group path does not preserve durable workflow position",
14874        ));
14875    }
14876    let mode = payload
14877        .get("parallel_group_mode")
14878        .and_then(Value::as_str)
14879        .unwrap_or("all");
14880    if !matches!(mode, "all" | "select") {
14881        return Err(invalid_recorded_history(
14882            "parallel_group_metadata_invalid",
14883            sequence,
14884            "parallel group mode all or select",
14885            mode,
14886            "parallel-group history contains an unsupported group mode",
14887        ));
14888    }
14889    let expected_id = if mode == "select" {
14890        format!("select-calls:{base_sequence}:{size}")
14891    } else {
14892        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
14893    };
14894    if group_id != expected_id {
14895        return Err(invalid_recorded_history(
14896            "parallel_group_metadata_invalid",
14897            sequence,
14898            &expected_id,
14899            &group_id,
14900            "parallel-group history contains an incompatible stable group ID",
14901        ));
14902    }
14903    let selection_member_key = if mode == "select" {
14904        Some(selection_key_from_value(
14905            payload.get("selection_member_key"),
14906            sequence,
14907        )?)
14908    } else {
14909        None
14910    };
14911    let selection_member_index = if mode == "select" {
14912        Some(required_parallel_usize(
14913            payload,
14914            "selection_member_index",
14915            sequence,
14916        )?)
14917    } else {
14918        None
14919    };
14920    let selection_member_base_sequence = if mode == "select" {
14921        Some(
14922            payload
14923                .get("selection_member_base_sequence")
14924                .and_then(value_as_u64)
14925                .filter(|value| *value >= base_sequence)
14926                .ok_or_else(|| {
14927                    invalid_recorded_history(
14928                        "parallel_group_metadata_invalid",
14929                        sequence,
14930                        "selection member base within its group",
14931                        &payload.to_string(),
14932                        "selection history contains an invalid member base sequence",
14933                    )
14934                })?,
14935        )
14936    } else {
14937        None
14938    };
14939    let selection_member_size = if mode == "select" {
14940        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
14941        if member_size == 0 {
14942            return Err(invalid_recorded_history(
14943                "parallel_group_metadata_invalid",
14944                sequence,
14945                "positive selection member size",
14946                &payload.to_string(),
14947                "selection history contains an invalid member size",
14948            ));
14949        }
14950        Some(member_size)
14951    } else {
14952        None
14953    };
14954    let selection_member_kind = if mode == "select" {
14955        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
14956            invalid_recorded_history(
14957                "parallel_group_metadata_invalid",
14958                sequence,
14959                "selection member operation kind",
14960                &payload.to_string(),
14961                "selection history is missing its authored member kind",
14962            )
14963        })?;
14964        if !matches!(
14965            kind.as_str(),
14966            "activity" | "child" | "timer" | "signal" | "condition" | "group"
14967        ) {
14968            return Err(invalid_recorded_history(
14969                "parallel_group_metadata_invalid",
14970                sequence,
14971                "activity, child, timer, signal, condition, or group selection member kind",
14972                &kind,
14973                "selection history contains an unsupported member kind",
14974            ));
14975        }
14976        Some(kind)
14977    } else {
14978        None
14979    };
14980    if let (Some(member_base), Some(member_size)) =
14981        (selection_member_base_sequence, selection_member_size)
14982    {
14983        let member_end = member_base
14984            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
14985            .ok_or_else(|| {
14986                invalid_recorded_history(
14987                    "parallel_group_metadata_invalid",
14988                    sequence,
14989                    "bounded selection member range",
14990                    &payload.to_string(),
14991                    "selection member range overflowed",
14992                )
14993            })?;
14994        let group_end = base_sequence
14995            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
14996            .unwrap_or(u64::MAX);
14997        if sequence < member_base || sequence >= member_end || member_end > group_end {
14998            return Err(invalid_recorded_history(
14999                "parallel_group_metadata_invalid",
15000                sequence,
15001                "workflow sequence within one bounded selection member",
15002                &payload.to_string(),
15003                "selection member range does not contain its durable leaf",
15004            ));
15005        }
15006    }
15007    Ok(ParallelGroupMetadata {
15008        parallel_group_id: group_id,
15009        parallel_group_kind: kind,
15010        parallel_group_base_sequence: base_sequence,
15011        parallel_group_size: size,
15012        parallel_group_index: index,
15013        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15014        selection_member_key,
15015        selection_member_index,
15016        selection_member_base_sequence,
15017        selection_member_size,
15018        selection_member_kind,
15019    })
15020}
15021
15022fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15023    payload
15024        .get(field)
15025        .and_then(value_as_u64)
15026        .and_then(|value| usize::try_from(value).ok())
15027        .ok_or_else(|| {
15028            invalid_recorded_history(
15029                "parallel_group_metadata_invalid",
15030                sequence,
15031                &format!("non-negative integer {field}"),
15032                &payload.to_string(),
15033                "selection history contains invalid member metadata",
15034            )
15035        })
15036}
15037
15038fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15039    match value {
15040        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15041        Some(value) => value_as_u64(value)
15042            .and_then(|value| usize::try_from(value).ok())
15043            .map(SelectionKey::Index)
15044            .ok_or_else(|| {
15045                invalid_recorded_history(
15046                    "selection_member_key_invalid",
15047                    sequence,
15048                    "non-empty string or non-negative integer member key",
15049                    &value.to_string(),
15050                    "selection history contains an invalid member key",
15051                )
15052            }),
15053        None => Err(invalid_recorded_history(
15054            "selection_member_key_missing",
15055            sequence,
15056            "selection_member_key",
15057            "<missing>",
15058            "selection history is missing its stable member key",
15059        )),
15060    }
15061}
15062
15063fn recorded_parallel_group_path(
15064    events: &[&HistoryEvent],
15065    sequence: u64,
15066) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15067    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15068    for event in events {
15069        let payload = &event.payload;
15070        let has_metadata = payload.get("parallel_group_path").is_some()
15071            || payload.get("parallel_group_id").is_some()
15072            || payload.get("parallel_group_kind").is_some()
15073            || payload.get("parallel_group_base_sequence").is_some()
15074            || payload.get("parallel_group_size").is_some()
15075            || payload.get("parallel_group_index").is_some()
15076            || payload.get("parallel_group_mode").is_some()
15077            || payload.get("selection_member_key").is_some();
15078        if !has_metadata {
15079            continue;
15080        }
15081
15082        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15083        let path = match payload.get("parallel_group_path") {
15084            None => vec![top_level.clone()],
15085            Some(Value::Array(entries)) if !entries.is_empty() => entries
15086                .iter()
15087                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15088                .collect::<Result<Vec<_>>>()?,
15089            Some(value) => {
15090                return Err(invalid_recorded_history(
15091                    "parallel_group_metadata_invalid",
15092                    sequence,
15093                    "non-empty parallel_group_path list",
15094                    &value.to_string(),
15095                    "parallel-group history contains an invalid group path",
15096                ));
15097            }
15098        };
15099        if path.last() != Some(&top_level) {
15100            return Err(invalid_recorded_history(
15101                "parallel_group_metadata_invalid",
15102                sequence,
15103                &serde_json::to_string(&path.last()).unwrap_or_default(),
15104                &serde_json::to_string(&top_level).unwrap_or_default(),
15105                "parallel-group top-level fields do not match the innermost path entry",
15106            ));
15107        }
15108        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15109            return Err(invalid_recorded_history(
15110                "parallel_group_history_conflict",
15111                sequence,
15112                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15113                &serde_json::to_string(&path).unwrap_or_default(),
15114                "parallel-group metadata changed between scheduling and resolution history",
15115            ));
15116        }
15117        recorded = Some(path);
15118    }
15119    Ok(recorded)
15120}
15121
15122fn recorded_commands(
15123    events: &[HistoryEvent],
15124    fallback_codec: &str,
15125    parent: WorkflowIdentity,
15126) -> Result<Vec<RecordedCommand>> {
15127    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15128    let mut last_new_sequence = None;
15129
15130    for event in events {
15131        let is_activity = matches!(
15132            event.event_type.as_str(),
15133            "ActivityScheduled"
15134                | "ActivityStarted"
15135                | "ActivityHeartbeatRecorded"
15136                | "ActivityRetryScheduled"
15137                | "ActivityCompleted"
15138                | "ActivityFailed"
15139                | "ActivityCancelled"
15140                | "ActivityTimedOut"
15141        );
15142        let is_workflow_timer = matches!(
15143            event.event_type.as_str(),
15144            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15145        ) && !is_internal_timer_event(event);
15146        let is_child_workflow = matches!(
15147            event.event_type.as_str(),
15148            "ChildWorkflowScheduled"
15149                | "ChildRunStarted"
15150                | "ChildRunCompleted"
15151                | "ChildRunFailed"
15152                | "ChildRunCancelled"
15153                | "ChildRunTerminated"
15154        );
15155        let is_signal_wait = is_recorded_signal_wait_event(event);
15156        let is_condition_wait = is_recorded_condition_wait_event(event);
15157        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15158        let is_side_effect = event.event_type == "SideEffectRecorded";
15159        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15160        let is_memo = event.event_type == "MemoUpserted";
15161        if !is_activity
15162            && !is_workflow_timer
15163            && !is_child_workflow
15164            && !is_signal_wait
15165            && !is_condition_wait
15166            && !is_search_attributes
15167            && !is_side_effect
15168            && !is_version_marker
15169            && !is_memo
15170        {
15171            continue;
15172        }
15173
15174        let sequence = durable_event_sequence(event).ok_or_else(|| {
15175            Error::NonDeterministicReplay(ReplayFailure::new(
15176                "durable_command_sequence_missing",
15177                None,
15178                Some("positive workflow sequence".to_string()),
15179                Some(event.event_type.clone()),
15180                "durable command history event has no workflow sequence",
15181            ))
15182        })?;
15183        if sequence == 0 {
15184            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15185                "durable_command_sequence_invalid",
15186                Some(sequence),
15187                Some("positive workflow sequence".to_string()),
15188                Some(sequence.to_string()),
15189                "durable command history uses an invalid workflow sequence",
15190            )));
15191        }
15192        if !events_by_sequence.contains_key(&sequence) {
15193            if let Some(previous) = last_new_sequence {
15194                if sequence < previous {
15195                    return Err(invalid_recorded_history(
15196                        "durable_command_sequence_mismatch",
15197                        sequence,
15198                        &format!("workflow sequence greater than {previous}"),
15199                        &sequence.to_string(),
15200                        "durable commands are not strictly ordered by their recorded workflow sequence",
15201                    ));
15202                }
15203            }
15204            last_new_sequence = Some(sequence);
15205        }
15206        events_by_sequence.entry(sequence).or_default().push(event);
15207    }
15208
15209    let commands: Vec<RecordedCommand> = events_by_sequence
15210        .into_iter()
15211        .map(|(sequence, sequence_events)| {
15212            let activity_events: Vec<_> = sequence_events
15213                .iter()
15214                .copied()
15215                .filter(|event| event.event_type.starts_with("Activity"))
15216                .collect();
15217            let timer_events: Vec<_> = sequence_events
15218                .iter()
15219                .copied()
15220                .filter(|event| event.event_type.starts_with("Timer"))
15221                .collect();
15222            let child_events: Vec<_> = sequence_events
15223                .iter()
15224                .copied()
15225                .filter(|event| {
15226                    event.event_type == "ChildWorkflowScheduled"
15227                        || event.event_type.starts_with("ChildRun")
15228                })
15229                .collect();
15230            let signal_wait_events: Vec<_> = sequence_events
15231                .iter()
15232                .copied()
15233                .filter(|event| is_recorded_signal_wait_event(event))
15234                .collect();
15235            let condition_wait_events: Vec<_> = sequence_events
15236                .iter()
15237                .copied()
15238                .filter(|event| is_recorded_condition_wait_event(event))
15239                .collect();
15240            let search_attribute_events: Vec<_> = sequence_events
15241                .iter()
15242                .copied()
15243                .filter(|event| event.event_type == "SearchAttributesUpserted")
15244                .collect();
15245            let side_effect_events: Vec<_> = sequence_events
15246                .iter()
15247                .copied()
15248                .filter(|event| event.event_type == "SideEffectRecorded")
15249                .collect();
15250            let version_marker_events: Vec<_> = sequence_events
15251                .iter()
15252                .copied()
15253                .filter(|event| event.event_type == "VersionMarkerRecorded")
15254                .collect();
15255            let memo_events: Vec<_> = sequence_events
15256                .iter()
15257                .copied()
15258                .filter(|event| event.event_type == "MemoUpserted")
15259                .collect();
15260
15261            let command_kind_count = usize::from(!activity_events.is_empty())
15262                + usize::from(!timer_events.is_empty())
15263                + usize::from(!child_events.is_empty())
15264                + usize::from(!signal_wait_events.is_empty())
15265                + usize::from(!condition_wait_events.is_empty())
15266                + usize::from(!search_attribute_events.is_empty())
15267                + usize::from(!side_effect_events.is_empty())
15268                + usize::from(!version_marker_events.is_empty())
15269                + usize::from(!memo_events.is_empty());
15270            if command_kind_count > 1 {
15271                let actual = [
15272                    (!activity_events.is_empty()).then_some("activity"),
15273                    (!timer_events.is_empty()).then_some("timer"),
15274                    (!child_events.is_empty()).then_some("child workflow"),
15275                    (!signal_wait_events.is_empty()).then_some("signal wait"),
15276                    (!condition_wait_events.is_empty()).then_some("condition wait"),
15277                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
15278                    (!side_effect_events.is_empty()).then_some("side effect"),
15279                    (!version_marker_events.is_empty()).then_some("version marker"),
15280                    (!memo_events.is_empty()).then_some("memo upsert"),
15281                ]
15282                .into_iter()
15283                .flatten()
15284                .collect::<Vec<_>>()
15285                .join(" and ");
15286                return Err(invalid_recorded_history(
15287                    "durable_command_sequence_collision",
15288                    sequence,
15289                    "one durable command kind",
15290                    &actual,
15291                    "one workflow sequence records more than one durable command kind",
15292                ));
15293            }
15294
15295            if !activity_events.is_empty() {
15296                let parallel_group_path =
15297                    recorded_parallel_group_path(&activity_events, sequence)?;
15298                let scheduled_count = activity_events
15299                    .iter()
15300                    .filter(|event| event.event_type == "ActivityScheduled")
15301                    .count();
15302                if scheduled_count > 1 {
15303                    return Err(invalid_recorded_history(
15304                        "duplicate_activity_schedule",
15305                        sequence,
15306                        "at most one ActivityScheduled event",
15307                        "multiple ActivityScheduled events",
15308                        "activity history schedules more than one command at one workflow sequence",
15309                    ));
15310                }
15311                let activity_type = activity_events.iter().find_map(|event| {
15312                    event
15313                        .payload
15314                        .get("activity_type")
15315                        .or_else(|| event.payload.get("activity_name"))
15316                        .and_then(Value::as_str)
15317                        .map(str::to_string)
15318                });
15319                if activity_events.iter().filter_map(|event| {
15320                    event
15321                        .payload
15322                        .get("activity_type")
15323                        .or_else(|| event.payload.get("activity_name"))
15324                        .and_then(Value::as_str)
15325                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
15326                    return Err(invalid_recorded_history(
15327                        "activity_identity_mismatch",
15328                        sequence,
15329                        activity_type.as_deref().unwrap_or("one activity identity"),
15330                        "conflicting activity identities",
15331                        "activity lifecycle events at one workflow sequence disagree on identity",
15332                    ));
15333                }
15334                let terminal: Vec<_> = activity_events
15335                    .iter()
15336                    .copied()
15337                    .filter(|event| {
15338                        matches!(
15339                            event.event_type.as_str(),
15340                            "ActivityCompleted"
15341                                | "ActivityFailed"
15342                                | "ActivityCancelled"
15343                                | "ActivityTimedOut"
15344                        )
15345                    })
15346                    .collect();
15347                let duplicate_delivery = terminal.first().is_some_and(|first| {
15348                    terminal.iter().all(|event| {
15349                        event.event_type == first.event_type && event.payload == first.payload
15350                    })
15351                });
15352                if terminal.len() > 1 && !duplicate_delivery {
15353                    return Err(invalid_recorded_history(
15354                        "duplicate_activity_terminal_event",
15355                        sequence,
15356                        "at most one terminal activity event",
15357                        "multiple terminal activity events",
15358                        "activity history settles one command more than once",
15359                    ));
15360                }
15361                let outcome = terminal
15362                    .first()
15363                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
15364                    .transpose()?;
15365                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
15366                let activity_snapshot = activity_events
15367                    .iter()
15368                    .find(|event| event.event_type == "ActivityScheduled")
15369                    .and_then(|event| event.payload.get("activity"))
15370                    .and_then(Value::as_object);
15371                let options = Some(match activity_snapshot {
15372                    Some(activity) => RecordedActivityOptions {
15373                        task_queue: recorded_optional_string(activity, "queue"),
15374                        execution_mode,
15375                        retry_policy: recorded_activity_retry_snapshot(
15376                            activity.get("retry_policy"),
15377                        ),
15378                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15379                    },
15380                    None => RecordedActivityOptions {
15381                        task_queue: RecordedSnapshotValue::Unknown,
15382                        execution_mode,
15383                        retry_policy: recorded_activity_retry_snapshot(None),
15384                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15385                    },
15386                });
15387                return Ok(RecordedCommand::Activity {
15388                    sequence,
15389                    activity_type,
15390                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
15391                    options,
15392                    outcome,
15393                    parallel_group_path,
15394                });
15395            }
15396
15397            if !child_events.is_empty() {
15398                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
15399                let scheduled: Vec<_> = child_events
15400                    .iter()
15401                    .copied()
15402                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
15403                    .collect();
15404                if scheduled.len() != 1 {
15405                    return Err(invalid_recorded_history(
15406                        "child_workflow_schedule_missing_or_duplicate",
15407                        sequence,
15408                        "one ChildWorkflowScheduled event",
15409                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
15410                        "child workflow replay requires exactly one recorded schedule event",
15411                    ));
15412                }
15413                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
15414                let workflow_type = child_events.iter().find_map(|event| {
15415                    event
15416                        .payload
15417                        .get("child_workflow_type")
15418                        .or_else(|| event.payload.get("workflow_type"))
15419                        .and_then(Value::as_str)
15420                        .filter(|value| !value.is_empty())
15421                        .map(str::to_string)
15422                });
15423                if child_events
15424                    .iter()
15425                    .filter_map(|event| {
15426                        event
15427                            .payload
15428                            .get("child_workflow_type")
15429                            .or_else(|| event.payload.get("workflow_type"))
15430                            .and_then(Value::as_str)
15431                    })
15432                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
15433                {
15434                    return Err(invalid_recorded_history(
15435                        "child_workflow_identity_mismatch",
15436                        sequence,
15437                        workflow_type
15438                            .as_deref()
15439                            .unwrap_or("one child workflow type"),
15440                        "conflicting child workflow types",
15441                        "child workflow lifecycle events at one sequence disagree on type",
15442                    ));
15443                }
15444                let mut outcomes = child_workflow_outcomes(
15445                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
15446                    fallback_codec,
15447                    parent.clone(),
15448                )?;
15449                let terminal_events = child_events
15450                    .iter()
15451                    .copied()
15452                    .filter(|event| event.event_type.starts_with("ChildRun"))
15453                    .collect::<Vec<_>>();
15454                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
15455                    terminal_events.iter().all(|event| {
15456                        event.event_type == first.event_type && event.payload == first.payload
15457                    })
15458                });
15459                if outcomes.len() > 1 && !duplicate_delivery {
15460                    return Err(invalid_recorded_history(
15461                        "duplicate_child_workflow_terminal_event",
15462                        sequence,
15463                        "at most one terminal child event",
15464                        "multiple terminal child events",
15465                        "child workflow history settles one command more than once",
15466                    ));
15467                }
15468                return Ok(RecordedCommand::ChildWorkflow {
15469                    sequence,
15470                    workflow_type,
15471                    policies,
15472                    outcome: outcomes.pop(),
15473                    parallel_group_path,
15474                });
15475            }
15476
15477            if !signal_wait_events.is_empty() {
15478                let opened: Vec<_> = signal_wait_events
15479                    .iter()
15480                    .copied()
15481                    .filter(|event| event.event_type == "SignalWaitOpened")
15482                    .collect();
15483                if opened.len() != 1 {
15484                    return Err(invalid_recorded_history(
15485                        "signal_wait_open_missing_or_duplicate",
15486                        sequence,
15487                        "one SignalWaitOpened event",
15488                        &format!("{} SignalWaitOpened events", opened.len()),
15489                        "signal replay requires exactly one canonical wait-open event",
15490                    ));
15491                }
15492
15493                let applied: Vec<_> = signal_wait_events
15494                    .iter()
15495                    .copied()
15496                    .filter(|event| event.event_type == "SignalApplied")
15497                    .collect();
15498                if applied.len() > 1 {
15499                    return Err(invalid_recorded_history(
15500                        "duplicate_signal_wait_apply",
15501                        sequence,
15502                        "at most one SignalApplied event",
15503                        "multiple SignalApplied events",
15504                        "signal history applies one durable wait more than once",
15505                    ));
15506                }
15507
15508                let signal_names = signal_wait_events
15509                    .iter()
15510                    .map(|event| required_signal_wait_name(event, sequence))
15511                    .collect::<Result<Vec<_>>>()?;
15512                let signal_name = signal_names
15513                    .first()
15514                    .expect("signal wait events are not empty")
15515                    .clone();
15516                if signal_names.iter().any(|candidate| candidate != &signal_name) {
15517                    return Err(invalid_recorded_history(
15518                        "signal_wait_identity_mismatch",
15519                        sequence,
15520                        &signal_name,
15521                        "conflicting signal names",
15522                        "signal wait lifecycle events at one workflow sequence disagree on identity",
15523                    ));
15524                }
15525                let value = applied
15526                    .first()
15527                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
15528                    .transpose()?;
15529                return Ok(RecordedCommand::SignalWait {
15530                    sequence,
15531                    signal_name,
15532                    value,
15533                    parallel_group_path: recorded_parallel_group_path(
15534                        &signal_wait_events,
15535                        sequence,
15536                    )?,
15537                });
15538            }
15539
15540            if !condition_wait_events.is_empty() {
15541                return recorded_condition_wait(
15542                    sequence,
15543                    &condition_wait_events,
15544                    events,
15545                );
15546            }
15547
15548            if !search_attribute_events.is_empty() {
15549                if search_attribute_events.len() != 1 {
15550                    return Err(invalid_recorded_history(
15551                        "duplicate_search_attribute_update",
15552                        sequence,
15553                        "one SearchAttributesUpserted event",
15554                        &format!(
15555                            "{} SearchAttributesUpserted events",
15556                            search_attribute_events.len()
15557                        ),
15558                        "search-attribute history records one workflow command more than once",
15559                    ));
15560                }
15561                let payload = &search_attribute_events[0].payload;
15562                let attributes = payload
15563                    .get("attributes")
15564                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
15565                    .cloned()
15566                    .ok_or_else(|| {
15567                        invalid_recorded_history(
15568                            "search_attribute_update_missing",
15569                            sequence,
15570                            "non-empty attributes object",
15571                            "missing or invalid attributes",
15572                            "search-attribute history is missing its recorded mutation",
15573                        )
15574                    })?;
15575                let attribute_types =
15576                    recorded_search_attribute_types(payload, &attributes, sequence)?;
15577                return Ok(RecordedCommand::SearchAttributes {
15578                    sequence,
15579                    attributes,
15580                    attribute_types,
15581                });
15582            }
15583
15584            if !side_effect_events.is_empty() {
15585                if side_effect_events.len() != 1 {
15586                    return Err(invalid_recorded_history(
15587                        "duplicate_side_effect_record",
15588                        sequence,
15589                        "one SideEffectRecorded event",
15590                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
15591                        "side-effect history records one workflow command more than once",
15592                    ));
15593                }
15594                let event = side_effect_events[0];
15595                let result = event.payload.get("result").ok_or_else(|| {
15596                    invalid_recorded_history(
15597                        "side_effect_result_missing",
15598                        sequence,
15599                        "recorded result payload",
15600                        "missing result",
15601                        "side-effect history is missing its recorded value",
15602                    )
15603                })?;
15604                let has_published_envelope = result.as_str().is_some()
15605                    || result.as_object().is_some_and(|envelope| {
15606                        envelope.get("codec").and_then(Value::as_str).is_some()
15607                            && envelope.get("blob").and_then(Value::as_str).is_some()
15608                    });
15609                if !has_published_envelope {
15610                    return Err(invalid_recorded_history(
15611                        "side_effect_payload_malformed",
15612                        sequence,
15613                        "payload blob or {codec, blob} envelope",
15614                        &result.to_string(),
15615                        "side-effect history result does not use a published payload envelope",
15616                    ));
15617                }
15618                let codec = event
15619                    .payload
15620                    .get("payload_codec")
15621                    .and_then(Value::as_str)
15622                    .unwrap_or(fallback_codec);
15623                let value = decode_wire_avro_value(result, codec).map_err(|error| {
15624                    if error.to_string().contains("unsupported_payload_codec") {
15625                        return error;
15626                    }
15627
15628                    invalid_recorded_history(
15629                        "side_effect_payload_incompatible",
15630                        sequence,
15631                        &format!("valid {codec} payload envelope"),
15632                        &error.to_string(),
15633                        "side-effect history payload cannot be decoded with its recorded codec",
15634                    )
15635                })?;
15636                return Ok(RecordedCommand::SideEffect { sequence, value });
15637            }
15638
15639            if !version_marker_events.is_empty() {
15640                if version_marker_events.len() != 1 {
15641                    return Err(invalid_recorded_history(
15642                        "duplicate_version_marker_record",
15643                        sequence,
15644                        "one VersionMarkerRecorded event",
15645                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
15646                        "version-marker history records one workflow command more than once",
15647                    ));
15648                }
15649                let payload = &version_marker_events[0].payload;
15650                let change_id = payload
15651                    .get("change_id")
15652                    .and_then(Value::as_str)
15653                    .filter(|value| !value.is_empty())
15654                    .map(str::to_string)
15655                    .ok_or_else(|| {
15656                        invalid_recorded_history(
15657                            "version_marker_field_missing",
15658                            sequence,
15659                            "non-empty change_id",
15660                            "missing or invalid change_id",
15661                            "version-marker history is missing its stable change ID",
15662                        )
15663                    })?;
15664                let version = required_version_i32(payload, "version", sequence)?;
15665                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
15666                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
15667                if min_supported > max_supported || version < min_supported || version > max_supported {
15668                    return Err(invalid_recorded_history(
15669                        "version_marker_history_range_invalid",
15670                        sequence,
15671                        "min_supported <= version <= max_supported",
15672                        &format!("{min_supported} <= {version} <= {max_supported}"),
15673                        "recorded version marker contains an internally incompatible range",
15674                    ));
15675                }
15676                return Ok(RecordedCommand::VersionMarker {
15677                    sequence,
15678                    change_id,
15679                    version,
15680                });
15681            }
15682
15683            if !memo_events.is_empty() {
15684                if memo_events.len() != 1 {
15685                    return Err(invalid_recorded_history(
15686                        "duplicate_memo_upsert_record",
15687                        sequence,
15688                        "one MemoUpserted event",
15689                        &format!("{} MemoUpserted events", memo_events.len()),
15690                        "memo history records one workflow update more than once",
15691                    ));
15692                }
15693                let payload = &memo_events[0].payload;
15694                let entries = payload.get("entries").cloned().ok_or_else(|| {
15695                    invalid_recorded_history(
15696                        "memo_entries_missing",
15697                        sequence,
15698                        "memo entries object",
15699                        "missing entries",
15700                        "MemoUpserted history is missing replay identity entries",
15701                    )
15702                })?;
15703                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
15704                    invalid_recorded_history(
15705                        "memo_entries_invalid",
15706                        sequence,
15707                        "valid canonical memo entries",
15708                        &error.to_string(),
15709                        "MemoUpserted history contains invalid replay identity entries",
15710                    )
15711                })?;
15712                let merged = payload.get("merged").cloned().ok_or_else(|| {
15713                    invalid_recorded_history(
15714                        "memo_merged_projection_missing",
15715                        sequence,
15716                        "merged memo projection",
15717                        "missing merged",
15718                        "MemoUpserted history is missing its merged projection",
15719                    )
15720                })?;
15721                decode_memo_history_map(&merged, false).map_err(|error| {
15722                    invalid_recorded_history(
15723                        "memo_merged_projection_invalid",
15724                        sequence,
15725                        "valid merged memo projection",
15726                        &error.to_string(),
15727                        "MemoUpserted history contains an invalid merged projection",
15728                    )
15729                })?;
15730
15731                return Ok(RecordedCommand::Memo { sequence, entries });
15732            }
15733            let scheduled: Vec<_> = timer_events
15734                .iter()
15735                .copied()
15736                .filter(|event| event.event_type == "TimerScheduled")
15737                .collect();
15738            let fired: Vec<_> = timer_events
15739                .iter()
15740                .copied()
15741                .filter(|event| event.event_type == "TimerFired")
15742                .collect();
15743            if scheduled.len() != 1 {
15744                return Err(invalid_recorded_history(
15745                    "timer_schedule_missing_or_duplicate",
15746                    sequence,
15747                    "one TimerScheduled event",
15748                    &format!("{} TimerScheduled events", scheduled.len()),
15749                    "timer replay requires exactly one recorded schedule event",
15750                ));
15751            }
15752            if fired.len() > 1 {
15753                return Err(invalid_recorded_history(
15754                    "duplicate_timer_fire",
15755                    sequence,
15756                    "at most one TimerFired event",
15757                    "multiple TimerFired events",
15758                    "timer history contains more than one fire event for a workflow sequence",
15759                ));
15760            }
15761
15762            let scheduled = scheduled[0];
15763            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
15764            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
15765            if let Some(fired) = fired.first() {
15766                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
15767                if fired_timer_id != timer_id {
15768                    return Err(invalid_recorded_history(
15769                        "timer_identity_mismatch",
15770                        sequence,
15771                        &timer_id,
15772                        &fired_timer_id,
15773                        "TimerFired does not correspond to the recorded TimerScheduled event",
15774                    ));
15775                }
15776                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
15777                if fired_delay != delay_seconds {
15778                    return Err(invalid_recorded_history(
15779                        "timer_history_delay_mismatch",
15780                        sequence,
15781                        &delay_seconds.to_string(),
15782                        &fired_delay.to_string(),
15783                        "TimerScheduled and TimerFired record different delays",
15784                    ));
15785                }
15786            }
15787
15788            Ok(RecordedCommand::Timer {
15789                sequence,
15790                delay_seconds,
15791                fired: !fired.is_empty(),
15792                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
15793            })
15794        })
15795        .collect::<Result<_>>()?;
15796
15797    let mut marker_sequences = HashMap::new();
15798    for command in &commands {
15799        if let RecordedCommand::VersionMarker {
15800            sequence,
15801            change_id,
15802            ..
15803        } = command
15804        {
15805            if let Some(first_sequence) = marker_sequences.insert(change_id.clone(), *sequence) {
15806                return Err(invalid_recorded_history(
15807                    "duplicate_version_marker",
15808                    *sequence,
15809                    &format!("one marker for change ID {change_id:?}"),
15810                    &format!("markers at sequences {first_sequence} and {sequence}"),
15811                    "workflow history contains duplicate markers for one stable change ID",
15812                ));
15813            }
15814        }
15815    }
15816
15817    Ok(commands)
15818}
15819
15820fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
15821    payload
15822        .get(field)
15823        .and_then(Value::as_i64)
15824        .and_then(|value| i32::try_from(value).ok())
15825        .ok_or_else(|| {
15826            invalid_recorded_history(
15827                "version_marker_field_missing",
15828                sequence,
15829                &format!("integer {field}"),
15830                "missing or out-of-range integer",
15831                "version-marker history is missing a required integer field",
15832            )
15833        })
15834}
15835
15836fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
15837    event
15838        .payload
15839        .get("sequence")
15840        .or_else(|| event.payload.get("workflow_sequence"))
15841        .or_else(|| event.raw.get("sequence"))
15842        .or_else(|| event.raw.get("workflow_sequence"))
15843        .and_then(value_as_u64)
15844}
15845
15846fn is_internal_timer_event(event: &HistoryEvent) -> bool {
15847    matches!(
15848        event
15849            .payload
15850            .get("timer_kind")
15851            .or_else(|| event.raw.get("timer_kind"))
15852            .and_then(Value::as_str),
15853        Some("condition_timeout" | "signal_timeout")
15854    )
15855}
15856
15857fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
15858    matches!(
15859        event.event_type.as_str(),
15860        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15861    )
15862}
15863
15864fn recorded_condition_wait(
15865    sequence: u64,
15866    condition_events: &[&HistoryEvent],
15867    all_events: &[HistoryEvent],
15868) -> Result<RecordedCommand> {
15869    let opened = condition_events
15870        .iter()
15871        .copied()
15872        .filter(|event| event.event_type == "ConditionWaitOpened")
15873        .collect::<Vec<_>>();
15874    if opened.len() != 1 {
15875        return Err(invalid_recorded_history(
15876            "condition_wait_open_missing_or_duplicate",
15877            sequence,
15878            "one ConditionWaitOpened event",
15879            &format!("{} ConditionWaitOpened events", opened.len()),
15880            "condition replay requires exactly one canonical wait-open event",
15881        ));
15882    }
15883    let terminal = condition_events
15884        .iter()
15885        .copied()
15886        .filter(|event| {
15887            matches!(
15888                event.event_type.as_str(),
15889                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15890            )
15891        })
15892        .collect::<Vec<_>>();
15893    if terminal.len() > 1 {
15894        return Err(invalid_recorded_history(
15895            "duplicate_condition_wait_terminal_event",
15896            sequence,
15897            "at most one condition terminal event",
15898            "multiple condition terminal events",
15899            "condition history settles one durable wait more than once",
15900        ));
15901    }
15902
15903    let opened = opened[0];
15904    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
15905    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
15906    for event in condition_events
15907        .iter()
15908        .copied()
15909        .filter(|event| !std::ptr::eq(*event, opened))
15910    {
15911        let event_wait_id = required_condition_wait_id(event, sequence)?;
15912        if event_wait_id != condition_wait_id {
15913            return Err(invalid_recorded_history(
15914                "condition_wait_id_mismatch",
15915                sequence,
15916                &condition_wait_id,
15917                &event_wait_id,
15918                "condition lifecycle events at one sequence disagree on wait identity",
15919            ));
15920        }
15921        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
15922        if event_occurrence_id != occurrence_id {
15923            return Err(invalid_recorded_history(
15924                "condition_wait_occurrence_history_mismatch",
15925                sequence,
15926                &occurrence_id,
15927                &event_occurrence_id,
15928                "condition lifecycle events at one sequence disagree on authored occurrence identity",
15929            ));
15930        }
15931    }
15932
15933    let condition_key = optional_non_empty_history_string(opened, "condition_key");
15934    let predicate_identity = opened
15935        .payload
15936        .get("condition_definition_fingerprint")
15937        .and_then(Value::as_str)
15938        .filter(|value| !value.is_empty())
15939        .map(str::to_string)
15940        .ok_or_else(|| {
15941            invalid_recorded_history(
15942                "condition_wait_predicate_fingerprint_missing",
15943                sequence,
15944                "non-empty condition_definition_fingerprint",
15945                &opened.event_type,
15946                "canonical condition history is missing its predicate identity",
15947            )
15948        })?;
15949    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
15950    for event in condition_events
15951        .iter()
15952        .copied()
15953        .filter(|event| !std::ptr::eq(*event, opened))
15954    {
15955        for (field, opened_value) in [
15956            ("condition_key", condition_key.as_deref()),
15957            (
15958                "condition_definition_fingerprint",
15959                Some(predicate_identity.as_str()),
15960            ),
15961        ] {
15962            if let Some(value) = optional_non_empty_history_string(event, field) {
15963                if opened_value.is_some_and(|opened_value| opened_value != value) {
15964                    return Err(invalid_recorded_history(
15965                        "condition_wait_definition_history_mismatch",
15966                        sequence,
15967                        opened_value.unwrap_or_default(),
15968                        &value,
15969                        "condition lifecycle events disagree on the recorded definition",
15970                    ));
15971                }
15972            }
15973        }
15974        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
15975            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
15976                return Err(invalid_recorded_history(
15977                    "condition_wait_definition_history_mismatch",
15978                    sequence,
15979                    &format!("{}s", timeout_seconds.unwrap_or_default()),
15980                    &format!("{event_timeout}s"),
15981                    "condition lifecycle events disagree on the recorded timeout",
15982                ));
15983            }
15984        }
15985    }
15986
15987    let timeout_timer_events = all_events
15988        .iter()
15989        .filter(|event| {
15990            matches!(
15991                event.event_type.as_str(),
15992                "TimerScheduled" | "TimerCancelled" | "TimerFired"
15993            ) && event.payload.get("timer_kind").and_then(Value::as_str)
15994                == Some("condition_timeout")
15995                && event
15996                    .payload
15997                    .get("condition_wait_id")
15998                    .and_then(Value::as_str)
15999                    == Some(condition_wait_id.as_str())
16000        })
16001        .collect::<Vec<_>>();
16002    let scheduled = timeout_timer_events
16003        .iter()
16004        .copied()
16005        .filter(|event| event.event_type == "TimerScheduled")
16006        .collect::<Vec<_>>();
16007    let fired = timeout_timer_events
16008        .iter()
16009        .copied()
16010        .filter(|event| event.event_type == "TimerFired")
16011        .collect::<Vec<_>>();
16012    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16013        return Err(invalid_recorded_history(
16014            "condition_wait_timeout_history_invalid",
16015            sequence,
16016            "one timeout schedule and at most one fire",
16017            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16018            "condition timeout history has a missing or duplicate lifecycle event",
16019        ));
16020    }
16021    if let Some(scheduled) = scheduled.first() {
16022        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16023        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16024        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16025            return Err(invalid_recorded_history(
16026                "condition_wait_timeout_delay_mismatch",
16027                sequence,
16028                &format!("{}s", timeout_seconds.unwrap_or_default()),
16029                &format!("{delay_seconds}s"),
16030                "condition timeout timer differs from the wait definition",
16031            ));
16032        }
16033        if let Some(fired) = fired.first() {
16034            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16035            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16036            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16037                return Err(invalid_recorded_history(
16038                    "condition_wait_timeout_identity_mismatch",
16039                    sequence,
16040                    &format!("{timer_id}:{delay_seconds}s"),
16041                    &format!("{fired_timer_id}:{fired_delay}s"),
16042                    "condition timeout fire does not match its durable schedule",
16043                ));
16044            }
16045        }
16046    }
16047
16048    let result = terminal.first().map(|event| {
16049        if event.event_type == "ConditionWaitTimedOut" {
16050            ConditionWaitResult::TimedOut
16051        } else {
16052            ConditionWaitResult::Satisfied
16053        }
16054    });
16055    let result = if !fired.is_empty() {
16056        if result == Some(ConditionWaitResult::Satisfied) {
16057            return Err(invalid_recorded_history(
16058                "condition_wait_terminal_conflict",
16059                sequence,
16060                "one satisfied or timed-out outcome",
16061                "satisfied event and fired timeout",
16062                "condition history records conflicting terminal outcomes",
16063            ));
16064        }
16065        Some(ConditionWaitResult::TimedOut)
16066    } else {
16067        result
16068    };
16069
16070    Ok(RecordedCommand::ConditionWait {
16071        sequence,
16072        occurrence_id,
16073        condition_key,
16074        predicate_identity,
16075        timeout_seconds,
16076        result,
16077        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16078    })
16079}
16080
16081fn recorded_condition_group_path(
16082    condition_events: &[&HistoryEvent],
16083    all_events: &[HistoryEvent],
16084    sequence: u64,
16085) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16086    let opened = condition_events
16087        .iter()
16088        .copied()
16089        .find(|event| event.event_type == "ConditionWaitOpened")
16090        .expect("canonical condition opener is validated first");
16091    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16092    let previous_events = all_events
16093        .iter()
16094        .take_while(|event| !std::ptr::eq(*event, opened))
16095        .collect::<Vec<_>>();
16096    let originals = previous_events
16097        .iter()
16098        .copied()
16099        .filter(|event| event.event_type == "ConditionWaitOpened")
16100        .filter(|event| {
16101            event
16102                .payload
16103                .get("condition_wait_occurrence_id")
16104                .and_then(Value::as_str)
16105                == Some(occurrence.as_str())
16106        })
16107        .collect::<Vec<_>>();
16108    let Some(original) = originals.first().copied() else {
16109        return recorded_parallel_group_path(condition_events, sequence);
16110    };
16111    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16112    if authored_sequence == sequence {
16113        return recorded_parallel_group_path(condition_events, sequence);
16114    }
16115    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16116    if original_path.is_none() {
16117        return recorded_parallel_group_path(condition_events, sequence);
16118    }
16119    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16120    let identity_matches = [
16121        "condition_key",
16122        "condition_definition_fingerprint",
16123        "timeout_seconds",
16124    ]
16125    .iter()
16126    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16127    let previous = originals
16128        .iter()
16129        .copied()
16130        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16131        .max_by_key(|event| durable_event_sequence(event));
16132    let previously_satisfied = previous.is_some_and(|previous| {
16133        previous_events.iter().any(|event| {
16134            event.event_type == "ConditionWaitSatisfied"
16135                && event.payload.get("condition_wait_id")
16136                    == previous.payload.get("condition_wait_id")
16137                && event.payload.get("condition_wait_occurrence_id")
16138                    == previous.payload.get("condition_wait_occurrence_id")
16139                && durable_event_sequence(event) == durable_event_sequence(previous)
16140        })
16141    });
16142    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16143        return Err(invalid_recorded_history(
16144            "condition_wait_group_reopen_mismatch",
16145            sequence,
16146            "same authored condition and group path after a satisfied physical wait",
16147            &opened.payload.to_string(),
16148            "grouped condition reopen has no matching recorded predecessor",
16149        ));
16150    }
16151    Ok(reopened_path)
16152}
16153
16154fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16155    event
16156        .payload
16157        .get("condition_wait_occurrence_id")
16158        .and_then(Value::as_str)
16159        .filter(|value| !value.is_empty())
16160        .map(str::to_string)
16161        .ok_or_else(|| {
16162            invalid_recorded_history(
16163                "condition_wait_occurrence_id_missing",
16164                sequence,
16165                "non-empty condition_wait_occurrence_id",
16166                &event.event_type,
16167                "condition history is missing authored occurrence identity",
16168            )
16169        })
16170}
16171
16172fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16173    event
16174        .payload
16175        .get("condition_wait_id")
16176        .and_then(Value::as_str)
16177        .filter(|value| !value.is_empty())
16178        .map(str::to_string)
16179        .ok_or_else(|| {
16180            invalid_recorded_history(
16181                "condition_wait_id_missing",
16182                sequence,
16183                "non-empty condition_wait_id",
16184                &event.event_type,
16185                "canonical condition history is missing its durable wait identity",
16186            )
16187        })
16188}
16189
16190fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16191    event
16192        .payload
16193        .get(field)
16194        .and_then(Value::as_str)
16195        .filter(|value| !value.is_empty())
16196        .map(str::to_string)
16197}
16198
16199fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16200    match event.payload.get(field) {
16201        None | Some(Value::Null) => Ok(None),
16202        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16203            invalid_recorded_history(
16204                "condition_wait_definition_invalid",
16205                sequence,
16206                &format!("non-negative integer {field}"),
16207                &value.to_string(),
16208                "condition history contains an invalid numeric definition field",
16209            )
16210        }),
16211    }
16212}
16213
16214fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16215    event
16216        .payload
16217        .get("signal_name")
16218        .or_else(|| event.raw.get("signal_name"))
16219        .and_then(Value::as_str)
16220        .filter(|value| !value.is_empty())
16221        .map(str::to_string)
16222        .ok_or_else(|| {
16223            invalid_recorded_history(
16224                "signal_wait_name_missing",
16225                sequence,
16226                "non-empty signal_name",
16227                &event.event_type,
16228                "canonical signal-wait history is missing its signal identity",
16229            )
16230        })
16231}
16232
16233fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16234    matches!(
16235        event.event_type.as_str(),
16236        "SignalWaitOpened" | "SignalApplied"
16237    )
16238}
16239
16240fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
16241    event
16242        .payload
16243        .get(field)
16244        .and_then(Value::as_str)
16245        .filter(|value| !value.is_empty())
16246        .map(str::to_string)
16247        .ok_or_else(|| {
16248            invalid_recorded_history(
16249                "timer_history_field_missing",
16250                sequence,
16251                field,
16252                &event.event_type,
16253                "timer history is missing a required identity field",
16254            )
16255        })
16256}
16257
16258fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
16259    event
16260        .payload
16261        .get(field)
16262        .and_then(value_as_u64)
16263        .ok_or_else(|| {
16264            invalid_recorded_history(
16265                "timer_history_field_missing",
16266                sequence,
16267                field,
16268                &event.event_type,
16269                "timer history is missing a required numeric field",
16270            )
16271        })
16272}
16273
16274fn recorded_search_attribute_types(
16275    payload: &Value,
16276    attributes: &Value,
16277    sequence: u64,
16278) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
16279    let Some(raw_types) = payload.get("attribute_types") else {
16280        // This is the explicit compatibility rule for histories recorded
16281        // before typed identity was persisted. Values still constrain replay;
16282        // the unknown type snapshot does not assert a typed match.
16283        return Ok(RecordedSnapshotValue::Unknown);
16284    };
16285    let Some(raw_types) = raw_types.as_object() else {
16286        return Err(invalid_recorded_history(
16287            "search_attribute_types_malformed",
16288            sequence,
16289            "canonical attribute type map",
16290            &raw_types.to_string(),
16291            "search-attribute history contains malformed type identity",
16292        ));
16293    };
16294    let attribute_keys = attributes
16295        .as_object()
16296        .expect("recorded search attributes were validated as an object");
16297    let mut types = BTreeMap::new();
16298    for (key, value) in raw_types {
16299        let Some(attribute_type) = value.as_str() else {
16300            return Err(invalid_recorded_history(
16301                "search_attribute_types_malformed",
16302                sequence,
16303                "canonical string type name",
16304                &value.to_string(),
16305                "search-attribute history contains a non-string type identity",
16306            ));
16307        };
16308        if !attribute_keys.contains_key(key)
16309            || !matches!(
16310                attribute_type,
16311                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
16312            )
16313        {
16314            return Err(invalid_recorded_history(
16315                "search_attribute_types_malformed",
16316                sequence,
16317                "canonical types for keys present in attributes",
16318                &format!("{key}:{attribute_type}"),
16319                "search-attribute history contains unsupported or orphaned type identity",
16320            ));
16321        }
16322        types.insert(key.clone(), attribute_type.to_string());
16323    }
16324    Ok(RecordedSnapshotValue::Known(types))
16325}
16326
16327fn invalid_recorded_history(
16328    reason: &str,
16329    sequence: u64,
16330    expected: &str,
16331    actual: &str,
16332    message: &str,
16333) -> Error {
16334    Error::NonDeterministicReplay(ReplayFailure::new(
16335        reason,
16336        Some(sequence),
16337        Some(expected.to_string()),
16338        Some(actual.to_string()),
16339        message,
16340    ))
16341}
16342
16343type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
16344
16345fn activity_outcome(
16346    event: &HistoryEvent,
16347    fallback_codec: &str,
16348    recorded_activity_type: Option<String>,
16349) -> Result<ActivityOutcome> {
16350    if event.event_type == "ActivityCompleted" {
16351        let codec = event
16352            .payload
16353            .get("payload_codec")
16354            .and_then(Value::as_str)
16355            .unwrap_or(fallback_codec);
16356        return Ok(Ok(decode_wire_avro_value(
16357            event.payload.get("result").unwrap_or(&Value::Null),
16358            codec,
16359        )?));
16360    }
16361
16362    let payload = &event.payload;
16363    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
16364        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
16365        "ActivityCancelled" => (
16366            ActivityFailureKind::Cancelled,
16367            "cancelled",
16368            "activity was cancelled",
16369        ),
16370        "ActivityTimedOut" => (
16371            ActivityFailureKind::TimedOut,
16372            "timeout",
16373            "activity timed out",
16374        ),
16375        _ => unreachable!("activity_outcome is called only for terminal activity events"),
16376    };
16377    let exception = payload
16378        .get("exception")
16379        .filter(|value| !value.is_null())
16380        .cloned();
16381    let failure_category = payload_string(payload, "failure_category");
16382    let timeout_kind = payload_string(payload, "timeout_kind");
16383    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
16384        ActivityFailureKind::Failed => failure_category
16385            .clone()
16386            .unwrap_or_else(|| fallback_reason.to_string()),
16387        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
16388        ActivityFailureKind::TimedOut => timeout_kind
16389            .clone()
16390            .unwrap_or_else(|| fallback_reason.to_string()),
16391    });
16392    let message = payload_string(payload, "message")
16393        .or_else(|| {
16394            exception
16395                .as_ref()
16396                .and_then(|value| payload_string(value, "message"))
16397        })
16398        .unwrap_or_else(|| fallback_message.to_string());
16399
16400    Ok(Err(ActivityFailure {
16401        kind,
16402        reason,
16403        message,
16404        activity_execution_id: payload_string(payload, "activity_execution_id"),
16405        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
16406        activity_type: payload_string(payload, "activity_type")
16407            .or_else(|| payload_string(payload, "activity_name"))
16408            .or(recorded_activity_type),
16409        activity_class: payload_string(payload, "activity_class"),
16410        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
16411        failure_id: payload_string(payload, "failure_id"),
16412        failure_category,
16413        timeout_kind,
16414        non_retryable: payload
16415            .get("non_retryable")
16416            .and_then(Value::as_bool)
16417            .unwrap_or(false),
16418        exception_type: payload_string(payload, "exception_type").or_else(|| {
16419            exception
16420                .as_ref()
16421                .and_then(|value| payload_string(value, "type"))
16422        }),
16423        exception_class: payload_string(payload, "exception_class").or_else(|| {
16424            exception
16425                .as_ref()
16426                .and_then(|value| payload_string(value, "class"))
16427        }),
16428        code: payload
16429            .get("code")
16430            .filter(|value| !value.is_null())
16431            .cloned(),
16432        exception,
16433    }))
16434}
16435
16436type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
16437
16438fn child_workflow_outcomes(
16439    events: &[HistoryEvent],
16440    fallback_codec: &str,
16441    parent: WorkflowIdentity,
16442) -> Result<Vec<ChildWorkflowOutcome>> {
16443    let mut outcomes = Vec::new();
16444
16445    for event in events {
16446        let kind = match event.event_type.as_str() {
16447            "ChildRunCompleted" => None,
16448            "ChildRunFailed" => Some((
16449                ChildWorkflowFailureKind::Failed,
16450                "child_workflow",
16451                "child workflow failed",
16452            )),
16453            "ChildRunCancelled" => Some((
16454                ChildWorkflowFailureKind::Cancelled,
16455                "cancelled",
16456                "child workflow was cancelled",
16457            )),
16458            "ChildRunTerminated" => Some((
16459                ChildWorkflowFailureKind::Terminated,
16460                "terminated",
16461                "child workflow was terminated",
16462            )),
16463            _ => continue,
16464        };
16465        let payload = &event.payload;
16466        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
16467        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
16468        let child_workflow_type = payload_string(payload, "child_workflow_type");
16469
16470        if let Some((kind, reason, fallback_message)) = kind {
16471            let exception = payload
16472                .get("exception")
16473                .filter(|value| !value.is_null())
16474                .cloned();
16475            let message = payload_string(payload, "message")
16476                .or_else(|| {
16477                    exception
16478                        .as_ref()
16479                        .and_then(|value| payload_string(value, "message"))
16480                })
16481                .unwrap_or_else(|| fallback_message.to_string());
16482            let exception_type = payload_string(payload, "exception_type").or_else(|| {
16483                exception
16484                    .as_ref()
16485                    .and_then(|value| payload_string(value, "type"))
16486            });
16487            let exception_class = payload_string(payload, "exception_class").or_else(|| {
16488                exception
16489                    .as_ref()
16490                    .and_then(|value| payload_string(value, "class"))
16491            });
16492            outcomes.push(Err(ChildWorkflowFailure {
16493                kind,
16494                reason: reason.to_string(),
16495                message,
16496                parent_workflow_id: parent.workflow_id.clone(),
16497                parent_workflow_run_id: parent.run_id.clone(),
16498                child_workflow_id,
16499                child_workflow_run_id,
16500                child_workflow_type,
16501                failure_id: payload_string(payload, "failure_id"),
16502                failure_category: payload_string(payload, "failure_category"),
16503                exception_type,
16504                exception_class,
16505                non_retryable: payload
16506                    .get("non_retryable")
16507                    .and_then(Value::as_bool)
16508                    .unwrap_or(false),
16509                code: payload
16510                    .get("code")
16511                    .filter(|value| !value.is_null())
16512                    .cloned(),
16513                exception,
16514            }));
16515            continue;
16516        }
16517
16518        let codec = payload
16519            .get("payload_codec")
16520            .and_then(Value::as_str)
16521            .unwrap_or(fallback_codec);
16522        let result = payload
16523            .get("result")
16524            .or_else(|| payload.get("output"))
16525            .unwrap_or(&Value::Null);
16526        outcomes.push(Ok(ChildWorkflowAvroResult {
16527            parent: parent.clone(),
16528            child: WorkflowIdentity {
16529                workflow_id: child_workflow_id,
16530                run_id: child_workflow_run_id,
16531            },
16532            child_workflow_type,
16533            result: decode_wire_avro_value(result, codec)?,
16534        }));
16535    }
16536
16537    Ok(outcomes)
16538}
16539
16540fn payload_string(payload: &Value, key: &str) -> Option<String> {
16541    payload
16542        .get(key)
16543        .and_then(Value::as_str)
16544        .filter(|value| !value.is_empty())
16545        .map(str::to_string)
16546}
16547
16548fn recorded_activity_failure_boundary(
16549    ctx: &WorkflowContext,
16550    error: &Error,
16551) -> Option<(u64, String)> {
16552    let Error::ActivityFailed(failure) = error else {
16553        return None;
16554    };
16555    if failure.kind != ActivityFailureKind::Failed {
16556        return None;
16557    }
16558    let activity_execution_id = failure
16559        .activity_execution_id
16560        .as_deref()
16561        .filter(|value| !value.is_empty())?;
16562    let state = ctx.state.lock().ok()?;
16563    let mut matches = state.recorded_commands.iter().filter_map(|command| {
16564        let RecordedCommand::Activity {
16565            sequence,
16566            outcome: Some(Err(recorded_failure)),
16567            ..
16568        } = command
16569        else {
16570            return None;
16571        };
16572        (*sequence > 0 && recorded_failure == failure)
16573            .then_some((*sequence, activity_execution_id.to_string()))
16574    });
16575    let boundary = matches.next()?;
16576    matches.next().is_none().then_some(boundary)
16577}
16578
16579fn workflow_failure_command(
16580    error: &Error,
16581    failed_activity_boundary: Option<(u64, String)>,
16582) -> Value {
16583    let (exception_type, exception_class, properties) = match error {
16584        Error::ActivityFailed(failure) => (
16585            match failure.kind {
16586                ActivityFailureKind::Failed => "ActivityFailed",
16587                ActivityFailureKind::Cancelled => "ActivityCancelled",
16588                ActivityFailureKind::TimedOut => "ActivityTimedOut",
16589            },
16590            "durable_workflow::ActivityFailure",
16591            json!({
16592                "reason": failure.reason,
16593                "activity_execution_id": failure.activity_execution_id,
16594                "activity_attempt_id": failure.activity_attempt_id,
16595                "activity_type": failure.activity_type,
16596                "activity_class": failure.activity_class,
16597                "attempt_number": failure.attempt_number,
16598                "failure_id": failure.failure_id,
16599                "failure_category": failure.failure_category,
16600                "timeout_kind": failure.timeout_kind,
16601                "activity_non_retryable": failure.non_retryable,
16602                "activity_exception_type": failure.exception_type,
16603                "activity_exception_class": failure.exception_class,
16604                "activity_code": failure.code,
16605                "activity_exception": failure.exception,
16606            }),
16607        ),
16608        Error::ChildWorkflowFailed(failure) => (
16609            match failure.kind {
16610                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16611                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16612                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16613            },
16614            "durable_workflow::ChildWorkflowFailure",
16615            json!({
16616                "reason": failure.reason,
16617                "parent_workflow_id": failure.parent_workflow_id,
16618                "parent_workflow_run_id": failure.parent_workflow_run_id,
16619                "child_workflow_id": failure.child_workflow_id,
16620                "child_workflow_run_id": failure.child_workflow_run_id,
16621                "child_workflow_type": failure.child_workflow_type,
16622                "failure_id": failure.failure_id,
16623                "failure_category": failure.failure_category,
16624                "child_exception_type": failure.exception_type,
16625                "child_exception_class": failure.exception_class,
16626                "child_non_retryable": failure.non_retryable,
16627                "child_code": failure.code,
16628                "child_exception": failure.exception,
16629            }),
16630        ),
16631        Error::ParallelFailed(failure) => (
16632            "ParallelFailed",
16633            "durable_workflow::ParallelFailure",
16634            json!({
16635                "parallel_group_id": failure.group_id,
16636                "parallel_member_path": failure.member_path,
16637                "parallel_group_path": failure.group_path,
16638                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
16639                "cause_type": workflow_error_type(&failure.cause),
16640                "cause_message": failure.cause.to_string(),
16641            }),
16642        ),
16643        Error::SagaCompensationFailed(failure) => (
16644            "SagaCompensationFailed",
16645            "durable_workflow::SagaCompensationFailure",
16646            json!({
16647                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
16648                "initiating_failure_message": failure.initiating_failure.to_string(),
16649                "compensation_activity_type": failure.compensation_activity_type,
16650                "compensation_registration_order": failure.compensation_registration_order,
16651                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
16652                "compensation_failure_message": failure.compensation_failure.to_string(),
16653            }),
16654        ),
16655        Error::WorkflowCancellationRequested(_) => (
16656            "WorkflowCancellationRequested",
16657            "durable_workflow::WorkflowCancellationRequested",
16658            json!({"reason": "cancelled"}),
16659        ),
16660        Error::CooperativeCancellationRequested(cancellation) => (
16661            "WorkflowCancellationRequested",
16662            "durable_workflow::CooperativeCancellationRequested",
16663            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
16664                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
16665        ),
16666        Error::CancellationScopeRequested(cancellation) => (
16667            "WorkflowCancellationRequested",
16668            "durable_workflow::CancellationScopeRequested",
16669            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
16670                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
16671                "cancellation":cancellation.context.to_value()}),
16672        ),
16673        Error::NonDeterministicReplay(_) => (
16674            "NonDeterministicReplay",
16675            "durable_workflow::Error",
16676            Value::Null,
16677        ),
16678        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
16679    };
16680    let non_retryable = match error {
16681        Error::ActivityFailed(failure) => failure.non_retryable,
16682        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16683        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16684        Error::SagaCompensationFailed(failure) => {
16685            workflow_error_non_retryable(&failure.compensation_failure)
16686        }
16687        Error::WorkflowCancellationRequested(_)
16688        | Error::CooperativeCancellationRequested(_)
16689        | Error::CancellationScopeRequested(_) => true,
16690        Error::NonDeterministicReplay(_) => true,
16691        _ => false,
16692    };
16693
16694    let mut command = json!({
16695        "type": "fail_workflow",
16696        "message": error.to_string(),
16697        "exception_type": exception_type,
16698        "exception_class": exception_class,
16699        "non_retryable": non_retryable,
16700        "exception": {
16701            "type": exception_type,
16702            "class": exception_class,
16703            "message": error.to_string(),
16704            "properties": properties,
16705        }
16706    });
16707
16708    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
16709        command["failed_step_sequence"] = json!(sequence);
16710        command["failed_activity_execution_id"] = json!(activity_execution_id);
16711    }
16712
16713    command
16714}
16715
16716fn workflow_error_type(error: &Error) -> &'static str {
16717    match error {
16718        Error::ActivityFailed(failure) => match failure.kind {
16719            ActivityFailureKind::Failed => "ActivityFailed",
16720            ActivityFailureKind::Cancelled => "ActivityCancelled",
16721            ActivityFailureKind::TimedOut => "ActivityTimedOut",
16722        },
16723        Error::ChildWorkflowFailed(failure) => match failure.kind {
16724            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16725            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16726            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16727        },
16728        Error::ParallelFailed(_) => "ParallelFailed",
16729        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
16730        Error::WorkflowCancellationRequested(_)
16731        | Error::CooperativeCancellationRequested(_)
16732        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
16733        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
16734        _ => "RustWorkflowError",
16735    }
16736}
16737
16738fn workflow_error_non_retryable(error: &Error) -> bool {
16739    match error {
16740        Error::ActivityFailed(failure) => failure.non_retryable,
16741        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16742        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16743        Error::SagaCompensationFailed(failure) => {
16744            workflow_error_non_retryable(&failure.compensation_failure)
16745        }
16746        Error::WorkflowCancellationRequested(_)
16747        | Error::CooperativeCancellationRequested(_)
16748        | Error::CancellationScopeRequested(_)
16749        | Error::NonDeterministicReplay(_) => true,
16750        _ => false,
16751    }
16752}
16753
16754fn workflow_task_integrity_error(error: &Error) -> bool {
16755    matches!(
16756        error,
16757        Error::NonDeterministicReplay(_)
16758            | Error::Protocol(_)
16759            | Error::CancellationScopeExecutionUnavailable
16760            | Error::MissingWorkflowCommandIdentity
16761            | Error::WorkflowStatePoisoned
16762    )
16763}
16764
16765fn decode_signal_event_arguments(
16766    event: &HistoryEvent,
16767    fallback_codec: &str,
16768) -> Result<Vec<AvroValue>> {
16769    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16770    validate_payload_codec(codec)?;
16771    let raw = signal_history_payload(&event.payload);
16772    let decoded = match raw.filter(|value| !value.is_null()) {
16773        Some(value) => decode_wire_avro_value(value, codec)?,
16774        None => AvroValue::Array(Vec::new()),
16775    };
16776    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16777        unreachable!("normalize_avro_arguments always returns an array");
16778    };
16779    Ok(arguments)
16780}
16781
16782fn decode_update_event_arguments(
16783    event: &HistoryEvent,
16784    fallback_codec: &str,
16785) -> Result<Vec<AvroValue>> {
16786    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16787    validate_payload_codec(codec)?;
16788    let decoded = match event
16789        .payload
16790        .get("arguments")
16791        .filter(|value| !value.is_null())
16792    {
16793        Some(value) => decode_wire_avro_value(value, codec)?,
16794        None => AvroValue::Array(Vec::new()),
16795    };
16796    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16797        unreachable!("normalize_avro_arguments always returns an array");
16798    };
16799    Ok(arguments)
16800}
16801
16802fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16803    let Some(export_events) = task
16804        .history_export
16805        .as_ref()
16806        .and_then(|export| export.get("history_events"))
16807        .and_then(Value::as_array)
16808    else {
16809        return Ok(());
16810    };
16811
16812    if export_events.len() > task.history_events.len() {
16813        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
16814    }
16815
16816    Ok(())
16817}
16818
16819fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16820    let Some(export) = task.history_export.as_ref() else {
16821        return Ok(());
16822    };
16823    let signals = export
16824        .get("signals")
16825        .and_then(Value::as_array)
16826        .cloned()
16827        .unwrap_or_default();
16828    let activities = export
16829        .get("activities")
16830        .and_then(Value::as_array)
16831        .cloned()
16832        .unwrap_or_default();
16833    let export_codec = export
16834        .get("payloads")
16835        .and_then(|payloads| payloads.get("codec"))
16836        .and_then(Value::as_str)
16837        .unwrap_or(&task.payload_codec)
16838        .to_string();
16839    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
16840
16841    for event in &mut task.history_events {
16842        if event.event_type == "ActivityCompleted" {
16843            let sequence = event
16844                .payload
16845                .get("sequence")
16846                .or_else(|| event.payload.get("workflow_sequence"))
16847                .and_then(value_as_u64);
16848            let Some(activity) = sequence.and_then(|sequence| {
16849                activities.iter().find(|activity| {
16850                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
16851                })
16852            }) else {
16853                continue;
16854            };
16855            let Some(payload) = event.payload.as_object_mut() else {
16856                continue;
16857            };
16858            if missing_payload(payload.get("result")) {
16859                if let Some(result) = activity
16860                    .get("result")
16861                    .filter(|value| !missing_payload(Some(value)))
16862                {
16863                    payload.insert("result".to_string(), result.clone());
16864                }
16865            }
16866            for field in ["payload_codec", "activity_type"] {
16867                if payload
16868                    .get(field)
16869                    .and_then(Value::as_str)
16870                    .unwrap_or_default()
16871                    .is_empty()
16872                {
16873                    if let Some(value) = activity.get(field) {
16874                        payload.insert(field.to_string(), value.clone());
16875                    }
16876                }
16877            }
16878            continue;
16879        }
16880
16881        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
16882            continue;
16883        }
16884        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
16885        let command_id = event
16886            .payload
16887            .get("workflow_command_id")
16888            .or_else(|| event.raw.get("workflow_command_id"))
16889            .and_then(Value::as_str);
16890        let signal_name = event
16891            .payload
16892            .get("signal_name")
16893            .and_then(Value::as_str)
16894            .unwrap_or_default()
16895            .to_string();
16896        let matched = signals
16897            .iter()
16898            .find(|signal| {
16899                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
16900            })
16901            .or_else(|| {
16902                signals.iter().find(|signal| {
16903                    command_id.is_some()
16904                        && signal.get("command_id").and_then(Value::as_str) == command_id
16905                })
16906            })
16907            .or_else(|| {
16908                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
16909                let signal = signals
16910                    .iter()
16911                    .filter(|signal| {
16912                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
16913                    })
16914                    .nth(*offset);
16915                if signal.is_some() {
16916                    *offset += 1;
16917                }
16918                signal
16919            });
16920        let Some(signal) = matched else {
16921            continue;
16922        };
16923        let signal_codec = signal
16924            .get("payload_codec")
16925            .and_then(Value::as_str)
16926            .unwrap_or(&export_codec);
16927        let Some(payload) = event.payload.as_object_mut() else {
16928            continue;
16929        };
16930        if missing_payload(payload.get("arguments")) {
16931            if let Some(arguments) = signal
16932                .get("arguments")
16933                .filter(|value| !missing_payload(Some(value)))
16934            {
16935                let envelope = match arguments {
16936                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
16937                    other => other.clone(),
16938                };
16939                payload.insert("arguments".to_string(), envelope);
16940            }
16941        }
16942        if payload
16943            .get("payload_codec")
16944            .and_then(Value::as_str)
16945            .unwrap_or_default()
16946            .is_empty()
16947        {
16948            payload.insert("payload_codec".to_string(), json!(signal_codec));
16949        }
16950    }
16951
16952    Ok(())
16953}
16954
16955fn missing_payload(value: Option<&Value>) -> bool {
16956    match value {
16957        None | Some(Value::Null) => true,
16958        Some(Value::String(value)) => value.is_empty(),
16959        Some(_) => false,
16960    }
16961}
16962
16963fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
16964    let export_signals = task
16965        .history_export
16966        .as_ref()
16967        .and_then(|export| export.get("signals"))
16968        .and_then(Value::as_array)
16969        .cloned()
16970        .unwrap_or_default();
16971    let export_codec = task
16972        .history_export
16973        .as_ref()
16974        .and_then(|export| export.get("payloads"))
16975        .and_then(|payloads| payloads.get("codec"))
16976        .and_then(Value::as_str)
16977        .unwrap_or(&task.payload_codec);
16978    let mut name_offsets: HashMap<String, usize> = HashMap::new();
16979    let mut signals = Vec::new();
16980
16981    for event in &task.history_events {
16982        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
16983            continue;
16984        }
16985
16986        let name = event
16987            .payload
16988            .get("signal_name")
16989            .and_then(Value::as_str)
16990            .unwrap_or_default();
16991        if name.is_empty() {
16992            continue;
16993        }
16994        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
16995        let command_id = event
16996            .payload
16997            .get("workflow_command_id")
16998            .or_else(|| event.raw.get("workflow_command_id"))
16999            .and_then(Value::as_str);
17000        let matched_export = export_signals
17001            .iter()
17002            .find(|candidate| {
17003                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17004            })
17005            .or_else(|| {
17006                export_signals.iter().find(|candidate| {
17007                    command_id.is_some()
17008                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17009                })
17010            })
17011            .or_else(|| {
17012                let offset = name_offsets.entry(name.to_string()).or_default();
17013                let candidate = export_signals
17014                    .iter()
17015                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17016                    .nth(*offset);
17017                if candidate.is_some() {
17018                    *offset += 1;
17019                }
17020                candidate
17021            });
17022        let codec = event
17023            .payload
17024            .get("payload_codec")
17025            .and_then(Value::as_str)
17026            .or_else(|| {
17027                matched_export
17028                    .and_then(|signal| signal.get("payload_codec"))
17029                    .and_then(Value::as_str)
17030            })
17031            .unwrap_or(export_codec);
17032        let raw_arguments = signal_history_payload(&event.payload)
17033            .filter(|value| !value.is_null())
17034            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17035        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
17036        let workflow_sequence = event
17037            .payload
17038            .get("workflow_sequence")
17039            .and_then(value_as_u64)
17040            .or_else(|| {
17041                matched_export
17042                    .and_then(|signal| signal.get("workflow_sequence"))
17043                    .and_then(value_as_u64)
17044            });
17045
17046        signals.push(QuerySignal {
17047            id: signal_id.map(str::to_string).or_else(|| {
17048                matched_export
17049                    .and_then(|signal| signal.get("id"))
17050                    .and_then(Value::as_str)
17051                    .map(str::to_string)
17052            }),
17053            name: name.to_string(),
17054            arguments,
17055            avro_arguments,
17056            workflow_sequence,
17057        });
17058    }
17059
17060    if signals.is_empty() {
17061        for signal in export_signals {
17062            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17063                continue;
17064            }
17065            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17066                continue;
17067            };
17068            let codec = signal
17069                .get("payload_codec")
17070                .and_then(Value::as_str)
17071                .unwrap_or(export_codec);
17072            let (arguments, avro_arguments) =
17073                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17074            signals.push(QuerySignal {
17075                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17076                name: name.to_string(),
17077                arguments,
17078                avro_arguments,
17079                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17080            });
17081        }
17082        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17083    }
17084
17085    Ok(signals)
17086}
17087
17088fn decode_query_signal_arguments(
17089    raw: Option<&Value>,
17090    codec: &str,
17091) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17092    validate_payload_codec(codec)?;
17093    let decoded = match raw.filter(|value| !value.is_null()) {
17094        Some(value) => decode_wire_avro_value(value, codec)?,
17095        None => AvroValue::Array(Vec::new()),
17096    };
17097    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17098        unreachable!("normalize_avro_arguments always returns an array");
17099    };
17100    let arguments = avro_arguments
17101        .iter()
17102        .cloned()
17103        .map(AvroValue::into_json)
17104        .collect::<Result<Vec<_>>>()?;
17105    Ok((arguments, avro_arguments))
17106}
17107
17108fn value_as_u64(value: &Value) -> Option<u64> {
17109    value
17110        .as_u64()
17111        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17112}
17113
17114#[cfg(test)]
17115mod tests {
17116    use super::*;
17117    mod activity_cancellation_policies;
17118    mod cancellation_scope_admission;
17119    mod cancellation_scope_authoring;
17120    mod cancellation_scope_history;
17121    mod cancellation_scope_opening;
17122    mod cancellation_scope_replay;
17123    mod child_workflow_policies;
17124    mod cooperative_cancellation;
17125    mod local_activity;
17126    mod runtime_payloads;
17127    mod runtime_uploads;
17128    mod worker_session;
17129    use std::{
17130        fs,
17131        io::{Read, Write},
17132        net::{SocketAddr, TcpListener, TcpStream},
17133        process::Command as ProcessCommand,
17134        sync::atomic::AtomicUsize,
17135        thread,
17136    };
17137
17138    #[derive(Clone, Copy, Debug)]
17139    enum InvalidTaskPayloadCodec {
17140        Missing,
17141        Null,
17142        NonString,
17143    }
17144
17145    impl InvalidTaskPayloadCodec {
17146        fn label(self) -> &'static str {
17147            match self {
17148                Self::Missing => "missing",
17149                Self::Null => "null",
17150                Self::NonString => "non-string",
17151            }
17152        }
17153
17154        fn apply(self, task: &mut Value) {
17155            let task = task.as_object_mut().expect("task fixture object");
17156            match self {
17157                Self::Missing => {
17158                    task.remove("payload_codec");
17159                }
17160                Self::Null => {
17161                    task.insert("payload_codec".to_string(), Value::Null);
17162                }
17163                Self::NonString => {
17164                    task.insert("payload_codec".to_string(), json!(42));
17165                }
17166            }
17167        }
17168    }
17169
17170    fn fixture_envelope(value: Value) -> Value {
17171        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
17172    }
17173
17174    fn fixture_blob(value: Value) -> String {
17175        encode_payload(&value, DEFAULT_CODEC)
17176            .expect("encode Avro test fixture")
17177            .blob
17178    }
17179
17180    #[test]
17181    fn client_builder_rejects_the_sdk_owned_api_suffix() {
17182        for base_url in [
17183            "http://127.0.0.1:8080/api",
17184            "http://localhost:8080/api/",
17185            "https://runtime.example.test/namespaces/orders/api",
17186        ] {
17187            let error = Client::builder(base_url)
17188                .build()
17189                .expect_err("SDK-owned /api suffix must be rejected during build");
17190
17191            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
17192            assert!(
17193                error.to_string().contains("SDK appends /api automatically"),
17194                "the validation error must explain how to fix the endpoint"
17195            );
17196        }
17197    }
17198
17199    #[test]
17200    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
17201        for (base_url, expected) in [
17202            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
17203            (
17204                "http://localhost:8080/durable-workflow/",
17205                "http://localhost:8080/durable-workflow",
17206            ),
17207            (
17208                "https://runtime.example.test/namespaces/orders",
17209                "https://runtime.example.test/namespaces/orders",
17210            ),
17211            (
17212                "https://runtime.example.test/gateway/api/namespaces/orders",
17213                "https://runtime.example.test/gateway/api/namespaces/orders",
17214            ),
17215            (
17216                "https://api.example.test/runtime/orders/",
17217                "https://api.example.test/runtime/orders",
17218            ),
17219        ] {
17220            let client = Client::builder(base_url)
17221                .build()
17222                .expect("Server and Cloud runtime base URL must remain valid");
17223
17224            assert_eq!(client.base_url, expected);
17225        }
17226    }
17227
17228    #[test]
17229    fn workflow_completion_uses_the_additive_command_protocol_floor() {
17230        assert_eq!(
17231            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
17232            WORKER_PROTOCOL_VERSION
17233        );
17234        assert_eq!(
17235            workflow_completion_protocol_version(&[json!({
17236                "type": "upsert_search_attributes",
17237                "attributes": {"OrderStatus": "waiting"},
17238            })]),
17239            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
17240        );
17241        assert_eq!(
17242            workflow_completion_protocol_version(&[json!({
17243                "type": "upsert_search_attributes",
17244                "attributes": {"OrderStatus": "waiting"},
17245                "attribute_types": {"OrderStatus": "keyword"},
17246            })]),
17247            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
17248        );
17249        assert_eq!(
17250            workflow_completion_protocol_version(&[
17251                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
17252                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17253            ]),
17254            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
17255        );
17256        assert_eq!(
17257            workflow_completion_protocol_version(&[
17258                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
17259                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17260            ]),
17261            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
17262        );
17263        assert_eq!(
17264            workflow_completion_protocol_version(&[json!({
17265                "type": "open_condition_wait",
17266                "condition_wait_occurrence_id": "rust:condition-wait:0",
17267                "condition_key": "ready",
17268            })]),
17269            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17270        );
17271        assert_eq!(
17272            workflow_completion_protocol_version_with_message_streams(
17273                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
17274                true,
17275            ),
17276            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
17277        );
17278        assert_eq!(
17279            workflow_completion_protocol_version_with_message_streams(
17280                &[json!({
17281                    "type": "open_condition_wait",
17282                    "condition_wait_occurrence_id": "rust:condition-wait:0",
17283                    "condition_key": "ready",
17284                })],
17285                true,
17286            ),
17287            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17288        );
17289    }
17290
17291    #[test]
17292    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
17293        let manifest = portable_worker_affinity_capability_manifest();
17294
17295        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
17296            assert_eq!(manifest[capability]["supported"], json!(false));
17297            assert_eq!(
17298                manifest[capability]["minimum_protocol_version"],
17299                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
17300            );
17301            assert!(manifest[capability]["reason"]
17302                .as_str()
17303                .is_some_and(|reason| !reason.is_empty()));
17304        }
17305    }
17306
17307    fn typed_fidelity_probe() -> AvroValue {
17308        AvroValue::Map(BTreeMap::from([
17309            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
17310            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
17311            (
17312                "numeric".to_string(),
17313                AvroValue::Map(BTreeMap::from([
17314                    ("0".to_string(), AvroValue::String("zero".to_string())),
17315                    ("1".to_string(), AvroValue::String("one".to_string())),
17316                ])),
17317            ),
17318            (
17319                "nested".to_string(),
17320                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
17321                    "enabled".to_string(),
17322                    AvroValue::Boolean(true),
17323                )]))]),
17324            ),
17325            (
17326                "projection_collisions".to_string(),
17327                AvroValue::Array(projection_collision_probe()),
17328            ),
17329        ]))
17330    }
17331
17332    fn projection_collision_probe() -> Vec<AvroValue> {
17333        vec![
17334            AvroValue::Map(BTreeMap::from([
17335                ("$type".to_string(), AvroValue::String("bytes".to_string())),
17336                (
17337                    "base64".to_string(),
17338                    AvroValue::String("ordinary user text".to_string()),
17339                ),
17340            ])),
17341            AvroValue::Map(BTreeMap::from([
17342                ("$type".to_string(), AvroValue::String("map".to_string())),
17343                (
17344                    "entries".to_string(),
17345                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
17346                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
17347                        (
17348                            "value".to_string(),
17349                            AvroValue::String("user map".to_string()),
17350                        ),
17351                    ]))]),
17352                ),
17353            ])),
17354        ]
17355    }
17356
17357    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17358    struct TypedContract {
17359        nested: TypedNested,
17360        mode: TypedMode,
17361        optional: Option<String>,
17362        absent: Option<String>,
17363        items: Vec<i64>,
17364        labels: BTreeMap<String, String>,
17365        bytes: serde_bytes::ByteBuf,
17366        signed: i64,
17367        finite: f64,
17368    }
17369
17370    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17371    struct TypedNested {
17372        enabled: bool,
17373    }
17374
17375    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17376    enum TypedMode {
17377        Detailed { label: String },
17378    }
17379
17380    fn typed_contract() -> TypedContract {
17381        TypedContract {
17382            nested: TypedNested { enabled: true },
17383            mode: TypedMode::Detailed {
17384                label: "compiler-checked".to_string(),
17385            },
17386            optional: Some("present".to_string()),
17387            absent: None,
17388            items: vec![i64::MIN, 0, i64::MAX],
17389            labels: BTreeMap::from([
17390                ("language".to_string(), "rust".to_string()),
17391                ("wire".to_string(), "avro".to_string()),
17392            ]),
17393            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
17394            signed: -9_223_372_036_854_775_000,
17395            finite: 12.5,
17396        }
17397    }
17398
17399    #[derive(Clone, Debug, Default, PartialEq)]
17400    struct ReplayCounterState {
17401        loaded: Option<String>,
17402        count: i64,
17403        finished: bool,
17404    }
17405
17406    fn replay_counter_worker() -> Worker {
17407        let client = Client::new("http://127.0.0.1:8080").expect("client");
17408        let mut worker = Worker::new(client, "rust-workers");
17409        worker.register_replayed_workflow(
17410            "replay-counter",
17411            ReplayCounterState::default,
17412            |ctx, _input, state| async move {
17413                let loaded = ctx.activity("load-counter", json!([])).await?;
17414                state.update(|current| {
17415                    current.loaded = loaded.as_str().map(str::to_string);
17416                })?;
17417                for _ in 0..2 {
17418                    let signal = ctx.wait_signal("increment").await?;
17419                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
17420                    state.update(|current| current.count += amount)?;
17421                }
17422                state.update(|current| current.finished = true)?;
17423                state.read(|current| Ok(json!(current.count)))?
17424            },
17425        );
17426        worker.register_replayed_query::<ReplayCounterState, _, _>(
17427            "replay-counter",
17428            "current",
17429            |_ctx, state, _args| async move {
17430                Ok(json!({
17431                    "loaded": state.loaded,
17432                    "count": state.count,
17433                    "finished": state.finished,
17434                }))
17435            },
17436        );
17437        worker.register_replayed_query::<ReplayCounterState, _, _>(
17438            "replay-counter",
17439            "detached-mutation",
17440            |_ctx, state, _args| async move {
17441                let mut detached = (*state).clone();
17442                detached.count = 999;
17443                Ok(json!(detached.count))
17444            },
17445        );
17446        worker.register_replayed_query::<ReplayCounterState, _, _>(
17447            "replay-counter",
17448            "failed-mutation",
17449            |_ctx, state, _args| async move {
17450                let mut detached = (*state).clone();
17451                detached.count = 999;
17452                Err(Error::WorkerLoop("query refused".to_string()))
17453            },
17454        );
17455        worker
17456    }
17457
17458    fn replay_counter_query(
17459        query_name: &str,
17460        history_events: Value,
17461        run_status: &str,
17462    ) -> QueryTask {
17463        let arguments = fixture_envelope(json!([]));
17464        serde_json::from_value(json!({
17465            "query_task_id": format!("query-{query_name}"),
17466            "workflow_type": "replay-counter",
17467            "query_name": query_name,
17468            "payload_codec": DEFAULT_CODEC,
17469            "workflow_arguments": arguments.clone(),
17470            "query_arguments": arguments,
17471            "history_events": history_events,
17472            "run_status": run_status,
17473        }))
17474        .expect("query task")
17475    }
17476
17477    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
17478        workflow_context_with_codec(history, DEFAULT_CODEC)
17479    }
17480
17481    fn workflow_context_with_codec(
17482        history: Vec<HistoryEvent>,
17483        payload_codec: &str,
17484    ) -> WorkflowContext {
17485        WorkflowContext {
17486            cancellation_scope_id: "root".into(),
17487            state: Arc::new(Mutex::new(
17488                WorkflowState::new_with_identity(
17489                    history,
17490                    None,
17491                    None,
17492                    "rust-workers".to_string(),
17493                    payload_codec.to_string(),
17494                    None,
17495                )
17496                .expect("valid workflow history"),
17497            )),
17498        }
17499    }
17500
17501    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
17502        HistoryEvent {
17503            event_type: event_type.to_string(),
17504            payload,
17505            raw: HashMap::new(),
17506        }
17507    }
17508
17509    fn parallel_path_entry(
17510        kind: &str,
17511        base: u64,
17512        size: usize,
17513        index: usize,
17514    ) -> ParallelGroupMetadata {
17515        parallel_group_entry(base, size, index, kind)
17516    }
17517
17518    fn parallel_history_event(
17519        event_type: &str,
17520        sequence: u64,
17521        identity_field: &str,
17522        identity: &str,
17523        path: Vec<ParallelGroupMetadata>,
17524        result: Option<Value>,
17525    ) -> HistoryEvent {
17526        let mut payload = serde_json::Map::from_iter([
17527            ("sequence".to_string(), json!(sequence)),
17528            (identity_field.to_string(), json!(identity)),
17529        ]);
17530        let inner = path.last().expect("parallel history path");
17531        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
17532        payload.insert("parallel_group_path".to_string(), json!(path));
17533        if let Some(result) = result {
17534            let field = if event_type == "ChildRunCompleted" {
17535                "result"
17536            } else {
17537                "result"
17538            };
17539            payload.insert(field.to_string(), fixture_envelope(result));
17540            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
17541        }
17542        history_event(event_type, Value::Object(payload))
17543    }
17544
17545    fn nested_parallel_operations() -> Vec<ParallelOperation> {
17546        vec![
17547            ParallelOperation::activity("first", json!([])),
17548            ParallelOperation::group(vec![
17549                ParallelOperation::child_workflow(
17550                    "second",
17551                    ChildWorkflowOptions::new("child-workers"),
17552                    json!([]),
17553                ),
17554                ParallelOperation::activity("third", json!([])),
17555            ]),
17556        ]
17557    }
17558
17559    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
17560        let outer = [
17561            parallel_path_entry("mixed", 1, 3, 0),
17562            parallel_path_entry("mixed", 1, 3, 1),
17563            parallel_path_entry("mixed", 1, 3, 2),
17564        ];
17565        [
17566            vec![outer[0].clone()],
17567            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
17568            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
17569        ]
17570    }
17571
17572    #[test]
17573    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
17574        let ctx = workflow_context(Vec::new());
17575        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17576        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17577
17578        assert!(matches!(
17579            call.as_mut().poll(&mut task_context),
17580            Poll::Pending
17581        ));
17582        let commands = ctx.take_commands().expect("parallel commands");
17583        assert_eq!(
17584            commands
17585                .iter()
17586                .map(|command| command["type"].as_str().unwrap_or_default())
17587                .collect::<Vec<_>>(),
17588            [
17589                "schedule_activity",
17590                "start_child_workflow",
17591                "schedule_activity"
17592            ]
17593        );
17594        let paths = nested_parallel_paths();
17595        for (command, path) in commands.iter().zip(paths) {
17596            assert_eq!(command["parallel_group_path"], json!(path));
17597            assert_eq!(
17598                command["parallel_group_id"],
17599                json!(path.last().expect("inner group").parallel_group_id)
17600            );
17601        }
17602    }
17603
17604    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
17605        let paths = nested_parallel_paths();
17606        let third = parallel_history_event(
17607            "ActivityCompleted",
17608            3,
17609            "activity_type",
17610            "third",
17611            paths[2].clone(),
17612            Some(json!("three")),
17613        );
17614        vec![
17615            parallel_history_event(
17616                "ActivityCompleted",
17617                1,
17618                "activity_type",
17619                "first",
17620                paths[0].clone(),
17621                Some(json!("one")),
17622            ),
17623            parallel_history_event(
17624                "ChildWorkflowScheduled",
17625                2,
17626                "child_workflow_type",
17627                "second",
17628                paths[1].clone(),
17629                None,
17630            ),
17631            parallel_history_event(
17632                "ChildRunCompleted",
17633                2,
17634                "child_workflow_type",
17635                "second",
17636                paths[1].clone(),
17637                Some(json!("two")),
17638            ),
17639            third.clone(),
17640            third,
17641        ]
17642    }
17643
17644    #[test]
17645    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
17646        for _restart_or_completed_replay in 0..2 {
17647            let ctx = workflow_context(completed_nested_parallel_history());
17648            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17649            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17650            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
17651                panic!("completed nested parallel history must replay");
17652            };
17653            assert_eq!(
17654                results,
17655                vec![
17656                    ParallelResult::Activity(json!("one")),
17657                    ParallelResult::Group(vec![
17658                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
17659                            parent: WorkflowIdentity {
17660                                workflow_id: None,
17661                                run_id: None,
17662                            },
17663                            child: WorkflowIdentity {
17664                                workflow_id: None,
17665                                run_id: None,
17666                            },
17667                            child_workflow_type: Some("second".to_string()),
17668                            result: json!("two"),
17669                        }),
17670                        ParallelResult::Activity(json!("three")),
17671                    ]),
17672                ]
17673            );
17674            assert!(ctx.take_commands().expect("commands").is_empty());
17675            ctx.ensure_history_consumed().expect("history consumed");
17676        }
17677    }
17678
17679    #[test]
17680    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
17681        let paths = nested_parallel_paths();
17682        let history = vec![
17683            parallel_history_event(
17684                "ActivityCompleted",
17685                1,
17686                "activity_type",
17687                "first",
17688                paths[0].clone(),
17689                Some(json!("one")),
17690            ),
17691            parallel_history_event(
17692                "ChildWorkflowScheduled",
17693                2,
17694                "child_workflow_type",
17695                "second",
17696                paths[1].clone(),
17697                None,
17698            ),
17699            parallel_history_event(
17700                "ChildRunFailed",
17701                2,
17702                "child_workflow_type",
17703                "second",
17704                paths[1].clone(),
17705                None,
17706            ),
17707            parallel_history_event(
17708                "ActivityCompleted",
17709                3,
17710                "activity_type",
17711                "third",
17712                paths[2].clone(),
17713                Some(json!("late")),
17714            ),
17715        ];
17716        let ctx = workflow_context(history);
17717        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17718        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17719        let outcome = call.as_mut().poll(&mut task_context);
17720        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
17721            panic!("one failed child must return a typed partial failure: {outcome:?}");
17722        };
17723        assert_eq!(failure.member_path, [1, 0]);
17724        assert_eq!(failure.group_id, "parallel-calls:1:3");
17725        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
17726        assert_eq!(
17727            failure
17728                .completed
17729                .iter()
17730                .map(|completion| completion.member_path.clone())
17731                .collect::<Vec<_>>(),
17732            [vec![0], vec![1, 1]]
17733        );
17734    }
17735
17736    #[test]
17737    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
17738        let paths = nested_parallel_paths();
17739        let history = vec![
17740            parallel_history_event(
17741                "ActivityScheduled",
17742                1,
17743                "activity_type",
17744                "first",
17745                paths[0].clone(),
17746                None,
17747            ),
17748            parallel_history_event(
17749                "ChildWorkflowScheduled",
17750                2,
17751                "child_workflow_type",
17752                "second",
17753                paths[1].clone(),
17754                None,
17755            ),
17756            parallel_history_event(
17757                "ActivityScheduled",
17758                3,
17759                "activity_type",
17760                "third",
17761                paths[2].clone(),
17762                None,
17763            ),
17764        ];
17765        for _restart in 0..2 {
17766            let ctx = workflow_context(history.clone());
17767            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17768            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17769            let outcome = call.as_mut().poll(&mut task_context);
17770            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
17771            assert!(ctx.take_commands().expect("commands").is_empty());
17772        }
17773    }
17774
17775    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
17776        vec![selection_group_entry(
17777            1,
17778            2,
17779            index,
17780            "activity",
17781            &SelectionMemberMetadata {
17782                key: SelectionKey::Name(key.to_string()),
17783                index,
17784                base_sequence: index as u64 + 1,
17785                size: 1,
17786                kind: "activity".to_string(),
17787            },
17788        )]
17789    }
17790
17791    fn selection_activity_event(
17792        event_type: &str,
17793        index: usize,
17794        key: &str,
17795        result: Option<Value>,
17796    ) -> HistoryEvent {
17797        let sequence = index as u64 + 1;
17798        let mut event = parallel_history_event(
17799            event_type,
17800            sequence,
17801            "activity_type",
17802            &format!("{key}-activity"),
17803            selection_path(index, key),
17804            result,
17805        );
17806        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
17807        event.raw.insert(
17808            "id".to_string(),
17809            json!(if event_type == "ActivityCompleted" {
17810                format!("event-{key}")
17811            } else {
17812                format!("{event_type}-{key}")
17813            }),
17814        );
17815        event
17816    }
17817
17818    fn selection_winner_marker() -> HistoryEvent {
17819        history_event(
17820            "SelectionResolved",
17821            json!({
17822                "selection_group_id": "select-calls:1:2",
17823                "selection_group_base_sequence": 1,
17824                "selection_group_size": 2,
17825                "member_key": "fast",
17826                "member_index": 1,
17827                "member_base_sequence": 2,
17828                "member_size": 1,
17829                "operation_kind": "activity",
17830                "operation_identity": "activity-fast",
17831                "outcome": "completed",
17832                "resolution_event_id": "event-fast",
17833                "resolution_event_type": "ActivityCompleted",
17834            }),
17835        )
17836    }
17837
17838    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
17839        ctx.select_keyed(vec![
17840            (
17841                "slow",
17842                ParallelOperation::activity_with_options(
17843                    "slow-activity",
17844                    ActivityOptions::new().task_queue("default"),
17845                    json!([]),
17846                ),
17847            ),
17848            (
17849                "fast",
17850                ParallelOperation::activity_with_options(
17851                    "fast-activity",
17852                    ActivityOptions::new().task_queue("default"),
17853                    json!([]),
17854                ),
17855            ),
17856        ])
17857    }
17858
17859    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
17860        let ctx = workflow_context(history);
17861        let mut call = Box::pin(keyed_activity_selection(&ctx));
17862        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17863        let selected = match call.as_mut().poll(&mut task_context) {
17864            Poll::Ready(Ok(selected)) => selected,
17865            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
17866            Poll::Pending => panic!("persisted selection winner must replay without pending"),
17867        };
17868        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
17869        assert_eq!(
17870            selected.value,
17871            Some(ParallelResult::Activity(json!("winner-value")))
17872        );
17873        let slow = selected
17874            .handle(&SelectionKey::Name("slow".to_string()))
17875            .expect("slow handle")
17876            .clone();
17877        let mut await_slow = Box::pin(slow.await_result());
17878        assert!(matches!(
17879            await_slow.as_mut().poll(&mut task_context),
17880            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
17881        ));
17882        assert!(ctx.take_commands().expect("commands").is_empty());
17883    }
17884
17885    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
17886
17887    fn canonical_selection_history() -> Vec<HistoryEvent> {
17888        const FIXTURE: &[u8] =
17889            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
17890        assert_eq!(
17891            format!("{:x}", Sha256::digest(FIXTURE)),
17892            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
17893        );
17894        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
17895
17896        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
17897    }
17898
17899    #[test]
17900    fn selection_fresh_process_entrypoint() {
17901        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
17902            return;
17903        };
17904        let persisted = fs::read(path).expect("persisted selection history");
17905        assert_eq!(
17906            format!("{:x}", Sha256::digest(&persisted)),
17907            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
17908        );
17909        let fixture: Value =
17910            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
17911        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
17912            .expect("valid persisted selection history");
17913
17914        assert_persisted_selection_replay(history);
17915    }
17916
17917    #[test]
17918    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
17919        let ctx = workflow_context(Vec::new());
17920        let mut call = Box::pin(keyed_activity_selection(&ctx));
17921        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17922
17923        assert!(matches!(
17924            call.as_mut().poll(&mut task_context),
17925            Poll::Pending
17926        ));
17927        let commands = ctx.take_commands().expect("selection commands");
17928        assert_eq!(commands.len(), 2);
17929        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
17930        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
17931        assert!(commands.iter().all(|command| {
17932            command["parallel_group_id"] == json!("select-calls:1:2")
17933                && command["parallel_group_mode"] == json!("select")
17934        }));
17935    }
17936
17937    #[test]
17938    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
17939        let ctx = workflow_context(Vec::new());
17940        let mut invalid = Box::pin(ctx.select_keyed(vec![(
17941            "",
17942            ParallelOperation::activity("invalid", json!([])),
17943        )]));
17944        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17945        assert!(matches!(
17946            invalid.as_mut().poll(&mut task_context),
17947            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
17948                reason: "selection_key_invalid",
17949                ..
17950            })))
17951        ));
17952
17953        for invalid_key in [json!(""), json!(-1)] {
17954            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
17955            event.payload["selection_member_key"] = invalid_key.clone();
17956            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
17957            assert!(matches!(
17958                WorkflowState::new_with_identity(
17959                    vec![event],
17960                    None,
17961                    None,
17962                    "rust-workers".to_string(),
17963                    DEFAULT_CODEC.to_string(),
17964                    None,
17965                ),
17966                Err(Error::NonDeterministicReplay(_))
17967            ));
17968        }
17969    }
17970
17971    #[test]
17972    fn selection_preserves_valid_named_and_numeric_keys() {
17973        let ctx = workflow_context(Vec::new());
17974        let mut selection = Box::pin(ctx.select_keyed(vec![
17975            (
17976                SelectionKey::Index(0),
17977                ParallelOperation::activity("numeric", json!([])),
17978            ),
17979            (
17980                SelectionKey::Name("named".to_string()),
17981                ParallelOperation::timer(Duration::from_secs(1)),
17982            ),
17983        ]));
17984        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17985
17986        assert!(matches!(
17987            selection.as_mut().poll(&mut task_context),
17988            Poll::Pending
17989        ));
17990        let commands = ctx.take_commands().expect("selection commands");
17991        assert_eq!(commands[0]["selection_member_key"], json!(0));
17992        assert_eq!(commands[1]["selection_member_key"], json!("named"));
17993    }
17994
17995    #[test]
17996    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
17997        let history = canonical_selection_history();
17998        assert_persisted_selection_replay(history.clone());
17999
18000        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18001            .join("tests/fixtures/durable_selection_runtime_history.json");
18002        let output =
18003            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
18004                .args([
18005                    "--exact",
18006                    "tests::selection_fresh_process_entrypoint",
18007                    "--nocapture",
18008                ])
18009                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
18010                .output()
18011                .expect("run fresh selection replay process");
18012
18013        assert!(
18014            output.status.success(),
18015            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
18016            String::from_utf8_lossy(&output.stdout),
18017            String::from_utf8_lossy(&output.stderr),
18018        );
18019    }
18020
18021    #[test]
18022    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
18023        let mut history = canonical_selection_history();
18024        history.retain(|event| event.event_type != "SelectionResolved");
18025        let ctx = workflow_context(history);
18026        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18027        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18028
18029        assert!(matches!(
18030            selection.as_mut().poll(&mut task_context),
18031            Poll::Pending
18032        ));
18033        assert!(ctx.take_commands().expect("commands").is_empty());
18034        assert!(
18035            ctx.matched_recorded_pending()
18036                .expect("selection pending state"),
18037            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
18038        );
18039    }
18040
18041    #[test]
18042    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18043        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18044            ("ConditionWaitSatisfied", true, None),
18045            ("ConditionWaitTimedOut", false, Some(0)),
18046        ] {
18047            let member = SelectionMemberMetadata {
18048                key: SelectionKey::Name("condition".to_string()),
18049                index: 0,
18050                base_sequence: 1,
18051                size: 1,
18052                kind: "condition".to_string(),
18053            };
18054            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18055            let mut payload = json!({
18056                "sequence": 1,
18057                "condition_wait_id": "condition-1",
18058                "condition_wait_occurrence_id": "rust:condition-wait:0",
18059                "condition_key": "ready",
18060                "condition_definition_fingerprint": "sha256:ready-v1",
18061                "parallel_group_path": path,
18062            });
18063            payload
18064                .as_object_mut()
18065                .expect("condition history payload")
18066                .extend(
18067                    serde_json::to_value(&path[0])
18068                        .expect("condition selection metadata")
18069                        .as_object()
18070                        .expect("condition selection metadata object")
18071                        .clone(),
18072                );
18073            if let Some(timeout_seconds) = timeout_seconds {
18074                payload["timeout_seconds"] = json!(timeout_seconds);
18075            }
18076            let history = vec![
18077                history_event("ConditionWaitOpened", payload.clone()),
18078                history_event(terminal_event, payload),
18079            ];
18080            let ctx = workflow_context(history);
18081            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18082            if timeout_seconds.is_some() {
18083                options = options.timeout(Duration::ZERO);
18084            }
18085            let mut selection = Box::pin(ctx.select_keyed(vec![(
18086                "condition",
18087                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18088            )]));
18089            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18090
18091            assert!(matches!(
18092                selection.as_mut().poll(&mut task_context),
18093                Poll::Pending
18094            ));
18095            assert!(ctx.take_commands().expect("commands").is_empty());
18096            assert!(
18097                ctx.matched_recorded_pending()
18098                    .expect("condition selection pending state"),
18099                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18100            );
18101        }
18102    }
18103
18104    #[test]
18105    fn selection_immediate_condition_members_open_a_durable_wait() {
18106        for predicate_satisfied in [true, false] {
18107            let ctx = workflow_context(Vec::new());
18108            let mut selection = Box::pin(ctx.select_keyed(vec![(
18109                "condition",
18110                ParallelOperation::condition(
18111                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18112                    move || Ok(predicate_satisfied),
18113                ),
18114            )]));
18115            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18116
18117            assert!(matches!(
18118                selection.as_mut().poll(&mut task_context),
18119                Poll::Pending
18120            ));
18121            let commands = ctx.take_commands().expect("condition selection command");
18122            assert_eq!(commands.len(), 1);
18123            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18124            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18125            assert_eq!(
18126                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18127                json!("select")
18128            );
18129        }
18130    }
18131
18132    #[test]
18133    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18134        let history = vec![
18135            selection_activity_event("ActivityScheduled", 0, "slow", None),
18136            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18137            selection_winner_marker(),
18138        ];
18139        let ctx = workflow_context(history.clone());
18140        let mut call = Box::pin(keyed_activity_selection(&ctx));
18141        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18142        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18143            panic!("winner must replay");
18144        };
18145        let slow = selected
18146            .handle(&SelectionKey::Name("slow".to_string()))
18147            .expect("slow handle")
18148            .clone();
18149        let mut cancel = Box::pin(slow.cancel());
18150        assert!(matches!(
18151            cancel.as_mut().poll(&mut task_context),
18152            Poll::Pending
18153        ));
18154        assert!(matches!(
18155            cancel.as_mut().poll(&mut task_context),
18156            Poll::Pending
18157        ));
18158        let commands = ctx.take_commands().expect("cancel command");
18159        assert_eq!(commands.len(), 1);
18160        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18161        assert_eq!(commands[0]["member_key"], json!("slow"));
18162
18163        let mut cancelled_history = history;
18164        cancelled_history.push(history_event(
18165            "SelectionOperationCancelled",
18166            json!({
18167                "selection_group_id": "select-calls:1:2",
18168                "member_key": "slow",
18169                "member_index": 0,
18170                "member_base_sequence": 1,
18171                "member_size": 1,
18172                "operation_kind": "activity",
18173                "operation_identity": "activity-slow",
18174                "cancelled_at": "2026-08-27T00:00:00Z",
18175            }),
18176        ));
18177        let replayed = workflow_context(cancelled_history);
18178        let mut call = Box::pin(keyed_activity_selection(&replayed));
18179        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18180            panic!("winner must replay after cancellation");
18181        };
18182        let slow = selected
18183            .handle(&SelectionKey::Name("slow".to_string()))
18184            .expect("slow handle")
18185            .clone();
18186        let mut cancel = Box::pin(slow.cancel());
18187        assert!(matches!(
18188            cancel.as_mut().poll(&mut task_context),
18189            Poll::Ready(Ok(()))
18190        ));
18191        assert!(replayed.take_commands().expect("commands").is_empty());
18192    }
18193
18194    #[test]
18195    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
18196        let base_history = vec![
18197            selection_activity_event("ActivityScheduled", 0, "slow", None),
18198            selection_activity_event("ActivityScheduled", 1, "fast", None),
18199            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18200            selection_winner_marker(),
18201        ];
18202        for (field, corrupt) in [
18203            ("member_key", json!("fast")),
18204            ("member_index", json!(1)),
18205            ("member_base_sequence", json!(3)),
18206            ("member_size", json!(2)),
18207            ("operation_kind", json!("timer")),
18208            ("operation_identity", json!("forged")),
18209        ] {
18210            let mut cancellation = json!({
18211                "selection_group_id": "select-calls:1:2",
18212                "member_key": "slow",
18213                "member_index": 0,
18214                "member_base_sequence": 1,
18215                "member_size": 1,
18216                "operation_kind": "activity",
18217                "operation_identity": "activity-slow",
18218            });
18219            cancellation[field] = corrupt;
18220            let mut history = base_history.clone();
18221            history.push(history_event("SelectionOperationCancelled", cancellation));
18222            let ctx = workflow_context(history);
18223            let mut selection = Box::pin(keyed_activity_selection(&ctx));
18224            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18225
18226            assert!(matches!(
18227                selection.as_mut().poll(&mut task_context),
18228                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18229            ));
18230        }
18231    }
18232
18233    #[test]
18234    fn selection_child_identity_prefers_the_durable_run_id() {
18235        let ctx = workflow_context(vec![history_event(
18236            "ChildWorkflowScheduled",
18237            json!({
18238                "sequence": 1,
18239                "child_workflow_type": "child",
18240                "child_workflow_instance_id": "child-instance",
18241                "child_workflow_run_id": "child-run",
18242            }),
18243        )]);
18244        let state = ctx.state.lock().expect("workflow state");
18245
18246        assert_eq!(
18247            selection_operation_identity(&state, "child", 1, 1),
18248            "child-run"
18249        );
18250    }
18251
18252    #[test]
18253    fn selection_activity_identity_requires_canonical_execution_id() {
18254        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
18255        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
18256        let mut fast_completed =
18257            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
18258        for event in [&mut fast_open, &mut fast_completed] {
18259            event
18260                .payload
18261                .as_object_mut()
18262                .expect("activity payload")
18263                .remove("activity_execution_id");
18264            event.payload["activity_id"] = json!("forged-activity-id");
18265        }
18266        let mut marker = selection_winner_marker();
18267        marker.payload["operation_identity"] = json!("forged-activity-id");
18268        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
18269        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18270        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18271
18272        assert!(matches!(
18273            selection.as_mut().poll(&mut task_context),
18274            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18275        ));
18276    }
18277
18278    #[test]
18279    fn selection_completion_before_cancellation_remains_awaitable() {
18280        let history = vec![
18281            selection_activity_event("ActivityScheduled", 0, "slow", None),
18282            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18283            selection_winner_marker(),
18284            selection_activity_event(
18285                "ActivityCompleted",
18286                0,
18287                "slow",
18288                Some(json!("completed-first")),
18289            ),
18290        ];
18291        let ctx = workflow_context(history);
18292        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18293        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18294        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18295            panic!("winner must replay");
18296        };
18297        let slow = selected
18298            .handle(&SelectionKey::Name("slow".to_string()))
18299            .expect("slow handle")
18300            .clone();
18301        let mut cancel = Box::pin(slow.cancel());
18302        assert!(matches!(
18303            cancel.as_mut().poll(&mut task_context),
18304            Poll::Ready(Ok(()))
18305        ));
18306        let mut await_slow = Box::pin(slow.await_result());
18307        assert!(matches!(
18308            await_slow.as_mut().poll(&mut task_context),
18309            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
18310        ));
18311        let commands = ctx.take_commands().expect("commands");
18312        assert!(commands.is_empty());
18313    }
18314
18315    #[test]
18316    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
18317        let nested_member = SelectionMemberMetadata {
18318            key: SelectionKey::Name("nested".to_string()),
18319            index: 0,
18320            base_sequence: 1,
18321            size: 2,
18322            kind: "group".to_string(),
18323        };
18324        let deadline_member = SelectionMemberMetadata {
18325            key: SelectionKey::Name("deadline".to_string()),
18326            index: 1,
18327            base_sequence: 3,
18328            size: 1,
18329            kind: "timer".to_string(),
18330        };
18331        let nested_paths = [
18332            vec![
18333                selection_group_entry(1, 3, 0, "mixed", &nested_member),
18334                parallel_group_entry(1, 2, 0, "activity"),
18335            ],
18336            vec![
18337                selection_group_entry(1, 3, 1, "mixed", &nested_member),
18338                parallel_group_entry(1, 2, 1, "activity"),
18339            ],
18340        ];
18341        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
18342        let mut timer_fired = parallel_history_event(
18343            "TimerFired",
18344            3,
18345            "timer_id",
18346            "timer-3",
18347            deadline_path.clone(),
18348            None,
18349        );
18350        timer_fired.payload["delay_seconds"] = json!(0);
18351        timer_fired
18352            .raw
18353            .insert("id".to_string(), json!("timer-fired"));
18354        let mut timer_scheduled = parallel_history_event(
18355            "TimerScheduled",
18356            3,
18357            "timer_id",
18358            "timer-3",
18359            deadline_path,
18360            None,
18361        );
18362        timer_scheduled.payload["delay_seconds"] = json!(0);
18363        let history = vec![
18364            parallel_history_event(
18365                "ActivityScheduled",
18366                1,
18367                "activity_type",
18368                "nested-first",
18369                nested_paths[0].clone(),
18370                None,
18371            ),
18372            parallel_history_event(
18373                "ActivityScheduled",
18374                2,
18375                "activity_type",
18376                "nested-second",
18377                nested_paths[1].clone(),
18378                None,
18379            ),
18380            timer_scheduled,
18381            timer_fired,
18382            history_event(
18383                "SelectionResolved",
18384                json!({
18385                    "selection_group_id": "select-calls:1:3",
18386                    "selection_group_base_sequence": 1,
18387                    "selection_group_size": 3,
18388                    "member_key": "deadline",
18389                    "member_index": 1,
18390                    "member_base_sequence": 3,
18391                    "member_size": 1,
18392                    "operation_kind": "timer",
18393                    "operation_identity": "timer-3",
18394                    "outcome": "completed",
18395                    "resolution_event_id": "timer-fired",
18396                    "resolution_event_type": "TimerFired",
18397                }),
18398            ),
18399            parallel_history_event(
18400                "ActivityFailed",
18401                2,
18402                "activity_type",
18403                "nested-second",
18404                nested_paths[1].clone(),
18405                None,
18406            ),
18407        ];
18408        let ctx = workflow_context(history);
18409        let mut selection = Box::pin(ctx.select_keyed(vec![
18410            (
18411                "nested",
18412                ParallelOperation::group(vec![
18413                    ParallelOperation::activity("nested-first", json!([])),
18414                    ParallelOperation::activity("nested-second", json!([])),
18415                ]),
18416            ),
18417            ("deadline", ParallelOperation::timer(Duration::ZERO)),
18418        ]));
18419        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18420        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18421            panic!("deadline winner must replay");
18422        };
18423        let nested = selected
18424            .handle(&SelectionKey::Name("nested".to_string()))
18425            .expect("nested handle")
18426            .clone();
18427        let mut cancel = Box::pin(nested.cancel());
18428        assert!(matches!(
18429            cancel.as_mut().poll(&mut task_context),
18430            Poll::Ready(Ok(()))
18431        ));
18432        let mut await_nested = Box::pin(nested.await_result());
18433
18434        assert!(matches!(
18435            await_nested.as_mut().poll(&mut task_context),
18436            Poll::Ready(Err(Error::ActivityFailed(_)))
18437        ));
18438        assert!(ctx.take_commands().expect("commands").is_empty());
18439    }
18440
18441    #[test]
18442    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
18443        let ctx = workflow_context(Vec::new());
18444        let mut call = Box::pin(ctx.select(vec![
18445            ParallelOperation::child_workflow(
18446                "child",
18447                ChildWorkflowOptions::new("children"),
18448                json!([]),
18449            ),
18450            ParallelOperation::timer(Duration::from_secs(30)),
18451            ParallelOperation::signal("approval"),
18452            ParallelOperation::condition(
18453                ConditionWaitOptions::new("ready", "sha256:ready"),
18454                || Ok(false),
18455            ),
18456            ParallelOperation::group(vec![
18457                ParallelOperation::activity("nested-one", json!([])),
18458                ParallelOperation::activity("nested-two", json!([])),
18459            ]),
18460        ]));
18461        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18462        assert!(matches!(
18463            call.as_mut().poll(&mut task_context),
18464            Poll::Pending
18465        ));
18466        let commands = ctx.take_commands().expect("selection commands");
18467        assert_eq!(
18468            commands
18469                .iter()
18470                .map(|command| command["type"].as_str().unwrap_or_default())
18471                .collect::<Vec<_>>(),
18472            [
18473                "start_child_workflow",
18474                "start_timer",
18475                "open_signal_wait",
18476                "open_condition_wait",
18477                "schedule_activity",
18478                "schedule_activity",
18479            ]
18480        );
18481        assert!(commands.iter().all(|command| {
18482            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
18483        }));
18484        assert_eq!(
18485            commands[4]["parallel_group_path"].as_array().map(Vec::len),
18486            Some(2)
18487        );
18488        assert_eq!(
18489            commands[4]["parallel_group_path"][0]["selection_member_kind"],
18490            json!("group")
18491        );
18492        assert_eq!(
18493            commands[5]["parallel_group_path"][0]["selection_member_kind"],
18494            json!("group")
18495        );
18496
18497        let one_leaf_ctx = workflow_context(Vec::new());
18498        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
18499            ParallelOperation::activity("nested-only", json!([])),
18500        ])]));
18501        assert!(matches!(
18502            one_leaf.as_mut().poll(&mut task_context),
18503            Poll::Pending
18504        ));
18505        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
18506        assert_eq!(one_leaf_commands.len(), 1);
18507        assert_eq!(
18508            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
18509            json!("group")
18510        );
18511        assert_eq!(
18512            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
18513            json!(1)
18514        );
18515    }
18516
18517    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
18518        let mut saga = ctx.saga();
18519        let outcome = async {
18520            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18521            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18522            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
18523            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
18524            ctx.activity("trip.charge", json!([])).await?;
18525            Ok(json!({"status": "booked"}))
18526        }
18527        .await;
18528        saga.finish(outcome).await
18529    }
18530
18531    fn saga_activity(
18532        event_type: &str,
18533        sequence: u64,
18534        activity_type: &str,
18535        result: Option<Value>,
18536    ) -> HistoryEvent {
18537        let mut payload = json!({
18538            "sequence": sequence,
18539            "activity_type": activity_type,
18540            "message": format!("{activity_type} failed"),
18541            "exception_type": "PlannedFailure",
18542            "non_retryable": true,
18543        });
18544        if let Some(result) = result {
18545            payload["result"] = fixture_envelope(result);
18546        }
18547        history_event(event_type, payload)
18548    }
18549
18550    #[test]
18551    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
18552        let completed_hotel_compensation = saga_activity(
18553            "ActivityCompleted",
18554            4,
18555            "trip.cancel-hotel",
18556            Some(Value::Null),
18557        );
18558        let history = vec![
18559            saga_activity(
18560                "ActivityCompleted",
18561                1,
18562                "trip.reserve-flight",
18563                Some(json!("flight-1")),
18564            ),
18565            saga_activity(
18566                "ActivityCompleted",
18567                2,
18568                "trip.reserve-hotel",
18569                Some(json!("hotel-1")),
18570            ),
18571            saga_activity("ActivityFailed", 3, "trip.charge", None),
18572            completed_hotel_compensation.clone(),
18573            completed_hotel_compensation,
18574        ];
18575
18576        for _restart in 0..2 {
18577            let ctx = workflow_context(history.clone());
18578            let mut future = Box::pin(trip_saga(ctx.clone()));
18579            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18580            assert!(matches!(
18581                future.as_mut().poll(&mut task_context),
18582                Poll::Pending
18583            ));
18584            let commands = ctx.take_commands().expect("compensation command");
18585            assert_eq!(commands.len(), 1);
18586            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18587        }
18588    }
18589
18590    #[test]
18591    fn saga_compensation_failure_preserves_both_typed_failures() {
18592        let history = vec![
18593            saga_activity(
18594                "ActivityCompleted",
18595                1,
18596                "trip.reserve-flight",
18597                Some(json!("flight-1")),
18598            ),
18599            saga_activity(
18600                "ActivityCompleted",
18601                2,
18602                "trip.reserve-hotel",
18603                Some(json!("hotel-1")),
18604            ),
18605            saga_activity("ActivityFailed", 3, "trip.charge", None),
18606            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
18607        ];
18608        let ctx = workflow_context(history);
18609        let mut future = Box::pin(trip_saga(ctx));
18610        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18611        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
18612            future.as_mut().poll(&mut task_context)
18613        else {
18614            panic!("compensation failure must remain structured");
18615        };
18616        assert!(matches!(
18617            *failure.initiating_failure,
18618            Error::ActivityFailed(_)
18619        ));
18620        assert!(matches!(
18621            *failure.compensation_failure,
18622            Error::ActivityFailed(_)
18623        ));
18624        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
18625        assert_eq!(failure.compensation_registration_order, 2);
18626    }
18627
18628    #[test]
18629    fn saga_compensates_cooperative_cancellation() {
18630        let ctx = workflow_context(vec![saga_activity(
18631            "ActivityCompleted",
18632            1,
18633            "trip.reserve-flight",
18634            Some(json!("flight-1")),
18635        )]);
18636        ctx.state.lock().expect("state").cancel_requested = true;
18637        let run = {
18638            let ctx = ctx.clone();
18639            async move {
18640                let mut saga = ctx.saga();
18641                let outcome = async {
18642                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18643                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18644                    ctx.throw_if_cancellation_requested()?;
18645                    Ok(json!("unexpected"))
18646                }
18647                .await;
18648                saga.finish(outcome).await
18649            }
18650        };
18651        let mut future = Box::pin(run);
18652        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18653        assert!(matches!(
18654            future.as_mut().poll(&mut task_context),
18655            Poll::Pending
18656        ));
18657        let commands = ctx.take_commands().expect("cancellation compensation");
18658        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18659    }
18660
18661    fn workflow_task(
18662        workflow_type: &str,
18663        history_events: Vec<HistoryEvent>,
18664        payload_codec: &str,
18665    ) -> WorkflowTask {
18666        WorkflowTask {
18667            task_id: format!("wft-{workflow_type}"),
18668            workflow_command_id: None,
18669            workflow_id: Some(format!("wf-{workflow_type}")),
18670            run_id: Some(format!("run-{workflow_type}")),
18671            workflow_type: workflow_type.to_string(),
18672            cancel_requested: false,
18673            payload_codec: payload_codec.to_string(),
18674            arguments: Some(
18675                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
18676            ),
18677            total_history_events: Some(history_events.len() as u64),
18678            history_size_bytes: None,
18679            continue_as_new_recommended: None,
18680            history_budget_pressure: None,
18681            history_events,
18682            next_history_page_token: None,
18683            workflow_task_attempt: 1,
18684            workflow_signal_id: None,
18685            signal_name: None,
18686            signal_arguments: None,
18687            workflow_update_id: None,
18688            update_name: None,
18689            lease_owner: Some("rust-worker".to_string()),
18690        }
18691    }
18692
18693    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18694    struct SideEffectProbe {
18695        request_id: String,
18696        attempt: u32,
18697    }
18698
18699    #[test]
18700    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
18701        let calls = AtomicUsize::new(0);
18702        let ctx = workflow_context(Vec::new());
18703        let value = ctx
18704            .side_effect(|| {
18705                calls.fetch_add(1, Ordering::SeqCst);
18706                SideEffectProbe {
18707                    request_id: "request-42".to_string(),
18708                    attempt: 3,
18709                }
18710            })
18711            .expect("first side effect");
18712        assert_eq!(value.attempt, 3);
18713        assert_eq!(calls.load(Ordering::SeqCst), 1);
18714        let commands = ctx.take_commands().expect("commands");
18715        assert_eq!(commands.len(), 1);
18716        assert_eq!(commands[0]["type"], "record_side_effect");
18717        assert_eq!(
18718            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18719            serde_json::to_value(&value).expect("value")
18720        );
18721
18722        let replay = workflow_context(vec![history_event(
18723            "SideEffectRecorded",
18724            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18725        )]);
18726        let replayed: SideEffectProbe = replay
18727            .side_effect(|| {
18728                calls.fetch_add(1, Ordering::SeqCst);
18729                panic!("committed side-effect callbacks must not run during replay")
18730            })
18731            .expect("replayed side effect");
18732        assert_eq!(replayed, value);
18733        assert_eq!(calls.load(Ordering::SeqCst), 1);
18734        assert!(replay.take_commands().expect("commands").is_empty());
18735        replay.ensure_history_consumed().expect("history consumed");
18736    }
18737
18738    #[test]
18739    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
18740        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18741        let value = ctx
18742            .side_effect(|| SideEffectProbe {
18743                request_id: "avro-request".to_string(),
18744                attempt: 1,
18745            })
18746            .expect("Avro side effect");
18747        let uuid = ctx.uuid_v4().expect("deterministic UUID");
18748        let commands = ctx.take_commands().expect("commands");
18749        assert_eq!(commands.len(), 2);
18750        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
18751        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
18752        assert_eq!(
18753            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18754            serde_json::to_value(&value).expect("value")
18755        );
18756
18757        let replay = workflow_context_with_codec(
18758            vec![
18759                history_event(
18760                    "SideEffectRecorded",
18761                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18762                ),
18763                history_event(
18764                    "SideEffectRecorded",
18765                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
18766                ),
18767            ],
18768            DEFAULT_CODEC,
18769        );
18770        let replayed: SideEffectProbe = replay
18771            .side_effect(|| panic!("Avro callback must not run"))
18772            .expect("replayed Avro value");
18773        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
18774        assert_eq!(replayed, value);
18775        assert_eq!(replayed_uuid, uuid);
18776        assert!(replay.take_commands().expect("commands").is_empty());
18777    }
18778
18779    #[test]
18780    fn typed_side_effect_replay_preserves_bytes_and_maps() {
18781        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18782        let value = ctx
18783            .side_effect_avro_value(typed_fidelity_probe)
18784            .expect("typed side effect");
18785        let commands = ctx.take_commands().expect("side-effect command");
18786        assert_eq!(
18787            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
18788                .expect("recorded side effect"),
18789            value
18790        );
18791
18792        let replay = workflow_context_with_codec(
18793            vec![history_event(
18794                "SideEffectRecorded",
18795                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18796            )],
18797            DEFAULT_CODEC,
18798        );
18799        assert_eq!(
18800            replay
18801                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
18802                .expect("replayed typed side effect"),
18803            value
18804        );
18805    }
18806
18807    #[test]
18808    fn ordered_side_effects_share_the_durable_command_stream() {
18809        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
18810        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
18811        let ctx = workflow_context(vec![
18812            history_event(
18813                "SideEffectRecorded",
18814                json!({"sequence": 1, "result": first}),
18815            ),
18816            history_event(
18817                "SideEffectRecorded",
18818                json!({"sequence": 2, "result": second}),
18819            ),
18820        ]);
18821        let first: String = ctx
18822            .side_effect(|| panic!("first callback must not run"))
18823            .expect("first replay");
18824        let second: i32 = ctx
18825            .side_effect(|| panic!("second callback must not run"))
18826            .expect("second replay");
18827        assert_eq!(first, "first");
18828        assert_eq!(second, 29);
18829        ctx.ensure_history_consumed().expect("ordered history");
18830
18831        let reordered = workflow_context(vec![history_event(
18832            "VersionMarkerRecorded",
18833            json!({
18834                "sequence": 1,
18835                "change_id": "before-side-effect",
18836                "version": 1,
18837                "min_supported": 1,
18838                "max_supported": 1,
18839            }),
18840        )]);
18841        let error = reordered
18842            .side_effect(|| "new".to_string())
18843            .expect_err("command reordering must fail");
18844        assert!(matches!(
18845            error,
18846            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18847                if reason == "recorded_command_mismatch"
18848        ));
18849    }
18850
18851    #[test]
18852    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
18853        let ctx = workflow_context(Vec::new());
18854        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
18855        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
18856        assert!(ctx.patched("new-search").expect("patch"));
18857        ctx.deprecate_patch("new-search").expect("deprecate patch");
18858        let commands = ctx.take_commands().expect("commands");
18859        assert_eq!(commands.len(), 2);
18860        assert_eq!(commands[0]["type"], "record_version_marker");
18861        assert_eq!(commands[0]["version"], 2);
18862        assert_eq!(commands[1]["change_id"], "new-search");
18863
18864        let replay = workflow_context(vec![history_event(
18865            "VersionMarkerRecorded",
18866            json!({
18867                "sequence": 1,
18868                "change_id": "checkout-v2",
18869                "version": 2,
18870                "min_supported": 1,
18871                "max_supported": 2,
18872            }),
18873        )]);
18874        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
18875        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
18876        assert!(replay.take_commands().expect("commands").is_empty());
18877        replay.ensure_history_consumed().expect("history consumed");
18878    }
18879
18880    #[test]
18881    fn version_markers_reject_incompatible_or_malformed_history() {
18882        let incompatible = workflow_context(vec![history_event(
18883            "VersionMarkerRecorded",
18884            json!({
18885                "sequence": 1,
18886                "change_id": "checkout-v2",
18887                "version": 1,
18888                "min_supported": 1,
18889                "max_supported": 2,
18890            }),
18891        )]);
18892        let error = incompatible
18893            .get_version("checkout-v2", 2, 3)
18894            .expect_err("old version is unsupported");
18895        assert!(matches!(
18896            error,
18897            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
18898                if reason == "version_marker_incompatible_range"
18899        ));
18900
18901        for (history, reason) in [
18902            (
18903                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
18904                "side_effect_result_missing",
18905            ),
18906            (
18907                vec![history_event(
18908                    "SideEffectRecorded",
18909                    json!({
18910                        "sequence": 1,
18911                        "result": {"codec": "avro", "blob": "not-base64"},
18912                    }),
18913                )],
18914                "side_effect_payload_incompatible",
18915            ),
18916            (
18917                vec![history_event(
18918                    "SideEffectRecorded",
18919                    json!({"sequence": 1, "result": {"unwrapped": true}}),
18920                )],
18921                "side_effect_payload_malformed",
18922            ),
18923            (
18924                vec![history_event(
18925                    "VersionMarkerRecorded",
18926                    json!({
18927                        "sequence": 1,
18928                        "change_id": "change",
18929                        "version": 1,
18930                        "min_supported": 2,
18931                        "max_supported": 1,
18932                    }),
18933                )],
18934                "version_marker_history_range_invalid",
18935            ),
18936        ] {
18937            let error = WorkflowState::new(
18938                history,
18939                "rust-workers".to_string(),
18940                DEFAULT_CODEC.to_string(),
18941                None,
18942            )
18943            .expect_err("malformed history must fail");
18944            assert!(matches!(
18945                error,
18946                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
18947                    if actual == reason
18948            ));
18949        }
18950    }
18951
18952    #[test]
18953    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
18954        let history = vec![history_event(
18955            "SearchAttributesUpserted",
18956            json!({
18957                "sequence": 1,
18958                "attributes": {"customer_tier": "gold"},
18959                "attribute_types": {"customer_tier": "keyword"},
18960                "merged": {"customer_tier": "gold"}
18961            }),
18962        )];
18963
18964        let matching = workflow_context(history.clone());
18965        matching
18966            .upsert_search_attributes(
18967                SearchAttributeUpdate::new()
18968                    .keyword("customer_tier", "gold")
18969                    .expect("keyword update"),
18970            )
18971            .expect("matching typed update must replay");
18972        matching
18973            .ensure_history_consumed()
18974            .expect("history consumed");
18975
18976        let changed_type = workflow_context(history.clone());
18977        let error = changed_type
18978            .upsert_search_attributes(
18979                SearchAttributeUpdate::new()
18980                    .string("customer_tier", "gold")
18981                    .expect("string update"),
18982            )
18983            .expect_err("same JSON value with a different declaration must be nondeterministic");
18984        let Error::NonDeterministicReplay(failure) = error else {
18985            panic!("typed identity drift must be a replay failure");
18986        };
18987        assert_eq!(failure.reason, "search_attribute_type_mismatch");
18988        assert_eq!(failure.sequence, Some(1));
18989
18990        let changed_value = workflow_context(history);
18991        let error = changed_value
18992            .upsert_search_attributes(
18993                SearchAttributeUpdate::new()
18994                    .keyword("customer_tier", "platinum")
18995                    .expect("keyword update"),
18996            )
18997            .expect_err("changed values must be nondeterministic");
18998        let Error::NonDeterministicReplay(failure) = error else {
18999            panic!("value drift must be a replay failure");
19000        };
19001        assert_eq!(failure.reason, "search_attribute_value_mismatch");
19002    }
19003
19004    #[test]
19005    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
19006        let history = vec![history_event(
19007            "SearchAttributesUpserted",
19008            json!({
19009                "sequence": 1,
19010                "attributes": {"customer_tier": "gold"},
19011                "merged": {"customer_tier": "gold"}
19012            }),
19013        )];
19014
19015        for update in [
19016            SearchAttributeUpdate::new()
19017                .keyword("customer_tier", "gold")
19018                .expect("keyword update"),
19019            SearchAttributeUpdate::new()
19020                .string("customer_tier", "gold")
19021                .expect("string update"),
19022        ] {
19023            let restarted = workflow_context(history.clone());
19024            restarted
19025                .upsert_search_attributes(update)
19026                .expect("legacy history constrains values but has unknown type identity");
19027            restarted
19028                .ensure_history_consumed()
19029                .expect("history consumed");
19030        }
19031    }
19032
19033    #[test]
19034    fn search_attribute_command_emits_canonical_types() {
19035        let ctx = workflow_context(Vec::new());
19036        ctx.upsert_search_attributes(
19037            SearchAttributeUpdate::new()
19038                .keyword("customer_tier", "gold")
19039                .expect("keyword update")
19040                .int("attempts", 3)
19041                .expect("int update")
19042                .delete("obsolete")
19043                .expect("delete update"),
19044        )
19045        .expect("valid search attributes");
19046
19047        assert_eq!(
19048            ctx.take_commands().expect("commands"),
19049            vec![json!({
19050                "type": "upsert_search_attributes",
19051                "attributes": {
19052                    "attempts": 3,
19053                    "customer_tier": "gold",
19054                    "obsolete": null
19055                },
19056                "attribute_types": {
19057                    "attempts": "int",
19058                    "customer_tier": "keyword"
19059                }
19060            })]
19061        );
19062    }
19063
19064    #[test]
19065    fn duplicate_side_effects_and_version_markers_are_rejected() {
19066        let duplicate_side_effect = WorkflowState::new(
19067            vec![
19068                history_event(
19069                    "SideEffectRecorded",
19070                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
19071                ),
19072                history_event(
19073                    "SideEffectRecorded",
19074                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
19075                ),
19076            ],
19077            "rust-workers".to_string(),
19078            DEFAULT_CODEC.to_string(),
19079            None,
19080        )
19081        .expect_err("duplicate side effect");
19082        assert!(matches!(
19083            duplicate_side_effect,
19084            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19085                if reason == "duplicate_side_effect_record"
19086        ));
19087
19088        let marker = |sequence| {
19089            history_event(
19090                "VersionMarkerRecorded",
19091                json!({
19092                    "sequence": sequence,
19093                    "change_id": "same-change",
19094                    "version": 1,
19095                    "min_supported": 1,
19096                    "max_supported": 1,
19097                }),
19098            )
19099        };
19100        let duplicate_marker = WorkflowState::new(
19101            vec![marker(1), marker(3)],
19102            "rust-workers".to_string(),
19103            DEFAULT_CODEC.to_string(),
19104            None,
19105        )
19106        .expect_err("duplicate marker");
19107        assert!(matches!(
19108            duplicate_marker,
19109            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19110                if reason == "duplicate_version_marker"
19111        ));
19112    }
19113
19114    #[test]
19115    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
19116        let mut state = WorkflowState::new(
19117            Vec::new(),
19118            "rust-workers".to_string(),
19119            DEFAULT_CODEC.to_string(),
19120            None,
19121        )
19122        .expect("workflow state");
19123        state.workflow_command_identity = "command-7".to_string();
19124        let context = WorkflowContext {
19125            state: Arc::new(Mutex::new(state)),
19126            cancellation_scope_id: "root".into(),
19127        };
19128        let item =
19129            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
19130
19131        context
19132            .append_workflow_stream("output", &[item], Some(10))
19133            .expect("append command");
19134        context
19135            .error_workflow_stream("output", "producer failed", None)
19136            .expect("error command");
19137        let commands = context.take_commands().expect("commands");
19138
19139        assert_eq!(commands[0]["type"], "record_side_effect");
19140        assert_eq!(
19141            commands[0]["workflow_stream"]["command_identity"],
19142            "command-7"
19143        );
19144        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
19145        assert_eq!(
19146            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19147            "dw-stream:command-7:0:0"
19148        );
19149        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
19150
19151        let recorded = history_event(
19152            "SideEffectRecorded",
19153            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
19154        );
19155        let mut replay_state = WorkflowState::new(
19156            vec![recorded],
19157            "rust-workers".to_string(),
19158            DEFAULT_CODEC.to_string(),
19159            None,
19160        )
19161        .expect("replay state");
19162        replay_state.workflow_command_identity = "command-7".to_string();
19163        let replay_context = WorkflowContext {
19164            state: Arc::new(Mutex::new(replay_state)),
19165            cancellation_scope_id: "root".into(),
19166        };
19167        replay_context
19168            .append_workflow_stream(
19169                "output",
19170                &[WorkflowStreamAppendItem::from_reference(
19171                    "s3://bucket/item.avro",
19172                )],
19173                Some(10),
19174            )
19175            .expect("replayed append");
19176        assert!(replay_context
19177            .take_commands()
19178            .expect("replayed commands")
19179            .is_empty());
19180    }
19181
19182    #[test]
19183    fn workflow_stream_authoring_requires_server_durable_command_identity() {
19184        let context = workflow_context(Vec::new());
19185        let error = context
19186            .append_workflow_stream(
19187                "output",
19188                &[WorkflowStreamAppendItem::from_reference(
19189                    "s3://bucket/item.avro",
19190                )],
19191                None,
19192            )
19193            .expect_err("stream append without durable command identity must fail closed");
19194
19195        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
19196        assert!(context.take_commands().expect("commands").is_empty());
19197    }
19198
19199    #[test]
19200    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
19201        let client = Client::builder("http://localhost:8080").build().unwrap();
19202        let mut worker = Worker::new(client, "rust-workers");
19203        worker.register_workflow("streams.worker", |ctx, _| async move {
19204            ctx.append_workflow_stream(
19205                "output",
19206                &[WorkflowStreamAppendItem::new(json!("hello"))?],
19207                None,
19208            )?;
19209            ctx.close_workflow_stream("output", None)?;
19210            Ok(json!("done"))
19211        });
19212        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
19213            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
19214            task.workflow_command_id = command_id.clone();
19215            let expected_identity = command_id
19216                .as_deref()
19217                .filter(|id| !id.is_empty())
19218                .unwrap_or(&task.task_id)
19219                .to_string();
19220            let commands = worker
19221                .execute_workflow_task(task)
19222                .expect("ordinary worker stream output");
19223            assert_eq!(commands.len(), 3);
19224            assert_eq!(
19225                commands[0]["workflow_stream"]["command_identity"],
19226                expected_identity
19227            );
19228            assert_eq!(
19229                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19230                format!("dw-stream:{expected_identity}:0:0")
19231            );
19232            assert_eq!(
19233                commands[1]["workflow_stream"]["command_identity"],
19234                expected_identity
19235            );
19236            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
19237            let history = commands[..2]
19238                .iter()
19239                .enumerate()
19240                .map(|(index, command)| {
19241                    history_event(
19242                        "SideEffectRecorded",
19243                        json!({"sequence":index + 1,"result":command["result"]}),
19244                    )
19245                })
19246                .collect();
19247            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
19248            replay.task_id = "replacement-task".to_string();
19249            let replayed = worker
19250                .execute_workflow_task(replay)
19251                .expect("replacement worker consumes recorded stream effects");
19252            assert_eq!(replayed.len(), 1);
19253            assert_eq!(replayed[0]["type"], "complete_workflow");
19254        }
19255        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
19256        missing.task_id.clear();
19257        assert!(matches!(
19258            worker.execute_workflow_task(missing),
19259            Err(Error::MissingWorkflowCommandIdentity)
19260        ));
19261    }
19262
19263    #[test]
19264    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
19265        fn worker(calls: Arc<AtomicUsize>) -> Worker {
19266            let client = Client::new("http://127.0.0.1:8080").expect("client");
19267            let mut worker = Worker::new(client, "rust-workers");
19268            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
19269                let calls = Arc::clone(&calls);
19270                async move {
19271                    let captured = ctx.side_effect(|| {
19272                        calls.fetch_add(1, Ordering::SeqCst);
19273                        "captured-once".to_string()
19274                    })?;
19275                    let version = ctx.get_version("cold-restart", 1, 2)?;
19276                    Ok(json!({"captured": captured, "version": version}))
19277                }
19278            });
19279            worker
19280        }
19281
19282        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
19283            WorkflowTask {
19284                task_id: "wft-side-effect-version".to_string(),
19285                workflow_command_id: None,
19286                workflow_id: Some("wf-side-effect-version".to_string()),
19287                run_id: Some("run-side-effect-version".to_string()),
19288                workflow_type: "rust.side-effect-version".to_string(),
19289                cancel_requested: false,
19290                payload_codec: DEFAULT_CODEC.to_string(),
19291                arguments: Some(
19292                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
19293                ),
19294                history_events,
19295                total_history_events: None,
19296                history_size_bytes: None,
19297                continue_as_new_recommended: None,
19298                history_budget_pressure: None,
19299                next_history_page_token: None,
19300                workflow_task_attempt: 1,
19301                workflow_signal_id: None,
19302                signal_name: None,
19303                signal_arguments: None,
19304                workflow_update_id: None,
19305                update_name: None,
19306                lease_owner: Some("rust-worker".to_string()),
19307            }
19308        }
19309
19310        let calls = Arc::new(AtomicUsize::new(0));
19311        let initial = worker(Arc::clone(&calls))
19312            .execute_workflow_task(task(Vec::new()))
19313            .expect("initial execution");
19314        assert_eq!(
19315            initial
19316                .iter()
19317                .map(|command| &command["type"])
19318                .collect::<Vec<_>>(),
19319            vec![
19320                "record_side_effect",
19321                "record_version_marker",
19322                "complete_workflow"
19323            ]
19324        );
19325        assert_eq!(calls.load(Ordering::SeqCst), 1);
19326
19327        let restarted = worker(Arc::clone(&calls));
19328        let replayed = restarted
19329            .execute_workflow_task(task(vec![
19330                history_event(
19331                    "SideEffectRecorded",
19332                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
19333                ),
19334                history_event(
19335                    "VersionMarkerRecorded",
19336                    json!({
19337                        "sequence": 2,
19338                        "change_id": "cold-restart",
19339                        "version": 2,
19340                        "min_supported": 1,
19341                        "max_supported": 2,
19342                    }),
19343                ),
19344            ]))
19345            .expect("cold replay");
19346        assert_eq!(replayed.len(), 1);
19347        assert_eq!(replayed[0]["type"], "complete_workflow");
19348        assert_eq!(calls.load(Ordering::SeqCst), 1);
19349    }
19350
19351    #[test]
19352    fn side_effect_replay_rejects_changed_rust_value_type() {
19353        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
19354        let ctx = workflow_context(vec![history_event(
19355            "SideEffectRecorded",
19356            json!({"sequence": 1, "result": result}),
19357        )]);
19358        let error = ctx
19359            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
19360            .expect_err("changed type must fail replay");
19361        assert!(matches!(
19362            error,
19363            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19364                if reason == "side_effect_type_mismatch"
19365        ));
19366    }
19367
19368    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
19369        vec![
19370            history_event(
19371                "ActivityScheduled",
19372                json!({
19373                    "sequence": 1,
19374                    "activity_type": "flaky",
19375                    "activity_execution_id": "act-1",
19376                    "activity": {
19377                        "id": "act-1",
19378                        "sequence": 1,
19379                        "type": "flaky",
19380                        "queue": "critical-activities",
19381                        "execution_mode": null,
19382                        "retry_policy": {
19383                            "snapshot_version": 1,
19384                            "max_attempts": 3,
19385                            "backoff_seconds": [2, 4],
19386                            "start_to_close_timeout": 30,
19387                            "schedule_to_start_timeout": 5,
19388                            "schedule_to_close_timeout": 90,
19389                            "heartbeat_timeout": 10,
19390                            "non_retryable_error_types": ["PermanentError"]
19391                        }
19392                    }
19393                }),
19394            ),
19395            history_event(
19396                "ActivityStarted",
19397                json!({
19398                    "sequence": 1,
19399                    "activity_type": "flaky",
19400                    "activity_execution_id": "act-1",
19401                    "activity_attempt_id": "attempt-1",
19402                    "attempt_number": 1
19403                }),
19404            ),
19405            history_event(
19406                "ActivityRetryScheduled",
19407                json!({
19408                    "sequence": 1,
19409                    "activity_type": "flaky",
19410                    "activity_execution_id": "act-1",
19411                    "activity_attempt_id": "attempt-1",
19412                    "attempt_number": 1,
19413                    "retry_after_attempt": 1,
19414                    "retry_backoff_seconds": 2,
19415                    "failure_category": "activity",
19416                    "exception_type": "TransientError"
19417                }),
19418            ),
19419            history_event(
19420                "ActivityStarted",
19421                json!({
19422                    "sequence": 1,
19423                    "activity_type": "flaky",
19424                    "activity_execution_id": "act-1",
19425                    "activity_attempt_id": "attempt-2",
19426                    "attempt_number": 2
19427                }),
19428            ),
19429            history_event(
19430                "ActivityCompleted",
19431                json!({
19432                    "sequence": 1,
19433                    "activity_type": "flaky",
19434                    "activity_execution_id": "act-1",
19435                    "activity_attempt_id": "attempt-2",
19436                    "attempt_number": 2,
19437                    "payload_codec": DEFAULT_CODEC,
19438                    "result": fixture_envelope(json!({"status":"recovered"}))
19439                }),
19440            ),
19441        ]
19442    }
19443
19444    fn retry_activity_options() -> ActivityOptions {
19445        ActivityOptions::new()
19446            .task_queue("critical-activities")
19447            .retry_policy(
19448                ActivityRetryPolicy::new(3)
19449                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
19450                    .non_retryable_error_type("PermanentError"),
19451            )
19452            .start_to_close_timeout(Duration::from_secs(30))
19453            .schedule_to_start_timeout(Duration::from_secs(5))
19454            .schedule_to_close_timeout(Duration::from_secs(90))
19455            .heartbeat_timeout(Duration::from_secs(10))
19456    }
19457
19458    #[test]
19459    fn fixed_avro_value_round_trips_json_values() {
19460        let value = json!({"greeting": "hello", "count": 3, "ok": true});
19461        let envelope = PayloadEnvelope::avro(&value).expect("encode");
19462        assert_eq!(envelope.codec, DEFAULT_CODEC);
19463        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
19464    }
19465
19466    #[tokio::test]
19467    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
19468        let client = Client::new("http://127.0.0.1:8080").expect("client");
19469        let mut worker = Worker::new(client, "rust-workers");
19470        worker.register_typed_workflow(
19471            "typed.contract.workflow",
19472            |_ctx, input: TypedContract| async move { Ok(input) },
19473        );
19474        worker.register_typed_activity(
19475            "typed.contract.activity",
19476            |_ctx, input: TypedContract| async move { Ok(input) },
19477        );
19478
19479        let expected = typed_contract();
19480        let arguments = AvroValue::Array(vec![
19481            AvroValue::from_serialize(&expected).expect("typed request")
19482        ]);
19483        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
19484        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
19485        workflow.arguments = Some(envelope.clone());
19486        let commands = worker
19487            .execute_workflow_task(workflow)
19488            .expect("typed workflow task");
19489        let workflow_result: TypedContract =
19490            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19491                .expect("workflow result envelope")
19492                .deserialize()
19493                .expect("workflow result type");
19494        assert_eq!(workflow_result, expected);
19495
19496        let activity = ActivityTask {
19497            task_id: "typed-contract-activity".to_string(),
19498            activity_attempt_id: Some("typed-contract-attempt".to_string()),
19499            attempt_id: None,
19500            activity_type: "typed.contract.activity".to_string(),
19501            payload_codec: DEFAULT_CODEC.to_string(),
19502            arguments: Some(envelope),
19503            attempt_number: 1,
19504            lease_owner: Some("rust-worker".to_string()),
19505        };
19506        let activity_result: TypedContract = worker
19507            .execute_activity_task(activity)
19508            .await
19509            .expect("typed activity task")
19510            .deserialize()
19511            .expect("activity result type");
19512        assert_eq!(activity_result, expected);
19513    }
19514
19515    #[tokio::test]
19516    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
19517        let client = Client::new("http://127.0.0.1:8080").expect("client");
19518        let mut worker = Worker::new(client, "rust-workers");
19519        worker.register_typed_workflow(
19520            "typed.shape.workflow",
19521            |_ctx, input: TypedContract| async move { Ok(input) },
19522        );
19523        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
19524            Ok(f64::NAN)
19525        });
19526
19527        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
19528        workflow.arguments = Some(
19529            encode_typed_envelope(
19530                &AvroValue::Array(vec![
19531                    AvroValue::String("first".to_string()),
19532                    AvroValue::String("second".to_string()),
19533                ]),
19534                DEFAULT_CODEC,
19535            )
19536            .expect("malformed typed arguments"),
19537        );
19538        let commands = worker
19539            .execute_workflow_task(workflow)
19540            .expect("shape mismatch becomes a workflow failure");
19541        let message = commands[0]["message"].as_str().expect("failure message");
19542        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
19543        assert!(message.contains(type_name::<TypedContract>()));
19544        assert!(message.contains("task carried 2 arguments"));
19545
19546        let activity = ActivityTask {
19547            task_id: "typed-unsupported-activity".to_string(),
19548            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
19549            attempt_id: None,
19550            activity_type: "typed.unsupported.activity".to_string(),
19551            payload_codec: DEFAULT_CODEC.to_string(),
19552            arguments: Some(
19553                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19554                    .expect("unit arguments"),
19555            ),
19556            attempt_number: 1,
19557            lease_owner: Some("rust-worker".to_string()),
19558        };
19559        let Error::HandlerType {
19560            handler_kind,
19561            handler_name,
19562            value_kind,
19563            rust_type,
19564            message,
19565        } = worker
19566            .execute_activity_task(activity)
19567            .await
19568            .expect_err("non-finite handler output must fail")
19569        else {
19570            panic!("expected contextual handler type failure");
19571        };
19572        assert_eq!(handler_kind, HandlerKind::Activity);
19573        assert_eq!(handler_name, "typed.unsupported.activity");
19574        assert_eq!(value_kind, HandlerValueKind::Result);
19575        assert_eq!(rust_type, type_name::<f64>());
19576        assert!(message.contains("non_finite_float"));
19577    }
19578
19579    #[tokio::test]
19580    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
19581        #[derive(Clone, Default)]
19582        struct State {
19583            observed: Option<TypedContract>,
19584        }
19585
19586        let client = Client::new("http://127.0.0.1:8080").expect("client");
19587        let mut worker = Worker::new(client, "rust-workers");
19588        worker.register_typed_replayed_workflow(
19589            "typed.contract.replayed",
19590            State::default,
19591            |ctx, input: TypedContract, state| async move {
19592                let result: TypedContract =
19593                    ctx.activity_typed("typed.contract.activity", input).await?;
19594                state.update(|current| current.observed = Some(result.clone()))?;
19595                Ok(result)
19596            },
19597        );
19598        worker.register_replayed_query::<State, _, _>(
19599            "typed.contract.replayed",
19600            "observed",
19601            |_ctx, state, _args| async move {
19602                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
19603            },
19604        );
19605
19606        let expected = typed_contract();
19607        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
19608        let workflow_arguments =
19609            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
19610                .expect("workflow arguments");
19611        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
19612        let task = QueryTask {
19613            query_task_id: "typed-replay-query".to_string(),
19614            query_task_attempt: 1,
19615            lease_owner: Some("rust-worker".to_string()),
19616            workflow_id: Some("typed-replay".to_string()),
19617            run_id: Some("typed-replay-run".to_string()),
19618            workflow_type: "typed.contract.replayed".to_string(),
19619            query_name: "observed".to_string(),
19620            payload_codec: DEFAULT_CODEC.to_string(),
19621            workflow_arguments: Some(workflow_arguments),
19622            query_arguments: Some(
19623                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19624                    .expect("query arguments"),
19625            ),
19626            history_events: vec![
19627                history_event(
19628                    "ActivityScheduled",
19629                    json!({
19630                        "sequence": 1,
19631                        "activity_type": "typed.contract.activity"
19632                    }),
19633                ),
19634                history_event(
19635                    "ActivityCompleted",
19636                    json!({
19637                        "sequence": 1,
19638                        "activity_type": "typed.contract.activity",
19639                        "payload_codec": DEFAULT_CODEC,
19640                        "result": result
19641                    }),
19642                ),
19643            ],
19644            history_export: None,
19645            run_status: Some("completed".to_string()),
19646        };
19647
19648        assert_eq!(
19649            worker
19650                .execute_query_task(task)
19651                .await
19652                .expect("typed replay query")
19653                .deserialize::<i64>()
19654                .expect("query result"),
19655            expected.signed
19656        );
19657    }
19658
19659    #[tokio::test]
19660    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
19661        let client = Client::new("http://127.0.0.1:8080").expect("client");
19662        let mut worker = Worker::new(client, "rust-workers");
19663        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
19664        worker
19665            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
19666        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
19667            Ok(input)
19668        });
19669        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
19670            Ok(input)
19671        });
19672        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
19673            Ok(AvroValue::Array(
19674                ctx.wait_signal_avro_value("changed").await?,
19675            ))
19676        });
19677
19678        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
19679        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
19680
19681        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
19682        workflow.arguments = Some(envelope.clone());
19683        let commands = worker
19684            .execute_workflow_task(workflow)
19685            .expect("typed workflow task");
19686        assert_eq!(commands[0]["type"], "complete_workflow");
19687        assert_eq!(
19688            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19689                .expect("typed workflow result"),
19690            arguments
19691        );
19692
19693        let activity = ActivityTask {
19694            task_id: "activity-typed".to_string(),
19695            activity_attempt_id: Some("attempt-typed".to_string()),
19696            attempt_id: None,
19697            activity_type: "typed.activity".to_string(),
19698            payload_codec: DEFAULT_CODEC.to_string(),
19699            arguments: Some(envelope.clone()),
19700            attempt_number: 1,
19701            lease_owner: Some("rust-worker".to_string()),
19702        };
19703        assert_eq!(
19704            worker
19705                .execute_activity_task(activity)
19706                .await
19707                .expect("typed activity result"),
19708            arguments
19709        );
19710
19711        let query = QueryTask {
19712            query_task_id: "query-typed".to_string(),
19713            query_task_attempt: 1,
19714            lease_owner: Some("rust-worker".to_string()),
19715            workflow_id: Some("typed-1".to_string()),
19716            run_id: Some("run-typed".to_string()),
19717            workflow_type: "typed.echo".to_string(),
19718            query_name: "inspect".to_string(),
19719            payload_codec: DEFAULT_CODEC.to_string(),
19720            workflow_arguments: Some(
19721                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
19722                    .expect("workflow input"),
19723            ),
19724            query_arguments: Some(envelope.clone()),
19725            history_events: Vec::new(),
19726            history_export: None,
19727            run_status: Some("running".to_string()),
19728        };
19729        assert_eq!(
19730            worker
19731                .execute_query_task(query)
19732                .await
19733                .expect("typed query result"),
19734            arguments
19735        );
19736
19737        let mut update = workflow_task(
19738            "typed.echo",
19739            vec![history_event(
19740                "UpdateAccepted",
19741                json!({
19742                    "update_id": "update-typed",
19743                    "update_name": "replace",
19744                    "arguments": envelope.clone(),
19745                }),
19746            )],
19747            DEFAULT_CODEC,
19748        );
19749        update.workflow_update_id = Some("update-typed".to_string());
19750        update.update_name = Some("replace".to_string());
19751        let commands = worker
19752            .execute_workflow_task(update)
19753            .expect("typed update task");
19754        assert_eq!(commands[0]["type"], "complete_update");
19755        assert_eq!(
19756            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19757                .expect("typed update result"),
19758            arguments
19759        );
19760
19761        let mut signal = workflow_task(
19762            "typed.signal",
19763            vec![history_event(
19764                "SignalReceived",
19765                json!({
19766                    "signal_id": "signal-typed",
19767                    "signal_name": "changed",
19768                    "arguments": envelope.clone(),
19769                }),
19770            )],
19771            DEFAULT_CODEC,
19772        );
19773        signal.workflow_signal_id = Some("signal-typed".to_string());
19774        signal.signal_name = Some("changed".to_string());
19775        signal.signal_arguments = Some(envelope);
19776        let commands = worker
19777            .execute_workflow_task(signal)
19778            .expect("typed signal resume");
19779        assert_eq!(
19780            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19781                .expect("typed signal result"),
19782            arguments
19783        );
19784    }
19785
19786    #[tokio::test]
19787    async fn typed_helpers_never_parse_json_inspection_projection() {
19788        let collision_values = projection_collision_probe();
19789        let expected = AvroValue::Array(collision_values.clone());
19790        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
19791
19792        let activity_context = workflow_context_with_codec(
19793            vec![history_event(
19794                "ActivityCompleted",
19795                json!({
19796                    "sequence": 1,
19797                    "activity_type": "collision.activity",
19798                    "payload_codec": DEFAULT_CODEC,
19799                    "result": envelope.clone(),
19800                }),
19801            )],
19802            DEFAULT_CODEC,
19803        );
19804        assert_eq!(
19805            activity_context
19806                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
19807                .await
19808                .expect("typed activity collision result"),
19809            expected
19810        );
19811
19812        let signal_context = workflow_context_with_codec(
19813            vec![
19814                history_event(
19815                    "SignalWaitOpened",
19816                    json!({"sequence": 1, "signal_name": "collision"}),
19817                ),
19818                history_event(
19819                    "SignalApplied",
19820                    json!({
19821                        "sequence": 1,
19822                        "signal_name": "collision",
19823                        "payload_codec": DEFAULT_CODEC,
19824                        "value": envelope.clone(),
19825                    }),
19826                ),
19827            ],
19828            DEFAULT_CODEC,
19829        );
19830        assert_eq!(
19831            signal_context
19832                .wait_signal_avro_value("collision")
19833                .await
19834                .expect("typed signal collision arguments"),
19835            collision_values
19836        );
19837
19838        let child_context = workflow_context_with_codec(
19839            vec![
19840                history_event(
19841                    "ChildWorkflowScheduled",
19842                    json!({
19843                        "sequence": 1,
19844                        "child_workflow_instance_id": "collision-child",
19845                        "child_workflow_run_id": "collision-run",
19846                        "child_workflow_type": "collision.child",
19847                    }),
19848                ),
19849                history_event(
19850                    "ChildRunCompleted",
19851                    json!({
19852                        "sequence": 1,
19853                        "child_workflow_instance_id": "collision-child",
19854                        "child_workflow_run_id": "collision-run",
19855                        "child_workflow_type": "collision.child",
19856                        "payload_codec": DEFAULT_CODEC,
19857                        "result": envelope,
19858                    }),
19859                ),
19860            ],
19861            DEFAULT_CODEC,
19862        );
19863        let child = child_context
19864            .start_child_workflow_avro_value(
19865                "collision.child",
19866                ChildWorkflowOptions::new("collision-workers"),
19867                AvroValue::Array(Vec::new()),
19868            )
19869            .await
19870            .expect("typed child collision result");
19871        assert_eq!(child.result, expected);
19872    }
19873
19874    #[tokio::test]
19875    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
19876        let client = Client::new("http://127.0.0.1:8080").expect("client");
19877        let mut worker = Worker::new(client, "rust-workers");
19878        worker.register_replayed_workflow_avro_value(
19879            "typed.replayed",
19880            || (),
19881            |_ctx, input, _state| async move { Ok(input) },
19882        );
19883        worker.register_replayed_query_avro_value::<(), _, _>(
19884            "typed.replayed",
19885            "inspect",
19886            |ctx, _state, args| async move {
19887                let mut signals = ctx.signals_avro_value("collision");
19888                let signal = signals
19889                    .pop()
19890                    .map(AvroValue::Array)
19891                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
19892                Ok(AvroValue::Array(vec![
19893                    ctx.workflow_input_avro_value().clone(),
19894                    signal,
19895                    args,
19896                ]))
19897            },
19898        );
19899        let arguments = AvroValue::Array(projection_collision_probe());
19900        let signal_arguments =
19901            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
19902        let task = QueryTask {
19903            query_task_id: "query-typed-replay".to_string(),
19904            query_task_attempt: 1,
19905            lease_owner: Some("rust-worker".to_string()),
19906            workflow_id: Some("typed-replay".to_string()),
19907            run_id: Some("run-typed-replay".to_string()),
19908            workflow_type: "typed.replayed".to_string(),
19909            query_name: "inspect".to_string(),
19910            payload_codec: DEFAULT_CODEC.to_string(),
19911            workflow_arguments: Some(
19912                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
19913            ),
19914            query_arguments: Some(
19915                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
19916            ),
19917            history_events: vec![history_event(
19918                "SignalReceived",
19919                json!({
19920                    "signal_id": "collision-signal",
19921                    "signal_name": "collision",
19922                    "workflow_sequence": 1,
19923                    "payload_codec": DEFAULT_CODEC,
19924                    "arguments": signal_arguments,
19925                }),
19926            )],
19927            history_export: None,
19928            run_status: Some("completed".to_string()),
19929        };
19930
19931        assert_eq!(
19932            worker
19933                .execute_query_task(task)
19934                .await
19935                .expect("typed replay query"),
19936            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
19937        );
19938    }
19939
19940    #[test]
19941    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
19942        let value = BTreeMap::from([(1_i32, "integer key")]);
19943        let error = PayloadEnvelope::avro(&value)
19944            .expect_err("integer map keys must fail")
19945            .to_string();
19946
19947        assert!(error.contains("invalid_map_key"));
19948    }
19949
19950    #[test]
19951    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
19952        let envelope = PayloadEnvelope {
19953            codec: "json".to_string(),
19954            blob: r#"{"greeting":"hello"}"#.to_string(),
19955        };
19956
19957        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
19958        let diagnostic = error.to_string();
19959        assert!(diagnostic.contains("unsupported_payload_codec"));
19960        assert!(diagnostic.contains("codec=\"avro\""));
19961        assert!(diagnostic.contains("HTTP document transport"));
19962    }
19963
19964    #[test]
19965    fn untagged_json_payload_value_fails_closed() {
19966        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
19967            .expect_err("untagged JSON payload values must fail");
19968        let diagnostic = error.to_string();
19969        assert!(diagnostic.contains("unsupported_payload_codec"));
19970        assert!(diagnostic.contains("untagged durable payload"));
19971        assert!(diagnostic.contains("HTTP document transport"));
19972    }
19973
19974    #[test]
19975    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
19976        let envelope = PayloadEnvelope {
19977            codec: DEFAULT_CODEC.to_string(),
19978            blob: BASE64.encode([0x01]),
19979        };
19980
19981        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
19982        assert!(error.to_string().contains("invalid_payload_framing"));
19983    }
19984
19985    #[tokio::test]
19986    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
19987        let server = MockWorkerServer::start();
19988        let client = Client::builder(server.base_url())
19989            .timeout(Duration::from_secs(2))
19990            .build()
19991            .expect("client");
19992        let invalid_commands = [
19993            json!({
19994                "type": "complete_workflow",
19995                "result": {"codec": "json", "blob": null}
19996            }),
19997            json!({
19998                "type": "schedule_activity",
19999                "arguments": {"codec": "yaml", "blob": "ignored"}
20000            }),
20001            json!({
20002                "type": "start_child_workflow",
20003                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
20004            }),
20005            json!({"type": "continue_as_new", "arguments": []}),
20006            json!({"type": "complete_update"}),
20007            json!({"type": "record_side_effect", "result": null}),
20008            json!({
20009                "type": "start_service_operation",
20010                "payload_codec": DEFAULT_CODEC,
20011                "request_payload": "raw-avro-bytes"
20012            }),
20013        ];
20014
20015        for command in invalid_commands {
20016            let error = client
20017                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
20018                .await
20019                .expect_err("invalid durable payload must fail locally");
20020            let diagnostic = error.to_string();
20021            assert!(
20022                diagnostic.contains("unsupported_payload_codec")
20023                    || diagnostic.contains("invalid_payload_envelope")
20024                    || diagnostic.contains("untagged durable payload"),
20025                "unexpected validation diagnostic: {diagnostic}"
20026            );
20027        }
20028
20029        assert_eq!(
20030            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
20031            0,
20032            "invalid command payloads must not reach HTTP transport"
20033        );
20034    }
20035
20036    #[test]
20037    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
20038        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
20039        let commands = [
20040            json!({"type": "complete_workflow", "result": envelope.clone()}),
20041            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
20042            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
20043            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
20044            json!({"type": "complete_update", "result": envelope.clone()}),
20045            json!({"type": "record_side_effect", "result": envelope.clone()}),
20046            json!({
20047                "type": "start_service_operation",
20048                "payload_codec": DEFAULT_CODEC,
20049                "request_payload": envelope.clone()
20050            }),
20051            json!({
20052                "type": "complete_workflow",
20053                "result": envelope,
20054                "metadata": {
20055                    "codec": "json",
20056                    "payload_codec": "customer-codec",
20057                    "result": {"codec": "yaml", "blob": null}
20058                }
20059            }),
20060        ];
20061
20062        validate_workflow_task_commands(&commands)
20063            .expect("customer metadata must not become a protocol codec declaration");
20064    }
20065
20066    #[test]
20067    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
20068        assert_eq!(
20069            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
20070            AvroValue::Array(Vec::new())
20071        );
20072        assert_eq!(
20073            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
20074            AvroValue::Array(Vec::new())
20075        );
20076
20077        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
20078        signal.signal_name = Some("empty-signal".to_string());
20079        signal.signal_arguments = None;
20080        let decoded = decode_resume_signal(&signal)
20081            .expect("valid Avro signal")
20082            .expect("named signal resumes the workflow");
20083        assert!(decoded.arguments.is_empty());
20084    }
20085
20086    #[tokio::test]
20087    async fn malformed_task_level_codecs_become_pre_handler_failures() {
20088        let client = Client::new("http://127.0.0.1:8080").expect("client");
20089        let mut worker = Worker::new(client, "rust-workers");
20090        let handler_calls = Arc::new(AtomicUsize::new(0));
20091
20092        let calls = Arc::clone(&handler_calls);
20093        worker.register_workflow("codec.workflow", move |_ctx, _args| {
20094            calls.fetch_add(1, Ordering::SeqCst);
20095            async move { Ok(Value::Null) }
20096        });
20097        let calls = Arc::clone(&handler_calls);
20098        worker.register_activity("codec.activity", move |_ctx, _args| {
20099            calls.fetch_add(1, Ordering::SeqCst);
20100            async move { Ok(Value::Null) }
20101        });
20102        let calls = Arc::clone(&handler_calls);
20103        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20104            calls.fetch_add(1, Ordering::SeqCst);
20105            async move { Ok(Value::Null) }
20106        });
20107
20108        let mut failures = Vec::new();
20109        for codec_case in [
20110            InvalidTaskPayloadCodec::Missing,
20111            InvalidTaskPayloadCodec::Null,
20112            InvalidTaskPayloadCodec::NonString,
20113        ] {
20114            let mut workflow = json!({
20115                "task_id": format!("workflow-{}", codec_case.label()),
20116                "workflow_type": "codec.workflow"
20117            });
20118            codec_case.apply(&mut workflow);
20119            match serde_json::from_value::<WorkflowTask>(workflow) {
20120                Ok(task) => match worker.execute_workflow_task(task) {
20121                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
20122                    outcome => failures.push(format!(
20123                        "workflow {} codec returned {outcome:?}",
20124                        codec_case.label()
20125                    )),
20126                },
20127                Err(error) => failures.push(format!(
20128                    "workflow {} codec failed transport deserialization: {error}",
20129                    codec_case.label()
20130                )),
20131            }
20132
20133            let mut activity = json!({
20134                "task_id": format!("activity-{}", codec_case.label()),
20135                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
20136                "activity_type": "codec.activity",
20137                "attempt_number": 1
20138            });
20139            codec_case.apply(&mut activity);
20140            match serde_json::from_value::<ActivityTask>(activity) {
20141                Ok(task) => match worker.execute_activity_task(task).await {
20142                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
20143                    outcome => failures.push(format!(
20144                        "activity {} codec returned {outcome:?}",
20145                        codec_case.label()
20146                    )),
20147                },
20148                Err(error) => failures.push(format!(
20149                    "activity {} codec failed transport deserialization: {error}",
20150                    codec_case.label()
20151                )),
20152            }
20153
20154            let mut query = json!({
20155                "query_task_id": format!("query-{}", codec_case.label()),
20156                "workflow_type": "codec.workflow",
20157                "query_name": "known"
20158            });
20159            codec_case.apply(&mut query);
20160            match serde_json::from_value::<QueryTask>(query) {
20161                Ok(task) => match worker.execute_query_task(task).await {
20162                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
20163                    outcome => failures.push(format!(
20164                        "query {} codec returned {outcome:?}",
20165                        codec_case.label()
20166                    )),
20167                },
20168                Err(error) => failures.push(format!(
20169                    "query {} codec failed transport deserialization: {error}",
20170                    codec_case.label()
20171                )),
20172            }
20173        }
20174
20175        assert!(failures.is_empty(), "{}", failures.join("\n"));
20176        assert_eq!(
20177            handler_calls.load(Ordering::SeqCst),
20178            0,
20179            "invalid task codecs must not invoke a handler"
20180        );
20181    }
20182
20183    #[tokio::test]
20184    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
20185        for codec_case in [
20186            InvalidTaskPayloadCodec::Missing,
20187            InvalidTaskPayloadCodec::Null,
20188            InvalidTaskPayloadCodec::NonString,
20189        ] {
20190            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
20191            let client = Client::builder(server.base_url())
20192                .timeout(Duration::from_secs(2))
20193                .build()
20194                .expect("client");
20195            let mut worker = Worker::new(client, "rust-workers")
20196                .worker_id("codec-worker")
20197                .poll_timeout(Duration::from_millis(10));
20198            let handler_calls = Arc::new(AtomicUsize::new(0));
20199
20200            let calls = Arc::clone(&handler_calls);
20201            worker.register_workflow("codec.workflow", move |_ctx, _args| {
20202                calls.fetch_add(1, Ordering::SeqCst);
20203                async move { Ok(Value::Null) }
20204            });
20205            let calls = Arc::clone(&handler_calls);
20206            worker.register_activity("codec.activity", move |_ctx, _args| {
20207                calls.fetch_add(1, Ordering::SeqCst);
20208                async move { Ok(Value::Null) }
20209            });
20210            let calls = Arc::clone(&handler_calls);
20211            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20212                calls.fetch_add(1, Ordering::SeqCst);
20213                async move { Ok(Value::Null) }
20214            });
20215
20216            assert_eq!(
20217                worker.run_once().await.expect("invalid tasks are settled"),
20218                3,
20219                "all {} codec tasks must be handled",
20220                codec_case.label()
20221            );
20222            assert_eq!(
20223                handler_calls.load(Ordering::SeqCst),
20224                0,
20225                "{} task codecs must fail before every handler",
20226                codec_case.label()
20227            );
20228
20229            for path in [
20230                "/api/worker/workflow-tasks/codec-workflow/fail",
20231                "/api/worker/activity-tasks/codec-activity/fail",
20232                "/api/worker/query-tasks/codec-query/fail",
20233            ] {
20234                let body = server.request_body(path);
20235                assert!(
20236                    body["failure"]["message"]
20237                        .as_str()
20238                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
20239                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
20240                    codec_case.label()
20241                );
20242            }
20243            assert_eq!(
20244                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
20245                    ["reason"],
20246                "query_payload_decode_failed"
20247            );
20248            for path in [
20249                "/api/worker/workflow-tasks/codec-workflow/complete",
20250                "/api/worker/activity-tasks/codec-activity/complete",
20251                "/api/worker/query-tasks/codec-query/complete",
20252            ] {
20253                assert_eq!(
20254                    server.request_count(path),
20255                    0,
20256                    "invalid {} codec task reached {path}",
20257                    codec_case.label()
20258                );
20259            }
20260        }
20261    }
20262
20263    #[tokio::test]
20264    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
20265        let client = Client::new("http://127.0.0.1:8080").expect("client");
20266        let mut worker = Worker::new(client, "rust-workers");
20267        let handler_calls = Arc::new(AtomicUsize::new(0));
20268
20269        let calls = Arc::clone(&handler_calls);
20270        worker.register_workflow("codec.workflow", move |_ctx, _args| {
20271            calls.fetch_add(1, Ordering::SeqCst);
20272            async move { Ok(Value::Null) }
20273        });
20274        let calls = Arc::clone(&handler_calls);
20275        worker.register_activity("codec.activity", move |_ctx, _args| {
20276            calls.fetch_add(1, Ordering::SeqCst);
20277            async move { Ok(Value::Null) }
20278        });
20279        let calls = Arc::clone(&handler_calls);
20280        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
20281            calls.fetch_add(1, Ordering::SeqCst);
20282            async move { Ok(Value::Null) }
20283        });
20284        let calls = Arc::clone(&handler_calls);
20285        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20286            calls.fetch_add(1, Ordering::SeqCst);
20287            async move { Ok(Value::Null) }
20288        });
20289
20290        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20291        workflow.payload_codec = "json".to_string();
20292        workflow.arguments = None;
20293        let error = worker
20294            .execute_workflow_task(workflow)
20295            .expect_err("task codec must be checked before workflow invocation");
20296        assert!(error.to_string().contains("unsupported_payload_codec"));
20297
20298        let activity = ActivityTask {
20299            task_id: "activity-invalid-codec".to_string(),
20300            activity_attempt_id: None,
20301            attempt_id: None,
20302            activity_type: "codec.activity".to_string(),
20303            payload_codec: "unknown".to_string(),
20304            arguments: None,
20305            attempt_number: 1,
20306            lease_owner: None,
20307        };
20308        let error = worker
20309            .execute_activity_task(activity)
20310            .await
20311            .expect_err("task codec must be checked before activity invocation");
20312        assert!(error.to_string().contains("unsupported_payload_codec"));
20313
20314        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20315        update.workflow_update_id = Some("update-invalid-codec".to_string());
20316        update.update_name = Some("known".to_string());
20317        update.history_events.push(history_event(
20318            "UpdateAccepted",
20319            json!({
20320                "update_id": "update-invalid-codec",
20321                "update_name": "known",
20322                "arguments": {"codec": "json", "blob": null}
20323            }),
20324        ));
20325        let error = worker
20326            .execute_workflow_task(update)
20327            .expect_err("nested update codec must be checked before handler lookup");
20328        assert!(error.to_string().contains("unsupported_payload_codec"));
20329
20330        let query: QueryTask = serde_json::from_value(json!({
20331            "query_task_id": "query-invalid-codec",
20332            "workflow_type": "codec.workflow",
20333            "query_name": "known",
20334            "payload_codec": DEFAULT_CODEC,
20335            "workflow_arguments": null,
20336            "query_arguments": null,
20337            "history_export": {
20338                "payloads": {"codec": DEFAULT_CODEC},
20339                "signals": [{
20340                    "name": "empty",
20341                    "payload_codec": "json",
20342                    "arguments": null
20343                }]
20344            }
20345        }))
20346        .expect("query task");
20347        let failure = worker
20348            .execute_query_task(query)
20349            .await
20350            .expect_err("exported signal codec must be checked before query invocation");
20351        assert_eq!(failure.reason, "query_payload_decode_failed");
20352        assert!(failure.message.contains("unsupported_payload_codec"));
20353
20354        let exported_history: QueryTask = serde_json::from_value(json!({
20355            "query_task_id": "query-invalid-history-codec",
20356            "workflow_type": "codec.workflow",
20357            "query_name": "known",
20358            "payload_codec": DEFAULT_CODEC,
20359            "history_export": {
20360                "payloads": {"codec": DEFAULT_CODEC},
20361                "history_events": [{
20362                    "type": "ActivityCompleted",
20363                    "payload": {"payload_codec": "unknown", "result": null}
20364                }]
20365            }
20366        }))
20367        .expect("query task");
20368        let failure = worker
20369            .execute_query_task(exported_history)
20370            .await
20371            .expect_err("exported history codec must be checked before query invocation");
20372        assert_eq!(failure.reason, "query_payload_decode_failed");
20373        assert!(failure.message.contains("unsupported_payload_codec"));
20374        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
20375
20376        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
20377        unknown_workflow.arguments = None;
20378        unknown_workflow.history_events.push(history_event(
20379            "SignalReceived",
20380            json!({
20381                "signal_name": "empty",
20382                "payload_codec": "json",
20383                "arguments": null
20384            }),
20385        ));
20386        let error = worker
20387            .execute_workflow_task(unknown_workflow)
20388            .expect_err("history codec must precede unknown workflow outcome");
20389        assert!(error.to_string().contains("unsupported_payload_codec"));
20390
20391        let unknown_activity = ActivityTask {
20392            task_id: "activity-unknown".to_string(),
20393            activity_attempt_id: None,
20394            attempt_id: None,
20395            activity_type: "missing".to_string(),
20396            payload_codec: "json".to_string(),
20397            arguments: None,
20398            attempt_number: 1,
20399            lease_owner: None,
20400        };
20401        let error = worker
20402            .execute_activity_task(unknown_activity)
20403            .await
20404            .expect_err("codec must precede unknown activity outcome");
20405        assert!(error.to_string().contains("unsupported_payload_codec"));
20406
20407        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20408        unknown_update.payload_codec = "json".to_string();
20409        unknown_update.arguments = None;
20410        unknown_update.workflow_update_id = Some("update-unknown".to_string());
20411        unknown_update.update_name = Some("missing".to_string());
20412        let error = worker
20413            .execute_workflow_task(unknown_update)
20414            .expect_err("codec must precede fail_update shortcut");
20415        assert!(error.to_string().contains("unsupported_payload_codec"));
20416
20417        let unknown_query: QueryTask = serde_json::from_value(json!({
20418            "query_task_id": "query-unknown",
20419            "workflow_type": "missing",
20420            "query_name": "missing",
20421            "payload_codec": "json",
20422            "workflow_arguments": null,
20423            "query_arguments": null
20424        }))
20425        .expect("query task");
20426        let failure = worker
20427            .execute_query_task(unknown_query)
20428            .await
20429            .expect_err("codec must precede unknown query outcome");
20430        assert_eq!(failure.reason, "query_payload_decode_failed");
20431        assert!(failure.message.contains("unsupported_payload_codec"));
20432    }
20433
20434    #[tokio::test]
20435    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
20436        let client = Client::new("http://127.0.0.1:8080").expect("client");
20437        let worker = Worker::new(client, "rust-workers");
20438
20439        for event_type in ["SignalReceived", "SignalApplied"] {
20440            for (payload_field, codec) in [
20441                ("value", "json"),
20442                ("input", "unknown"),
20443                ("arguments", "json"),
20444            ] {
20445                let payload = json!({
20446                    "signal_name": "empty",
20447                    payload_field: {"codec": codec, "blob": null}
20448                });
20449                let workflow = workflow_task(
20450                    "missing",
20451                    vec![history_event(event_type, payload.clone())],
20452                    DEFAULT_CODEC,
20453                );
20454                let error = worker
20455                    .execute_workflow_task(workflow)
20456                    .expect_err("signal payload codec must precede unknown workflow outcome");
20457                assert!(
20458                    error.to_string().contains("unsupported_payload_codec"),
20459                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
20460                );
20461
20462                let query: QueryTask = serde_json::from_value(json!({
20463                    "query_task_id": format!("query-{event_type}-{payload_field}"),
20464                    "workflow_type": "missing",
20465                    "query_name": "missing",
20466                    "payload_codec": DEFAULT_CODEC,
20467                    "workflow_arguments": null,
20468                    "query_arguments": null,
20469                    "history_events": [{
20470                        "event_type": event_type,
20471                        "payload": payload
20472                    }]
20473                }))
20474                .expect("query task");
20475                let failure = worker
20476                    .execute_query_task(query)
20477                    .await
20478                    .expect_err("signal payload codec must precede unknown query outcome");
20479                assert_eq!(
20480                    failure.reason, "query_payload_decode_failed",
20481                    "{event_type}.{payload_field} returned an unrelated query outcome"
20482                );
20483                assert!(
20484                    failure.message.contains("unsupported_payload_codec"),
20485                    "{event_type}.{payload_field} returned an unrelated query error: {}",
20486                    failure.message
20487                );
20488            }
20489        }
20490    }
20491
20492    #[test]
20493    fn workflow_context_schedules_activity_until_completion_is_in_history() {
20494        let ctx = WorkflowContext {
20495            cancellation_scope_id: "root".into(),
20496            state: Arc::new(Mutex::new(
20497                WorkflowState::new_with_identity(
20498                    Vec::new(),
20499                    Some("wf-parent".to_string()),
20500                    Some("run-parent".to_string()),
20501                    "rust-workers".to_string(),
20502                    DEFAULT_CODEC.to_string(),
20503                    None,
20504                )
20505                .expect("workflow state"),
20506            )),
20507        };
20508
20509        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
20510        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20511        assert!(matches!(
20512            call.as_mut().poll(&mut task_context),
20513            Poll::Pending
20514        ));
20515
20516        let commands = ctx.take_commands().expect("commands");
20517        assert_eq!(commands[0]["type"], "schedule_activity");
20518        assert_eq!(commands[0]["activity_type"], "hello.activity");
20519    }
20520
20521    #[test]
20522    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
20523        let ctx = workflow_context(Vec::new());
20524        let options = ActivityOptions::new()
20525            .task_queue("payments")
20526            .retry_policy(
20527                ActivityRetryPolicy::new(4)
20528                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
20529                    .non_retryable_error_type("ValidationError"),
20530            )
20531            .start_to_close_timeout(Duration::from_secs(120))
20532            .schedule_to_start_timeout(Duration::from_secs(10))
20533            .schedule_to_close_timeout(Duration::from_secs(300))
20534            .heartbeat_timeout(Duration::from_secs(15));
20535        let mut call = Box::pin(ctx.activity_with_options(
20536            "charge-card",
20537            options,
20538            json!([{"order_id": "o-1"}]),
20539        ));
20540        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20541
20542        assert!(matches!(
20543            call.as_mut().poll(&mut task_context),
20544            Poll::Pending
20545        ));
20546        assert!(matches!(
20547            call.as_mut().poll(&mut task_context),
20548            Poll::Pending
20549        ));
20550
20551        let commands = ctx.take_commands().expect("activity command");
20552        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
20553        assert_eq!(commands[0]["queue"], "payments");
20554        assert_eq!(
20555            commands[0]["retry_policy"],
20556            json!({
20557                "max_attempts": 4,
20558                "backoff_seconds": [1, 3, 9],
20559                "non_retryable_error_types": ["ValidationError"],
20560            })
20561        );
20562        assert_eq!(commands[0]["start_to_close_timeout"], 120);
20563        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
20564        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
20565        assert_eq!(commands[0]["heartbeat_timeout"], 15);
20566    }
20567
20568    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
20569        vec![
20570            history_event(
20571                "ActivityScheduled",
20572                json!({"sequence":1,"activity_type":"render",
20573                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
20574            ),
20575            history_event(
20576                "ActivityCompleted",
20577                json!({"sequence":1,"activity_type":"render",
20578                "payload_codec":DEFAULT_CODEC,
20579                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
20580            ),
20581        ]
20582    }
20583
20584    #[test]
20585    fn worker_session_activity_routes_to_session_queue_once() {
20586        let ctx = workflow_context(Vec::new());
20587        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20588        let mut call = Box::pin(
20589            ctx.activity("render", json!([]))
20590                .in_worker_session(session.clone()),
20591        );
20592        let mut cx = TaskContext::from_waker(noop_waker_ref());
20593        assert!(call.as_mut().poll(&mut cx).is_pending());
20594        assert!(call.as_mut().poll(&mut cx).is_pending());
20595        let commands = ctx.take_commands().unwrap();
20596        assert_eq!(commands.len(), 1);
20597        assert_eq!(commands[0]["queue"], "gpu-workers");
20598        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
20599    }
20600
20601    #[tokio::test]
20602    async fn worker_session_cold_replay_uses_recorded_avro_result() {
20603        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20604        for _replacement in 0..2 {
20605            let ctx = workflow_context(completed_worker_session_history(&session));
20606            let result: i64 = ctx
20607                .activity("render", json!([]))
20608                .in_worker_session(session.clone())
20609                .typed()
20610                .await
20611                .unwrap();
20612            assert_eq!(result, 42);
20613            assert!(ctx.take_commands().unwrap().is_empty());
20614        }
20615    }
20616
20617    #[test]
20618    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
20619        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20620        for changed in [
20621            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
20622            Some(original.clone().ttl_seconds(60)),
20623            Some(original.clone().requirements(["gpu:l4"])),
20624            None,
20625        ] {
20626            let ctx = workflow_context(completed_worker_session_history(&original));
20627            let mut call = ctx.activity_with_options(
20628                "render",
20629                ActivityOptions::new().task_queue("gpu-workers"),
20630                json!([]),
20631            );
20632            if let Some(changed) = changed {
20633                call = call.in_worker_session(changed);
20634            }
20635            let mut call = Box::pin(call);
20636            let mut cx = TaskContext::from_waker(noop_waker_ref());
20637            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20638                call.as_mut().poll(&mut cx)
20639            else {
20640                panic!("changed session must fail replay");
20641            };
20642            assert_eq!(failure.reason, "activity_worker_session_mismatch");
20643            assert!(ctx.take_commands().unwrap().is_empty());
20644        }
20645    }
20646
20647    #[test]
20648    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
20649        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
20650        let ctx = workflow_context(Vec::new());
20651        let mut local = Box::pin(
20652            ctx.local_activity("render", json!([]))
20653                .in_worker_session(session.clone()),
20654        );
20655        let mut cx = TaskContext::from_waker(noop_waker_ref());
20656        assert!(matches!(
20657            local.as_mut().poll(&mut cx),
20658            Poll::Ready(Err(Error::WorkerLoop(_)))
20659        ));
20660        assert!(ctx.take_commands().unwrap().is_empty());
20661        let mut remote = Box::pin(
20662            ctx.activity_with_options(
20663                "render",
20664                ActivityOptions::new().task_queue("other"),
20665                json!([]),
20666            )
20667            .in_worker_session(session),
20668        );
20669        assert!(matches!(
20670            remote.as_mut().poll(&mut cx),
20671            Poll::Ready(Err(Error::WorkerLoop(_)))
20672        ));
20673        assert!(ctx.take_commands().unwrap().is_empty());
20674    }
20675
20676    #[test]
20677    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
20678        let ctx = workflow_context(Vec::new());
20679        let options = ActivityOptions::new().retry_policy(
20680            ActivityRetryPolicy::new(3)
20681                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
20682        );
20683        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
20684        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20685
20686        assert!(matches!(
20687            call.as_mut().poll(&mut task_context),
20688            Poll::Pending
20689        ));
20690        assert_eq!(
20691            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
20692            json!([1, 2])
20693        );
20694    }
20695
20696    #[test]
20697    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
20698        let cases = [
20699            (
20700                ActivityOptions::new().task_queue("  "),
20701                ActivityOptionsErrorKind::EmptyTaskQueue,
20702            ),
20703            (
20704                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
20705                ActivityOptionsErrorKind::EmptyRetryPolicy,
20706            ),
20707            (
20708                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
20709                ActivityOptionsErrorKind::InvalidMaxAttempts,
20710            ),
20711            (
20712                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
20713                    max_attempts: None,
20714                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
20715                    non_retryable_error_types: Vec::new(),
20716                }),
20717                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
20718            ),
20719            (
20720                ActivityOptions::new().retry_policy(
20721                    ActivityRetryPolicy::new(2)
20722                        .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
20723                ),
20724                ActivityOptionsErrorKind::TooManyBackoffIntervals,
20725            ),
20726            (
20727                ActivityOptions::new().retry_policy(
20728                    ActivityRetryPolicy::new(2).exponential_backoff(
20729                        Duration::from_secs(1),
20730                        0,
20731                        None,
20732                    ),
20733                ),
20734                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
20735            ),
20736            (
20737                ActivityOptions::new()
20738                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
20739                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
20740            ),
20741            (
20742                ActivityOptions::new().retry_policy(
20743                    ActivityRetryPolicy::new(10_002).exponential_backoff(
20744                        Duration::from_secs(1),
20745                        1,
20746                        None,
20747                    ),
20748                ),
20749                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
20750            ),
20751            (
20752                ActivityOptions::new().retry_policy(
20753                    ActivityRetryPolicy::new(2)
20754                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
20755                ),
20756                ActivityOptionsErrorKind::BackoffOverflow,
20757            ),
20758        ];
20759
20760        for (options, expected_kind) in cases {
20761            let ctx = workflow_context(Vec::new());
20762            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
20763            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20764            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
20765                call.as_mut().poll(&mut task_context)
20766            else {
20767                panic!("expected typed activity validation error");
20768            };
20769            assert_eq!(error.kind, expected_kind);
20770            assert!(ctx.take_commands().expect("commands").is_empty());
20771        }
20772    }
20773
20774    #[test]
20775    fn activity_options_validate_positive_and_ordered_timeouts() {
20776        let zero_timeout_cases = [
20777            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
20778            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
20779            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
20780            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
20781        ];
20782        for options in zero_timeout_cases {
20783            assert_eq!(
20784                options.validate().expect_err("zero timeout").kind,
20785                ActivityOptionsErrorKind::TimeoutNotPositive
20786            );
20787        }
20788
20789        let ordering_cases = [
20790            ActivityOptions::new()
20791                .heartbeat_timeout(Duration::from_secs(11))
20792                .start_to_close_timeout(Duration::from_secs(10)),
20793            ActivityOptions::new()
20794                .start_to_close_timeout(Duration::from_secs(31))
20795                .schedule_to_close_timeout(Duration::from_secs(30)),
20796            ActivityOptions::new()
20797                .schedule_to_start_timeout(Duration::from_secs(31))
20798                .schedule_to_close_timeout(Duration::from_secs(30)),
20799        ];
20800        for options in ordering_cases {
20801            assert_eq!(
20802                options.validate().expect_err("timeout order").kind,
20803                ActivityOptionsErrorKind::TimeoutOrder
20804            );
20805        }
20806
20807        assert_eq!(
20808            ActivityOptions::new()
20809                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
20810                .validate()
20811                .expect_err("protocol integer overflow")
20812                .kind,
20813            ActivityOptionsErrorKind::TimeoutOverflow
20814        );
20815    }
20816
20817    #[test]
20818    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
20819        let ctx = workflow_context(completed_retry_activity_history());
20820        let mut call =
20821            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20822        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20823
20824        assert!(matches!(
20825            call.as_mut().poll(&mut task_context),
20826            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20827        ));
20828        assert!(ctx.take_commands().expect("commands").is_empty());
20829        ctx.ensure_history_consumed().expect("history consumed");
20830    }
20831
20832    #[test]
20833    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
20834        let mut options = retry_activity_options();
20835        options
20836            .retry_policy
20837            .as_mut()
20838            .expect("retry policy")
20839            .non_retryable_error_types
20840            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
20841
20842        let new_ctx = workflow_context(Vec::new());
20843        let mut new_call =
20844            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
20845        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20846        assert!(matches!(
20847            new_call.as_mut().poll(&mut task_context),
20848            Poll::Pending
20849        ));
20850        let commands = new_ctx.take_commands().expect("commands");
20851        assert_eq!(commands.len(), 1);
20852        assert_eq!(
20853            commands[0]["retry_policy"]["non_retryable_error_types"],
20854            json!(["PermanentError"])
20855        );
20856
20857        let replay_ctx = workflow_context(completed_retry_activity_history());
20858        let mut replay_call =
20859            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
20860        assert!(matches!(
20861            replay_call.as_mut().poll(&mut task_context),
20862            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
20863        ));
20864        assert!(replay_ctx.take_commands().expect("commands").is_empty());
20865        replay_ctx
20866            .ensure_history_consumed()
20867            .expect("history consumed");
20868    }
20869
20870    #[test]
20871    fn replayed_intermediate_retry_remains_pending_across_restarts() {
20872        let history = completed_retry_activity_history()
20873            .into_iter()
20874            .take(3)
20875            .collect::<Vec<_>>();
20876
20877        for _restart in 0..2 {
20878            let ctx = workflow_context(history.clone());
20879            let mut call =
20880                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
20881            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20882            assert!(matches!(
20883                call.as_mut().poll(&mut task_context),
20884                Poll::Pending
20885            ));
20886            assert!(ctx.take_commands().expect("commands").is_empty());
20887        }
20888    }
20889
20890    #[test]
20891    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
20892        let mut changed_queue = retry_activity_options();
20893        changed_queue.task_queue = Some("different-queue".to_string());
20894
20895        let mut changed_max_attempts = retry_activity_options();
20896        let retry_policy = changed_max_attempts
20897            .retry_policy
20898            .as_mut()
20899            .expect("retry policy");
20900        retry_policy.max_attempts = Some(4);
20901
20902        let mut changed_backoff = retry_activity_options();
20903        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
20904        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
20905            Duration::from_secs(3),
20906            Duration::from_secs(4),
20907        ]));
20908
20909        let mut changed_non_retryable_types = retry_activity_options();
20910        let retry_policy = changed_non_retryable_types
20911            .retry_policy
20912            .as_mut()
20913            .expect("retry policy");
20914        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
20915
20916        let mut changed_start_to_close = retry_activity_options();
20917        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
20918        let mut changed_schedule_to_start = retry_activity_options();
20919        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
20920        let mut changed_schedule_to_close = retry_activity_options();
20921        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
20922        let mut changed_heartbeat = retry_activity_options();
20923        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
20924
20925        let cases = [
20926            (changed_queue, "activity_task_queue_mismatch"),
20927            (changed_max_attempts, "activity_retry_policy_mismatch"),
20928            (changed_backoff, "activity_retry_policy_mismatch"),
20929            (
20930                changed_non_retryable_types,
20931                "activity_retry_policy_mismatch",
20932            ),
20933            (changed_start_to_close, "activity_retry_policy_mismatch"),
20934            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
20935            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
20936            (changed_heartbeat, "activity_retry_policy_mismatch"),
20937        ];
20938
20939        for (options, expected_reason) in cases {
20940            let ctx = workflow_context(completed_retry_activity_history());
20941            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
20942            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20943            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
20944                call.as_mut().poll(&mut task_context)
20945            else {
20946                panic!("changed activity options must fail replay");
20947            };
20948            assert_eq!(failure.reason, expected_reason);
20949            assert_eq!(failure.sequence, Some(1));
20950            assert!(ctx.take_commands().expect("commands").is_empty());
20951        }
20952    }
20953
20954    #[test]
20955    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
20956        let cases = [
20957            (
20958                "execution_mode",
20959                json!("local"),
20960                "activity_execution_mode_mismatch",
20961            ),
20962            (
20963                "snapshot_version",
20964                json!(2),
20965                "activity_retry_policy_mismatch",
20966            ),
20967        ];
20968
20969        for (field, value, expected_reason) in cases {
20970            let mut history = completed_retry_activity_history();
20971            let activity = history[0].payload["activity"]
20972                .as_object_mut()
20973                .expect("activity snapshot");
20974            if field == "execution_mode" {
20975                activity.insert(field.to_string(), value);
20976            } else {
20977                activity["retry_policy"]
20978                    .as_object_mut()
20979                    .expect("retry snapshot")
20980                    .insert(field.to_string(), value);
20981            }
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!("changed {field} must fail replay");
20991            };
20992            assert_eq!(failure.reason, expected_reason);
20993            assert_eq!(failure.sequence, Some(1));
20994            assert!(ctx.take_commands().expect("commands").is_empty());
20995        }
20996    }
20997
20998    #[test]
20999    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
21000        for (nested, field, value, terminal_only) in [
21001            (false, "execution_mode", json!("local"), false),
21002            (false, "local_activity", json!(true), false),
21003            (true, "local_activity", json!(true), false),
21004            (false, "local_activity", json!(true), true),
21005        ] {
21006            let mut history = completed_retry_activity_history();
21007            history[0]
21008                .payload
21009                .as_object_mut()
21010                .unwrap()
21011                .remove("activity");
21012            let event = if terminal_only {
21013                history.last_mut().unwrap()
21014            } else {
21015                &mut history[0]
21016            };
21017            if nested {
21018                event.payload["activity"] = json!({(field): value});
21019            } else {
21020                event.payload[field] = value;
21021            }
21022            let ctx = workflow_context(history);
21023            let mut call =
21024                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21025            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21026            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21027                call.as_mut().poll(&mut task_context)
21028            else {
21029                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
21030            };
21031            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
21032            assert_eq!(failure.sequence, Some(1));
21033            assert!(ctx.take_commands().expect("commands").is_empty());
21034        }
21035    }
21036
21037    #[test]
21038    fn activity_history_rejects_conflicting_local_execution_markers() {
21039        let mut history = completed_retry_activity_history();
21040        history.last_mut().unwrap().payload["local_activity"] = json!(true);
21041        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
21042            .expect_err("remote schedule cannot become a local completion");
21043        assert!(
21044            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
21045            if reason == "activity_execution_mode_conflict")
21046        );
21047    }
21048
21049    #[test]
21050    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
21051        let mut history = completed_retry_activity_history();
21052        let activity = history[0].payload["activity"]
21053            .as_object_mut()
21054            .expect("activity snapshot");
21055        activity.remove("execution_mode");
21056        activity.remove("retry_policy");
21057
21058        let mut current = retry_activity_options();
21059        current.start_to_close_timeout = Some(Duration::from_secs(45));
21060        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
21061        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
21062        current.heartbeat_timeout = Some(Duration::from_secs(12));
21063
21064        let ctx = workflow_context(history);
21065        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
21066        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21067        assert!(matches!(
21068            call.as_mut().poll(&mut task_context),
21069            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21070        ));
21071        assert!(ctx.take_commands().expect("commands").is_empty());
21072        ctx.ensure_history_consumed().expect("history consumed");
21073    }
21074
21075    #[test]
21076    fn terminal_activity_failed_after_start_returns_typed_failure() {
21077        let history = vec![
21078            history_event(
21079                "ActivityScheduled",
21080                json!({
21081                    "sequence": 1,
21082                    "activity_type": "flaky",
21083                    "activity_execution_id": "act-terminal",
21084                    "activity": {
21085                        "id": "act-terminal",
21086                        "sequence": 1,
21087                        "type": "flaky",
21088                        "queue": "critical-activities",
21089                        "retry_policy": {
21090                            "snapshot_version": 1,
21091                            "max_attempts": 3,
21092                            "backoff_seconds": [2, 4],
21093                            "non_retryable_error_types": ["PermanentError"]
21094                        }
21095                    }
21096                }),
21097            ),
21098            history_event(
21099                "ActivityStarted",
21100                json!({
21101                    "sequence": 1,
21102                    "activity_type": "flaky",
21103                    "activity_execution_id": "act-terminal",
21104                    "activity_attempt_id": "attempt-1",
21105                    "attempt_number": 1
21106                }),
21107            ),
21108            history_event(
21109                "ActivityFailed",
21110                json!({
21111                    "sequence": 1,
21112                    "activity_type": "flaky",
21113                    "activity_execution_id": "act-terminal",
21114                    "activity_attempt_id": "attempt-1",
21115                    "attempt_number": 1,
21116                    "failure_id": "failure-terminal",
21117                    "failure_category": "activity",
21118                    "exception_type": "PermanentError",
21119                    "message": "cannot retry",
21120                    "non_retryable": true
21121                }),
21122            ),
21123        ];
21124        let ctx = workflow_context(history);
21125        let mut call =
21126            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21127        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21128
21129        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21130            call.as_mut().poll(&mut task_context)
21131        else {
21132            panic!("terminal ActivityFailed must settle the activity future");
21133        };
21134        assert_eq!(failure.kind, ActivityFailureKind::Failed);
21135        assert_eq!(
21136            failure.activity_execution_id.as_deref(),
21137            Some("act-terminal")
21138        );
21139        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
21140        assert!(failure.non_retryable);
21141        assert!(ctx.take_commands().expect("commands").is_empty());
21142        ctx.ensure_history_consumed().expect("history consumed");
21143    }
21144
21145    #[test]
21146    fn activity_terminal_events_return_machine_readable_failures() {
21147        let cases = [
21148            (
21149                "ActivityFailed",
21150                json!({
21151                    "sequence": 1,
21152                    "activity_type": "charge-card",
21153                    "activity_execution_id": "act-1",
21154                    "activity_attempt_id": "attempt-2",
21155                    "attempt_number": 2,
21156                    "failure_id": "failure-1",
21157                    "failure_category": "activity",
21158                    "exception_type": "PaymentDeclined",
21159                    "exception_class": "payments.PaymentDeclined",
21160                    "message": "card declined",
21161                    "non_retryable": true
21162                }),
21163                ActivityFailureKind::Failed,
21164                "activity",
21165            ),
21166            (
21167                "ActivityCancelled",
21168                json!({
21169                    "sequence": 1,
21170                    "activity_type": "charge-card",
21171                    "activity_execution_id": "act-1",
21172                    "activity_attempt_id": "attempt-1"
21173                }),
21174                ActivityFailureKind::Cancelled,
21175                "cancelled",
21176            ),
21177        ];
21178
21179        for (event_type, payload, expected_kind, expected_reason) in cases {
21180            let ctx = workflow_context(vec![history_event(event_type, payload)]);
21181            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
21182            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21183            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21184                call.as_mut().poll(&mut task_context)
21185            else {
21186                panic!("expected terminal activity failure");
21187            };
21188            assert_eq!(failure.kind, expected_kind);
21189            assert_eq!(failure.reason, expected_reason);
21190            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
21191            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
21192        }
21193    }
21194
21195    #[test]
21196    fn every_activity_timeout_class_is_typed() {
21197        for timeout_kind in [
21198            "start_to_close",
21199            "schedule_to_start",
21200            "schedule_to_close",
21201            "heartbeat",
21202        ] {
21203            let ctx = workflow_context(vec![history_event(
21204                "ActivityTimedOut",
21205                json!({
21206                    "sequence": 1,
21207                    "activity_type": "slow",
21208                    "activity_execution_id": "act-timeout",
21209                    "activity_attempt_id": "attempt-timeout",
21210                    "failure_category": "timeout",
21211                    "timeout_kind": timeout_kind,
21212                    "message": "deadline expired"
21213                }),
21214            )]);
21215            let mut call = Box::pin(ctx.activity("slow", json!([])));
21216            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21217            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21218                call.as_mut().poll(&mut task_context)
21219            else {
21220                panic!("expected timeout failure");
21221            };
21222            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
21223            assert_eq!(failure.reason, timeout_kind);
21224            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
21225            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
21226        }
21227    }
21228
21229    #[test]
21230    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
21231        let ctx = workflow_context(Vec::new());
21232        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
21233        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21234
21235        assert!(matches!(
21236            sleep.as_mut().poll(&mut task_context),
21237            Poll::Pending
21238        ));
21239        assert!(matches!(
21240            sleep.as_mut().poll(&mut task_context),
21241            Poll::Pending
21242        ));
21243
21244        let commands = ctx.take_commands().expect("timer command");
21245        assert_eq!(
21246            commands,
21247            vec![json!({
21248                "type": "start_timer",
21249                "delay_seconds": 2,
21250            })]
21251        );
21252    }
21253
21254    #[test]
21255    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
21256        let history = vec![
21257            history_event(
21258                "TimerScheduled",
21259                json!({
21260                    "sequence": 1,
21261                    "timer_id": "timer-1",
21262                    "delay_seconds": 5,
21263                    "fire_at": "2026-07-11T12:00:05Z",
21264                }),
21265            ),
21266            history_event(
21267                "TimerFired",
21268                json!({
21269                    "sequence": 1,
21270                    "timer_id": "timer-1",
21271                    "delay_seconds": 5,
21272                    "fire_at": "2026-07-11T12:00:05Z",
21273                    "fired_at": "2026-07-11T12:00:05Z",
21274                }),
21275            ),
21276        ];
21277
21278        for _restart in 0..2 {
21279            let ctx = workflow_context(history.clone());
21280            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
21281            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21282            assert!(matches!(
21283                sleep.as_mut().poll(&mut task_context),
21284                Poll::Ready(Ok(()))
21285            ));
21286            assert!(ctx.take_commands().expect("commands").is_empty());
21287            ctx.ensure_history_consumed().expect("history consumed");
21288        }
21289    }
21290
21291    #[test]
21292    fn workflow_sleep_rejects_changed_delay_during_replay() {
21293        let ctx = workflow_context(vec![
21294            history_event(
21295                "TimerScheduled",
21296                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21297            ),
21298            history_event(
21299                "TimerFired",
21300                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21301            ),
21302        ]);
21303        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
21304        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21305
21306        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21307            sleep.as_mut().poll(&mut task_context)
21308        else {
21309            panic!("changed timer delay must be rejected");
21310        };
21311        assert_eq!(failure.reason, "timer_delay_mismatch");
21312        assert_eq!(failure.sequence, Some(1));
21313    }
21314
21315    #[test]
21316    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
21317        let ctx = workflow_context(Vec::new());
21318        let mut wait = Box::pin(
21319            ctx.wait_condition(
21320                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
21321                    .timeout(Duration::from_millis(60_001)),
21322                || Ok(false),
21323            ),
21324        );
21325        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21326
21327        assert!(matches!(
21328            wait.as_mut().poll(&mut task_context),
21329            Poll::Pending
21330        ));
21331        assert!(matches!(
21332            wait.as_mut().poll(&mut task_context),
21333            Poll::Pending
21334        ));
21335        assert_eq!(
21336            ctx.take_commands().expect("condition command"),
21337            vec![json!({
21338                "type": "open_condition_wait",
21339                "condition_wait_occurrence_id": "rust:condition-wait:0",
21340                "condition_key": "approval.ready",
21341                "condition_definition_fingerprint": "sha256:approval-v1",
21342                "timeout_seconds": 61,
21343            })]
21344        );
21345    }
21346
21347    #[test]
21348    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
21349        let ctx = workflow_context(Vec::new());
21350        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
21351        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21352        assert!(matches!(
21353            satisfied.as_mut().poll(&mut task_context),
21354            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21355        ));
21356
21357        let mut timed_out = Box::pin(wait_condition!(
21358            ctx,
21359            "no-wait",
21360            timeout: Duration::ZERO,
21361            || Ok(false),
21362        ));
21363        assert!(matches!(
21364            timed_out.as_mut().poll(&mut task_context),
21365            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
21366        ));
21367        assert!(ctx.take_commands().expect("commands").is_empty());
21368    }
21369
21370    #[test]
21371    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
21372        let signal_history = vec![
21373            history_event(
21374                "ConditionWaitOpened",
21375                json!({
21376                    "sequence": 4,
21377                    "condition_wait_id": "condition:4",
21378                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21379                    "condition_key": "approval",
21380                    "condition_definition_fingerprint": "sha256:approval-v1",
21381                    "timeout_seconds": 30,
21382                }),
21383            ),
21384            history_event(
21385                "SignalReceived",
21386                json!({
21387                    "workflow_sequence": 4,
21388                    "signal_name": "approve",
21389                    "arguments": fixture_envelope(json!(["Ada"])),
21390                }),
21391            ),
21392        ];
21393        for _worker_before_or_after_restart in 0..2 {
21394            let ctx = workflow_context(signal_history.clone());
21395            let predicate_ctx = ctx.clone();
21396            let mut wait = Box::pin(
21397                ctx.wait_condition(
21398                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
21399                        .timeout(Duration::from_secs(30)),
21400                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
21401                ),
21402            );
21403            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21404            assert!(matches!(
21405                wait.as_mut().poll(&mut task_context),
21406                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21407            ));
21408            assert!(ctx.take_commands().expect("commands").is_empty());
21409            ctx.ensure_history_consumed().expect("condition consumed");
21410        }
21411
21412        let update_history = vec![
21413            history_event(
21414                "ConditionWaitOpened",
21415                json!({
21416                    "sequence": 7,
21417                    "condition_wait_id": "condition:7",
21418                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21419                    "condition_key": "update-approval",
21420                    "condition_definition_fingerprint": "sha256:update-approval-v1",
21421                }),
21422            ),
21423            history_event(
21424                "UpdateApplied",
21425                json!({
21426                    "sequence": 7,
21427                    "update_id": "update-1",
21428                    "update_name": "approve",
21429                    "arguments": fixture_envelope(json!([true])),
21430                }),
21431            ),
21432        ];
21433        let ctx = workflow_context(update_history);
21434        let predicate_ctx = ctx.clone();
21435        let mut wait = Box::pin(ctx.wait_condition(
21436            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
21437            move || {
21438                Ok(predicate_ctx
21439                    .updates("approve")?
21440                    .first()
21441                    .and_then(|arguments| arguments.first())
21442                    .and_then(Value::as_bool)
21443                    == Some(true))
21444            },
21445        ));
21446        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21447        assert!(matches!(
21448            wait.as_mut().poll(&mut task_context),
21449            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21450        ));
21451        assert!(ctx.take_commands().expect("commands").is_empty());
21452        ctx.ensure_history_consumed().expect("condition consumed");
21453    }
21454
21455    #[test]
21456    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
21457        let open_history = vec![
21458            history_event(
21459                "ConditionWaitOpened",
21460                json!({
21461                    "sequence": 3,
21462                    "condition_wait_id": "condition:3",
21463                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21464                    "condition_key": "two-votes",
21465                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21466                    "timeout_seconds": 120,
21467                }),
21468            ),
21469            history_event(
21470                "SignalReceived",
21471                json!({
21472                    "workflow_sequence": 3,
21473                    "signal_name": "vote",
21474                    "arguments": fixture_envelope(json!(["first"])),
21475                }),
21476            ),
21477        ];
21478        for _worker_before_or_after_restart in 0..2 {
21479            let ctx = workflow_context(open_history.clone());
21480            let predicate_ctx = ctx.clone();
21481            let mut wait = Box::pin(
21482                ctx.wait_condition(
21483                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21484                        .timeout(Duration::from_secs(120)),
21485                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
21486                ),
21487            );
21488            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21489            assert!(matches!(
21490                wait.as_mut().poll(&mut task_context),
21491                Poll::Pending
21492            ));
21493            assert_eq!(
21494                ctx.take_commands().expect("reopened condition"),
21495                vec![json!({
21496                    "type": "open_condition_wait",
21497                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21498                    "condition_key": "two-votes",
21499                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21500                    "timeout_seconds": 120,
21501                })]
21502            );
21503        }
21504
21505        let satisfied_ctx = workflow_context(vec![
21506            history_event(
21507                "ConditionWaitOpened",
21508                json!({
21509                    "sequence": 5,
21510                    "condition_wait_id": "condition:5",
21511                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21512                    "condition_key": "approval",
21513                    "condition_definition_fingerprint": "sha256:approval-v1",
21514                }),
21515            ),
21516            history_event(
21517                "ConditionWaitSatisfied",
21518                json!({
21519                    "sequence": 5,
21520                    "condition_wait_id": "condition:5",
21521                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21522                    "condition_key": "approval",
21523                    "condition_definition_fingerprint": "sha256:approval-v1",
21524                }),
21525            ),
21526        ]);
21527        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
21528            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
21529            || Ok(false),
21530        ));
21531        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21532        assert!(matches!(
21533            satisfied.as_mut().poll(&mut task_context),
21534            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21535        ));
21536
21537        let timed_out_ctx = workflow_context(vec![
21538            history_event(
21539                "ConditionWaitOpened",
21540                json!({
21541                    "sequence": 8,
21542                    "condition_wait_id": "condition:8",
21543                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21544                    "condition_key": "approval-timeout",
21545                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
21546                    "timeout_seconds": 5,
21547                }),
21548            ),
21549            history_event(
21550                "TimerScheduled",
21551                json!({
21552                    "sequence": 9,
21553                    "timer_id": "condition-timer:9",
21554                    "timer_kind": "condition_timeout",
21555                    "condition_wait_id": "condition:8",
21556                    "delay_seconds": 5,
21557                }),
21558            ),
21559            history_event(
21560                "TimerFired",
21561                json!({
21562                    "sequence": 9,
21563                    "timer_id": "condition-timer:9",
21564                    "timer_kind": "condition_timeout",
21565                    "condition_wait_id": "condition:8",
21566                    "delay_seconds": 5,
21567                }),
21568            ),
21569        ]);
21570        let mut timed_out = Box::pin(
21571            timed_out_ctx.wait_condition(
21572                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
21573                    .timeout(Duration::from_secs(5)),
21574                || Ok(true),
21575            ),
21576        );
21577        assert!(matches!(
21578            timed_out.as_mut().poll(&mut task_context),
21579            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
21580        ));
21581    }
21582
21583    #[test]
21584    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
21585        let ctx = workflow_context(reopened_selection_condition_history());
21586        {
21587            let state = ctx.state.lock().unwrap();
21588            assert!(matches!(
21589                selection_member_recorded_command(&state, 2),
21590                Some(RecordedCommand::ConditionWait {
21591                    sequence: 3,
21592                    result: None,
21593                    ..
21594                })
21595            ));
21596        }
21597        let mut selected = Box::pin(ctx.select_keyed(vec![
21598            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
21599            (
21600                "votes",
21601                ParallelOperation::condition(
21602                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
21603                    || Ok(true),
21604                ),
21605            ),
21606        ]));
21607        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21608        assert!(selected.as_mut().poll(&mut task_context).is_pending());
21609        assert!(
21610            ctx.take_commands().unwrap().is_empty(),
21611            "true predicate must not reopen the recorded wait"
21612        );
21613        ctx.ensure_history_consumed()
21614            .expect("physical reopens are consumed while canonical selection is pending");
21615    }
21616
21617    #[test]
21618    fn reopened_selection_condition_replays_its_latest_physical_winner() {
21619        for (terminal_type, acknowledge_timeout) in [
21620            ("ConditionWaitSatisfied", false),
21621            ("ConditionWaitTimedOut", false),
21622            ("TimerFired", false),
21623            ("TimerFired", true),
21624        ] {
21625            let mut history = reopened_selection_condition_history();
21626            let original_identity = history[1].payload["condition_wait_id"].clone();
21627            let uses_timer = terminal_type == "TimerFired";
21628            let mut resolution_payload = history[3].payload.clone();
21629            if uses_timer {
21630                for event in &mut history[1..] {
21631                    event.payload["timeout_seconds"] = json!(3);
21632                }
21633                resolution_payload = history[3].payload.clone();
21634                resolution_payload["timer_kind"] = json!("condition_timeout");
21635                resolution_payload["timer_id"] = json!("condition-timeout-3");
21636                resolution_payload["delay_seconds"] = json!(3);
21637                history.push(history_event("TimerScheduled", resolution_payload.clone()));
21638            }
21639            let mut resolution = history_event(terminal_type, resolution_payload.clone());
21640            resolution
21641                .raw
21642                .insert("id".into(), json!("latest-condition-resolution"));
21643            history.push(resolution);
21644            history.push(history_event(
21645                "SelectionResolved",
21646                json!({
21647                    "selection_group_id": "select-calls:1:2",
21648                    "selection_group_base_sequence": 1,
21649                    "selection_group_size": 2,
21650                    "member_key": "votes",
21651                    "member_index": 1,
21652                    "member_base_sequence": 2,
21653                    "member_size": 1,
21654                    "operation_kind": "condition",
21655                    "operation_identity": original_identity,
21656                    "outcome": "completed",
21657                    "resolution_event_id": "latest-condition-resolution",
21658                    "resolution_event_type": terminal_type,
21659                }),
21660            ));
21661            if acknowledge_timeout {
21662                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
21663            }
21664            let ctx = workflow_context(history);
21665            let mut selected = Box::pin(ctx.select_keyed(vec![
21666                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
21667                (
21668                    "votes",
21669                    ParallelOperation::condition(
21670                        if uses_timer {
21671                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21672                                .timeout(Duration::from_secs(3))
21673                        } else {
21674                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
21675                        },
21676                        || Ok(true),
21677                    ),
21678                ),
21679            ]));
21680            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21681            match selected.as_mut().poll(&mut task_context) {
21682                Poll::Ready(Ok(result)) => {
21683                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
21684                    let expected = if terminal_type == "ConditionWaitSatisfied" {
21685                        ConditionWaitResult::Satisfied
21686                    } else {
21687                        ConditionWaitResult::TimedOut
21688                    };
21689                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
21690                }
21691                other => panic!("latest physical winner must replay: {other:?}"),
21692            }
21693            assert!(ctx.take_commands().unwrap().is_empty());
21694            ctx.ensure_history_consumed()
21695                .expect("winner history consumed");
21696        }
21697    }
21698
21699    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
21700        let fixture: Value = serde_json::from_str(include_str!(
21701            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
21702        ))
21703        .expect("grouped condition fixture");
21704        fixture["history"]
21705            .as_array()
21706            .unwrap()
21707            .iter()
21708            .map(|event| {
21709                let mut payload = event["payload"].clone();
21710                let index = payload["parallel_group_index"].as_u64().unwrap();
21711                payload["parallel_group_id"] = json!("select-calls:1:2");
21712                payload["parallel_group_mode"] = json!("select");
21713                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
21714                payload["selection_member_index"] = json!(index);
21715                payload["selection_member_base_sequence"] = json!(index + 1);
21716                payload["selection_member_size"] = json!(1);
21717                payload["selection_member_kind"] =
21718                    json!(if index == 0 { "timer" } else { "condition" });
21719                history_event(event["event_type"].as_str().unwrap(), payload)
21720            })
21721            .collect()
21722    }
21723
21724    #[test]
21725    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
21726        let fixture: Value = serde_json::from_str(include_str!(
21727            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
21728        ))
21729        .expect("grouped condition fixture");
21730        let original = fixture["history"].as_array().expect("fixture history");
21731        let decode = |events: &[Value]| {
21732            let history = events
21733                .iter()
21734                .map(|event| {
21735                    history_event(
21736                        event["event_type"].as_str().unwrap(),
21737                        event["payload"].clone(),
21738                    )
21739                })
21740                .collect::<Vec<_>>();
21741            recorded_commands(
21742                &history,
21743                DEFAULT_CODEC,
21744                WorkflowIdentity {
21745                    workflow_id: None,
21746                    run_id: None,
21747                },
21748            )
21749        };
21750        assert!(decode(original).is_ok());
21751        for field in [
21752            "condition_wait_occurrence_id",
21753            "condition_key",
21754            "condition_definition_fingerprint",
21755            "timeout_seconds",
21756            "parallel_group_id",
21757            "parallel_group_size",
21758            "parallel_group_index",
21759        ] {
21760            let mut changed = original.clone();
21761            changed[3]["payload"][field] = match field {
21762                "timeout_seconds" | "parallel_group_size" => json!(30),
21763                "parallel_group_index" => json!(0),
21764                _ => json!("changed"),
21765            };
21766            assert!(
21767                decode(&changed).is_err(),
21768                "reopen must reject changed {field}"
21769            );
21770        }
21771        let mut unsettled = original.clone();
21772        unsettled.remove(2);
21773        assert!(
21774            decode(&unsettled).is_err(),
21775            "physical predecessor must be resolved"
21776        );
21777        let mut timed_out = original.clone();
21778        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
21779        assert!(decode(&timed_out).is_err(), "timeout is terminal");
21780        let mut late_resolution = original.clone();
21781        late_resolution.swap(2, 3);
21782        assert!(
21783            decode(&late_resolution).is_err(),
21784            "later history cannot authorize a reopen"
21785        );
21786    }
21787
21788    #[test]
21789    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
21790        let history = vec![
21791            history_event(
21792                "ConditionWaitOpened",
21793                json!({
21794                    "sequence": 3,
21795                    "condition_wait_id": "condition:3",
21796                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21797                    "condition_key": "two-votes",
21798                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21799                }),
21800            ),
21801            history_event(
21802                "SignalReceived",
21803                json!({
21804                    "workflow_sequence": 3,
21805                    "signal_name": "vote",
21806                    "arguments": fixture_envelope(json!(["first"])),
21807                }),
21808            ),
21809            history_event(
21810                "ConditionWaitSatisfied",
21811                json!({
21812                    "sequence": 3,
21813                    "condition_wait_id": "condition:3",
21814                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21815                    "condition_key": "two-votes",
21816                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21817                }),
21818            ),
21819            history_event(
21820                "ConditionWaitOpened",
21821                json!({
21822                    "sequence": 5,
21823                    "condition_wait_id": "condition:5",
21824                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21825                    "condition_key": "two-votes",
21826                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21827                }),
21828            ),
21829            history_event(
21830                "SignalReceived",
21831                json!({
21832                    "workflow_sequence": 5,
21833                    "signal_name": "vote",
21834                    "arguments": fixture_envelope(json!(["second"])),
21835                }),
21836            ),
21837            history_event(
21838                "ConditionWaitSatisfied",
21839                json!({
21840                    "sequence": 5,
21841                    "condition_wait_id": "condition:5",
21842                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21843                    "condition_key": "two-votes",
21844                    "condition_definition_fingerprint": "sha256:two-votes-v1",
21845                }),
21846            ),
21847        ];
21848        for _cold_worker_or_restart in 0..2 {
21849            let ctx = workflow_context(history.clone());
21850            let predicate_ctx = ctx.clone();
21851            let mut wait = Box::pin(ctx.wait_condition(
21852                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
21853                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
21854            ));
21855            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21856
21857            assert!(matches!(
21858                wait.as_mut().poll(&mut task_context),
21859                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21860            ));
21861            assert!(ctx.take_commands().expect("commands").is_empty());
21862            ctx.ensure_history_consumed()
21863                .expect("every physical wait-open is consumed");
21864        }
21865    }
21866
21867    #[test]
21868    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
21869        let history = vec![
21870            history_event(
21871                "ConditionWaitOpened",
21872                json!({
21873                    "sequence": 3,
21874                    "condition_wait_id": "condition:3",
21875                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21876                    "condition_key": "approved",
21877                    "condition_definition_fingerprint": "sha256:approved-v1",
21878                }),
21879            ),
21880            history_event(
21881                "UpdateApplied",
21882                json!({
21883                    "sequence": 3,
21884                    "update_id": "update-1",
21885                    "update_name": "approve",
21886                    "arguments": fixture_envelope(json!([false])),
21887                }),
21888            ),
21889            history_event(
21890                "ConditionWaitOpened",
21891                json!({
21892                    "sequence": 5,
21893                    "condition_wait_id": "condition:5",
21894                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21895                    "condition_key": "approved",
21896                    "condition_definition_fingerprint": "sha256:approved-v1",
21897                }),
21898            ),
21899            history_event(
21900                "UpdateApplied",
21901                json!({
21902                    "sequence": 5,
21903                    "update_id": "update-2",
21904                    "update_name": "approve",
21905                    "arguments": fixture_envelope(json!([true])),
21906                }),
21907            ),
21908        ];
21909
21910        for _cold_worker_or_restart in 0..2 {
21911            let ctx = workflow_context(history.clone());
21912            let predicate_ctx = ctx.clone();
21913            let mut wait = Box::pin(ctx.wait_condition(
21914                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
21915                move || {
21916                    Ok(predicate_ctx
21917                        .updates("approve")?
21918                        .last()
21919                        .and_then(|arguments| arguments.first())
21920                        .and_then(Value::as_bool)
21921                        == Some(true))
21922                },
21923            ));
21924            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21925
21926            assert!(matches!(
21927                wait.as_mut().poll(&mut task_context),
21928                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21929            ));
21930            assert!(ctx.take_commands().expect("commands").is_empty());
21931            ctx.ensure_history_consumed()
21932                .expect("every update-driven reopen is consumed");
21933        }
21934    }
21935
21936    #[test]
21937    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
21938        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
21939            ("shared", "sha256:first", "shared", "sha256:second"),
21940            ("first", "sha256:shared", "second", "sha256:shared"),
21941            ("shared", "sha256:shared", "shared", "sha256:shared"),
21942            ("first", "sha256:first", "second", "sha256:second"),
21943        ] {
21944            let history = vec![
21945                history_event(
21946                    "ConditionWaitOpened",
21947                    json!({
21948                        "sequence": 3,
21949                        "condition_wait_id": "condition:3",
21950                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21951                        "condition_key": first_key,
21952                        "condition_definition_fingerprint": first_fingerprint,
21953                    }),
21954                ),
21955                history_event(
21956                    "ConditionWaitSatisfied",
21957                    json!({
21958                        "sequence": 3,
21959                        "condition_wait_id": "condition:3",
21960                        "condition_wait_occurrence_id": "rust:condition-wait:0",
21961                        "condition_key": first_key,
21962                        "condition_definition_fingerprint": first_fingerprint,
21963                    }),
21964                ),
21965                history_event(
21966                    "ConditionWaitOpened",
21967                    json!({
21968                        "sequence": 4,
21969                        "condition_wait_id": "condition:4",
21970                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21971                        "condition_key": second_key,
21972                        "condition_definition_fingerprint": second_fingerprint,
21973                    }),
21974                ),
21975                history_event(
21976                    "ConditionWaitSatisfied",
21977                    json!({
21978                        "sequence": 4,
21979                        "condition_wait_id": "condition:4",
21980                        "condition_wait_occurrence_id": "rust:condition-wait:1",
21981                        "condition_key": second_key,
21982                        "condition_definition_fingerprint": second_fingerprint,
21983                    }),
21984                ),
21985            ];
21986            for _cold_worker_or_restart in 0..2 {
21987                let ctx = workflow_context(history.clone());
21988                let mut task_context = TaskContext::from_waker(noop_waker_ref());
21989                let mut first = Box::pin(ctx.wait_condition(
21990                    ConditionWaitOptions::new(first_key, first_fingerprint),
21991                    || Ok(false),
21992                ));
21993                assert!(matches!(
21994                    first.as_mut().poll(&mut task_context),
21995                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
21996                ));
21997
21998                let mut second = Box::pin(ctx.wait_condition(
21999                    ConditionWaitOptions::new(second_key, second_fingerprint),
22000                    || Ok(false),
22001                ));
22002                assert!(matches!(
22003                    second.as_mut().poll(&mut task_context),
22004                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22005                ));
22006                assert!(ctx.take_commands().expect("commands").is_empty());
22007                ctx.ensure_history_consumed()
22008                    .expect("each authored wait consumes one occurrence");
22009            }
22010        }
22011    }
22012
22013    #[test]
22014    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
22015        fn worker() -> Worker {
22016            let client = Client::new("http://127.0.0.1:8080").expect("client");
22017            let mut worker = Worker::new(client, "rust-workers");
22018            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
22019                let mut outcomes = Vec::new();
22020                for _ in 0..2 {
22021                    outcomes.push(
22022                        ctx.wait_condition(
22023                            ConditionWaitOptions::new("shared", "sha256:shared"),
22024                            || Ok(false),
22025                        )
22026                        .await?,
22027                    );
22028                }
22029                Ok(json!(outcomes))
22030            });
22031            worker
22032        }
22033
22034        let task = workflow_task(
22035            "rust.condition-loop",
22036            vec![
22037                history_event(
22038                    "ConditionWaitOpened",
22039                    json!({
22040                        "sequence": 1,
22041                        "condition_wait_id": "condition:1",
22042                        "condition_wait_occurrence_id": "rust:condition-wait:0",
22043                        "condition_key": "shared",
22044                        "condition_definition_fingerprint": "sha256:shared",
22045                    }),
22046                ),
22047                history_event(
22048                    "ConditionWaitSatisfied",
22049                    json!({
22050                        "sequence": 1,
22051                        "condition_wait_id": "condition:1",
22052                        "condition_wait_occurrence_id": "rust:condition-wait:0",
22053                        "condition_key": "shared",
22054                        "condition_definition_fingerprint": "sha256:shared",
22055                    }),
22056                ),
22057                history_event(
22058                    "ConditionWaitOpened",
22059                    json!({
22060                        "sequence": 2,
22061                        "condition_wait_id": "condition:2",
22062                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22063                        "condition_key": "shared",
22064                        "condition_definition_fingerprint": "sha256:shared",
22065                    }),
22066                ),
22067                history_event(
22068                    "ConditionWaitSatisfied",
22069                    json!({
22070                        "sequence": 2,
22071                        "condition_wait_id": "condition:2",
22072                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22073                        "condition_key": "shared",
22074                        "condition_definition_fingerprint": "sha256:shared",
22075                    }),
22076                ),
22077            ],
22078            DEFAULT_CODEC,
22079        );
22080
22081        for _cold_worker_or_restart in 0..2 {
22082            let commands = worker()
22083                .execute_workflow_task(task.clone())
22084                .expect("adjacent loop waits replay deterministically");
22085            assert_eq!(commands.len(), 1);
22086            assert_eq!(commands[0]["type"], "complete_workflow");
22087            assert_eq!(
22088                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
22089                json!(["satisfied", "satisfied"])
22090            );
22091        }
22092    }
22093
22094    #[test]
22095    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
22096        let history = vec![history_event(
22097            "ConditionWaitOpened",
22098            json!({
22099                "sequence": 12,
22100                "condition_wait_id": "condition:12",
22101                "condition_wait_occurrence_id": "rust:condition-wait:0",
22102                "condition_key": "approval",
22103                "condition_definition_fingerprint": "sha256:approval-v1",
22104                "timeout_seconds": 30,
22105            }),
22106        )];
22107        for (options, expected_reason) in [
22108            (
22109                ConditionWaitOptions::new("changed", "sha256:approval-v1")
22110                    .timeout(Duration::from_secs(30)),
22111                "condition_wait_key_mismatch",
22112            ),
22113            (
22114                ConditionWaitOptions::new("approval", "sha256:approval-v2")
22115                    .timeout(Duration::from_secs(30)),
22116                "condition_wait_predicate_mismatch",
22117            ),
22118            (
22119                ConditionWaitOptions::new("approval", "sha256:approval-v1")
22120                    .timeout(Duration::from_secs(29)),
22121                "condition_wait_timeout_mismatch",
22122            ),
22123        ] {
22124            let ctx = workflow_context(history.clone());
22125            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
22126            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22127            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22128                wait.as_mut().poll(&mut task_context)
22129            else {
22130                panic!("changed condition definition must fail replay");
22131            };
22132            assert_eq!(failure.reason, expected_reason);
22133            assert_eq!(failure.sequence, Some(12));
22134        }
22135    }
22136
22137    #[test]
22138    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
22139        let error = WorkflowState::new(
22140            vec![history_event(
22141                "ConditionWaitOpened",
22142                json!({
22143                    "sequence": 12,
22144                    "condition_wait_id": "condition:12",
22145                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22146                    "condition_key": "approval",
22147                }),
22148            )],
22149            "rust-workers".to_string(),
22150            DEFAULT_CODEC.to_string(),
22151            None,
22152        )
22153        .expect_err("condition history without a predicate fingerprint must fail");
22154
22155        assert!(matches!(
22156            error,
22157            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22158                if reason == "condition_wait_predicate_fingerprint_missing"
22159        ));
22160    }
22161
22162    #[test]
22163    fn condition_wait_history_requires_authored_occurrence_identity() {
22164        let error = WorkflowState::new(
22165            vec![history_event(
22166                "ConditionWaitOpened",
22167                json!({
22168                    "sequence": 12,
22169                    "condition_wait_id": "condition:12",
22170                    "condition_key": "approval",
22171                    "condition_definition_fingerprint": "sha256:approval-v1",
22172                }),
22173            )],
22174            "rust-workers".to_string(),
22175            DEFAULT_CODEC.to_string(),
22176            None,
22177        )
22178        .expect_err("condition history without occurrence identity must fail");
22179
22180        assert!(matches!(
22181            error,
22182            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22183                if reason == "condition_wait_occurrence_id_missing"
22184        ));
22185    }
22186
22187    #[test]
22188    fn typed_search_attribute_updates_validate_emit_and_replay() {
22189        let update = SearchAttributeUpdate::new()
22190            .keyword("OrderStatus", " waiting ")
22191            .expect("keyword")
22192            .int("Attempt", 3)
22193            .expect("int")
22194            .bool("Escalated", false)
22195            .expect("bool")
22196            .keyword_list("Regions", ["us-east", "eu-west"])
22197            .expect("list")
22198            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
22199            .expect("datetime")
22200            .delete("LegacyStatus")
22201            .expect("delete");
22202        let ctx = workflow_context(Vec::new());
22203        ctx.upsert_search_attributes(update.clone())
22204            .expect("typed update");
22205        assert_eq!(
22206            ctx.take_commands().expect("search-attribute command"),
22207            vec![json!({
22208                "type": "upsert_search_attributes",
22209                "attributes": {
22210                    "Attempt": 3,
22211                    "Escalated": false,
22212                    "LegacyStatus": null,
22213                    "OrderStatus": "waiting",
22214                    "Regions": ["us-east", "eu-west"],
22215                    "UpdatedAt": "2026-08-22T04:00:00Z",
22216                },
22217                "attribute_types": {
22218                    "Attempt": "int",
22219                    "Escalated": "bool",
22220                    "OrderStatus": "keyword",
22221                    "Regions": "keyword_list",
22222                    "UpdatedAt": "datetime",
22223                },
22224            })]
22225        );
22226
22227        let replay = workflow_context(vec![history_event(
22228            "SearchAttributesUpserted",
22229            json!({
22230                "sequence": 6,
22231                "attributes": {
22232                    "Attempt": 3,
22233                    "Escalated": false,
22234                    "LegacyStatus": null,
22235                    "OrderStatus": "waiting",
22236                    "Regions": ["us-east", "eu-west"],
22237                    "UpdatedAt": "2026-08-22T04:00:00Z",
22238                },
22239                "attribute_types": {
22240                    "Attempt": "int",
22241                    "Escalated": "bool",
22242                    "OrderStatus": "keyword",
22243                    "Regions": "keyword_list",
22244                    "UpdatedAt": "datetime",
22245                },
22246                "merged": {},
22247            }),
22248        )]);
22249        replay
22250            .upsert_search_attributes(update)
22251            .expect("matching update replays");
22252        assert!(replay.take_commands().expect("commands").is_empty());
22253        replay.ensure_history_consumed().expect("history consumed");
22254
22255        let type_drift = workflow_context(vec![history_event(
22256            "SearchAttributesUpserted",
22257            json!({
22258                "sequence": 7,
22259                "attributes": {"OrderStatus": "waiting"},
22260                "attribute_types": {"OrderStatus": "keyword"},
22261                "merged": {"OrderStatus": "waiting"},
22262            }),
22263        )]);
22264        let error = type_drift
22265            .upsert_search_attributes(
22266                SearchAttributeUpdate::new()
22267                    .string("OrderStatus", "waiting")
22268                    .expect("string update"),
22269            )
22270            .expect_err("same JSON value with a changed type must fail replay");
22271        assert!(matches!(
22272            error,
22273            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22274                if reason == "search_attribute_type_mismatch"
22275        ));
22276
22277        let malformed_types = WorkflowState::new(
22278            vec![history_event(
22279                "SearchAttributesUpserted",
22280                json!({
22281                    "sequence": 8,
22282                    "attributes": {"OrderStatus": "waiting"},
22283                    "attribute_types": {"OrderStatus": "unsupported"},
22284                    "merged": {"OrderStatus": "waiting"},
22285                }),
22286            )],
22287            "rust-workers".to_string(),
22288            DEFAULT_CODEC.to_string(),
22289            None,
22290        )
22291        .expect_err("unsupported search-attribute type metadata must fail");
22292        assert!(matches!(
22293            malformed_types,
22294            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22295                if reason == "search_attribute_types_malformed"
22296        ));
22297
22298        assert!(matches!(
22299            SearchAttributeUpdate::new().keyword("bad key", "value"),
22300            Err(SearchAttributeUpdateError::InvalidKey(_))
22301        ));
22302        assert!(matches!(
22303            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
22304            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
22305        ));
22306        assert!(matches!(
22307            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
22308            Err(SearchAttributeUpdateError::ValueTooLong { .. })
22309        ));
22310        assert!(matches!(
22311            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
22312            Err(SearchAttributeUpdateError::InvalidDateTime(_))
22313        ));
22314        assert!(matches!(
22315            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
22316            Err(Error::InvalidSearchAttributeUpdate(
22317                SearchAttributeUpdateError::Empty
22318            ))
22319        ));
22320    }
22321
22322    #[test]
22323    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
22324        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
22325        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
22326
22327        assert!(SearchAttributeUpdate::new()
22328            .string("AsciiDescription", ascii)
22329            .is_ok());
22330        assert!(SearchAttributeUpdate::new()
22331            .string("Utf8Description", utf8)
22332            .is_ok());
22333        assert!(matches!(
22334            SearchAttributeUpdate::new().string(
22335                "TooLongDescription",
22336                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
22337            ),
22338            Err(SearchAttributeUpdateError::ValueTooLong {
22339                kind: "string",
22340                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
22341                ..
22342            })
22343        ));
22344    }
22345
22346    #[test]
22347    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
22348        let lone_fire = WorkflowState::new(
22349            vec![history_event(
22350                "TimerFired",
22351                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22352            )],
22353            "rust-workers".to_string(),
22354            DEFAULT_CODEC.to_string(),
22355            None,
22356        )
22357        .expect_err("TimerFired requires TimerScheduled");
22358        assert!(matches!(
22359            lone_fire,
22360            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22361                if reason == "timer_schedule_missing_or_duplicate"
22362        ));
22363
22364        let wrong_identity = WorkflowState::new(
22365            vec![
22366                history_event(
22367                    "TimerScheduled",
22368                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22369                ),
22370                history_event(
22371                    "TimerFired",
22372                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
22373                ),
22374            ],
22375            "rust-workers".to_string(),
22376            DEFAULT_CODEC.to_string(),
22377            None,
22378        )
22379        .expect_err("fire must match scheduled timer identity");
22380        assert!(matches!(
22381            wrong_identity,
22382            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22383                if reason == "timer_identity_mismatch"
22384        ));
22385
22386        let duplicate_fire = WorkflowState::new(
22387            vec![
22388                history_event(
22389                    "TimerScheduled",
22390                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22391                ),
22392                history_event(
22393                    "TimerFired",
22394                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22395                ),
22396                history_event(
22397                    "TimerFired",
22398                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22399                ),
22400            ],
22401            "rust-workers".to_string(),
22402            DEFAULT_CODEC.to_string(),
22403            None,
22404        )
22405        .expect_err("a durable timer cannot fire twice");
22406        assert!(matches!(
22407            duplicate_fire,
22408            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22409                if reason == "duplicate_timer_fire"
22410        ));
22411
22412        let wrong_fired_delay = WorkflowState::new(
22413            vec![
22414                history_event(
22415                    "TimerScheduled",
22416                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22417                ),
22418                history_event(
22419                    "TimerFired",
22420                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
22421                ),
22422            ],
22423            "rust-workers".to_string(),
22424            DEFAULT_CODEC.to_string(),
22425            None,
22426        )
22427        .expect_err("timer schedule and fire delays must agree");
22428        assert!(matches!(
22429            wrong_fired_delay,
22430            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22431                if reason == "timer_history_delay_mismatch"
22432        ));
22433    }
22434
22435    #[test]
22436    fn replay_rejects_activity_moved_before_recorded_timer() {
22437        let ctx = workflow_context(vec![
22438            history_event(
22439                "TimerScheduled",
22440                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22441            ),
22442            history_event(
22443                "TimerFired",
22444                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22445            ),
22446            history_event(
22447                "ActivityCompleted",
22448                json!({
22449                    "sequence": 2,
22450                    "activity_type": "after-timer",
22451                    "payload_codec": DEFAULT_CODEC,
22452                    "result": fixture_envelope(json!("done")),
22453                }),
22454            ),
22455        ]);
22456        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
22457        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22458
22459        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22460            activity.as_mut().poll(&mut task_context)
22461        else {
22462            panic!("reordered durable command must be rejected");
22463        };
22464        assert_eq!(failure.reason, "recorded_command_mismatch");
22465        assert_eq!(failure.sequence, Some(1));
22466        assert_eq!(failure.expected.as_deref(), Some("timer"));
22467        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
22468    }
22469
22470    #[test]
22471    fn workflow_context_emits_a_typed_named_signal_wait() {
22472        let ctx = workflow_context(Vec::new());
22473        let mut signal = Box::pin(ctx.wait_signal("finish"));
22474        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22475
22476        assert!(matches!(
22477            signal.as_mut().poll(&mut task_context),
22478            Poll::Pending
22479        ));
22480        assert_eq!(
22481            ctx.take_commands().expect("signal-wait command"),
22482            vec![json!({
22483                "type": "open_signal_wait",
22484                "signal_name": "finish",
22485            })]
22486        );
22487    }
22488
22489    #[test]
22490    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
22491        let ctx = workflow_context(Vec::new());
22492        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
22493        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22494
22495        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
22496        else {
22497            panic!("runtime-reserved signal should be rejected");
22498        };
22499        assert!(message.contains("reserved by the workflow runtime"));
22500        assert!(ctx.take_commands().expect("commands").is_empty());
22501    }
22502
22503    #[tokio::test]
22504    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
22505        let client = Client::builder("http://127.0.0.1:9")
22506            .build()
22507            .expect("client");
22508        let error = client
22509            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
22510            .await
22511            .expect_err("runtime-reserved signal should be rejected before transport");
22512
22513        assert!(
22514            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
22515        );
22516    }
22517
22518    #[test]
22519    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
22520        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22521            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22522                value.to_string(),
22523            )]))
22524            .expect("message payload");
22525            json!({
22526                "schema": MESSAGE_STREAM_SCHEMA,
22527                "stream_name": "orders",
22528                "message_id": message_id,
22529                "position": position,
22530                "payload_envelope": payload,
22531            })
22532        }
22533
22534        fn opened(sequence: u64) -> HistoryEvent {
22535            history_event(
22536                "SignalWaitOpened",
22537                json!({
22538                    "sequence": sequence,
22539                    "signal_name": MESSAGE_STREAM_SIGNAL,
22540                }),
22541            )
22542        }
22543
22544        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22545            history_event(
22546                "SignalApplied",
22547                json!({
22548                    "sequence": sequence,
22549                    "signal_name": MESSAGE_STREAM_SIGNAL,
22550                    "value": fixture_envelope(json!([delivery])),
22551                }),
22552            )
22553        }
22554
22555        fn received(delivery: Value) -> HistoryEvent {
22556            history_event(
22557                "SignalReceived",
22558                json!({
22559                    "signal_name": MESSAGE_STREAM_SIGNAL,
22560                    "arguments": fixture_envelope(json!([delivery])),
22561                    "payload_codec": DEFAULT_CODEC,
22562                }),
22563            )
22564        }
22565
22566        let client = Client::new("http://127.0.0.1:8080").expect("client");
22567        let mut worker = Worker::new(client, "rust-workers");
22568        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
22569            let messages = ctx.message_stream("orders")?.receive(2).await?;
22570            Ok(json!(messages
22571                .into_iter()
22572                .map(|message| message.message_id)
22573                .collect::<Vec<_>>()))
22574        });
22575
22576        let first = delivery("message-1", 1, "one");
22577        let second = delivery("message-2", 2, "two");
22578        let batch = worker
22579            .execute_workflow_task_decision(workflow_task(
22580                "rust.message-stream-batch",
22581                vec![
22582                    opened(1),
22583                    received(first.clone()),
22584                    applied(1, first.clone()),
22585                    received(first.clone()),
22586                    received(second),
22587                ],
22588                DEFAULT_CODEC,
22589            ))
22590            .expect("worker task consumes the available batch");
22591
22592        assert_eq!(batch.commands.len(), 1);
22593        assert_eq!(batch.commands[0]["type"], "complete_workflow");
22594        assert_eq!(
22595            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
22596                .expect("workflow result"),
22597            json!(["message-1", "message-2"])
22598        );
22599        assert_eq!(
22600            batch.message_stream_cursors,
22601            vec![json!({"stream_name": "orders", "through_position": 2})]
22602        );
22603        assert!(batch.message_stream_waits.is_empty());
22604
22605        let partial = worker
22606            .execute_workflow_task_decision(workflow_task(
22607                "rust.message-stream-batch",
22608                vec![opened(1), received(first.clone()), applied(1, first)],
22609                DEFAULT_CODEC,
22610            ))
22611            .expect("worker task returns without waiting for a missing second item");
22612        assert_eq!(partial.commands.len(), 1);
22613        assert_eq!(partial.commands[0]["type"], "complete_workflow");
22614        assert_eq!(
22615            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
22616                .expect("workflow result"),
22617            json!(["message-1"])
22618        );
22619        assert_eq!(
22620            partial.message_stream_cursors,
22621            vec![json!({"stream_name": "orders", "through_position": 1})]
22622        );
22623        assert!(partial.message_stream_waits.is_empty());
22624    }
22625
22626    #[test]
22627    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
22628        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22629            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22630                value.to_string(),
22631            )]))
22632            .expect("message payload");
22633            json!({
22634                "schema": MESSAGE_STREAM_SCHEMA,
22635                "stream_name": "orders",
22636                "message_id": message_id,
22637                "position": position,
22638                "payload_envelope": payload,
22639            })
22640        }
22641
22642        fn opened(sequence: u64) -> HistoryEvent {
22643            history_event(
22644                "SignalWaitOpened",
22645                json!({
22646                    "sequence": sequence,
22647                    "signal_name": MESSAGE_STREAM_SIGNAL,
22648                }),
22649            )
22650        }
22651
22652        fn received(delivery: Value) -> HistoryEvent {
22653            history_event(
22654                "SignalReceived",
22655                json!({
22656                    "signal_name": MESSAGE_STREAM_SIGNAL,
22657                    "arguments": fixture_envelope(json!([delivery])),
22658                    "payload_codec": DEFAULT_CODEC,
22659                }),
22660            )
22661        }
22662
22663        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22664            history_event(
22665                "SignalApplied",
22666                json!({
22667                    "sequence": sequence,
22668                    "signal_name": MESSAGE_STREAM_SIGNAL,
22669                    "value": fixture_envelope(json!([delivery])),
22670                }),
22671            )
22672        }
22673
22674        let client = Client::new("http://127.0.0.1:8080").expect("client");
22675        let mut worker = Worker::new(client, "rust-workers");
22676        worker.register_workflow(
22677            "rust.message-stream-partial-batches",
22678            |ctx, _input| async move {
22679                let stream = ctx.message_stream("orders")?;
22680                let first = stream.receive(10).await?;
22681                let second = stream.receive(10).await?;
22682                Ok(json!([
22683                    first
22684                        .into_iter()
22685                        .map(|message| message.message_id)
22686                        .collect::<Vec<_>>(),
22687                    second
22688                        .into_iter()
22689                        .map(|message| message.message_id)
22690                        .collect::<Vec<_>>(),
22691                ]))
22692            },
22693        );
22694
22695        let first = delivery("message-1", 1, "one");
22696        let second = delivery("message-2", 2, "two");
22697        let decision = worker
22698            .execute_workflow_task_decision(workflow_task(
22699                "rust.message-stream-partial-batches",
22700                vec![
22701                    opened(1),
22702                    received(first.clone()),
22703                    applied(1, first),
22704                    opened(2),
22705                    received(second.clone()),
22706                    applied(2, second),
22707                ],
22708                DEFAULT_CODEC,
22709            ))
22710            .expect("cold replay preserves both authored receive boundaries");
22711
22712        assert_eq!(decision.commands.len(), 1);
22713        assert_eq!(decision.commands[0]["type"], "complete_workflow");
22714        assert_eq!(
22715            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
22716                .expect("workflow result"),
22717            json!([["message-1"], ["message-2"]])
22718        );
22719        assert_eq!(
22720            decision.message_stream_cursors,
22721            vec![json!({"stream_name": "orders", "through_position": 2})]
22722        );
22723        assert!(decision.message_stream_waits.is_empty());
22724    }
22725
22726    #[test]
22727    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
22728        let ctx = workflow_context(Vec::new());
22729        let stream = ctx.message_stream("orders").expect("message stream");
22730        let mut receive = Box::pin(stream.receive(10));
22731        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22732
22733        assert!(matches!(
22734            receive.as_mut().poll(&mut task_context),
22735            Poll::Pending
22736        ));
22737        assert_eq!(
22738            ctx.take_commands().expect("message-stream wait command"),
22739            vec![json!({
22740                "type": "open_signal_wait",
22741                "signal_name": MESSAGE_STREAM_SIGNAL,
22742            })]
22743        );
22744        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
22745        assert!(cursors.is_empty());
22746        assert_eq!(
22747            waits,
22748            vec![json!({"stream_name": "orders", "after_position": 0})]
22749        );
22750    }
22751
22752    #[test]
22753    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
22754        let ctx = workflow_context(vec![history_event(
22755            "SignalReceived",
22756            json!({
22757                "signal_name": MESSAGE_STREAM_SIGNAL,
22758                "arguments": fixture_envelope(json!([{
22759                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
22760                    "stream_name": "orders",
22761                    "through_position": 2,
22762                }])),
22763                "payload_codec": DEFAULT_CODEC,
22764            }),
22765        )]);
22766        let stream = ctx.message_stream("orders").expect("message stream");
22767        let mut receive = Box::pin(stream.receive(10));
22768        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22769
22770        assert!(matches!(
22771            receive.as_mut().poll(&mut task_context),
22772            Poll::Pending
22773        ));
22774        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
22775        assert_eq!(
22776            cursors,
22777            vec![json!({"stream_name": "orders", "through_position": 2})]
22778        );
22779        assert_eq!(
22780            waits,
22781            vec![json!({"stream_name": "orders", "after_position": 2})]
22782        );
22783    }
22784
22785    #[test]
22786    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
22787        let mut empty_map = BTreeMap::new();
22788        let mut nested = BTreeMap::new();
22789        nested.insert(
22790            "value".to_string(),
22791            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
22792        );
22793        let values = vec![
22794            AvroValue::Bytes(vec![0, 255]),
22795            AvroValue::Long(1),
22796            AvroValue::Double(1.0),
22797            AvroValue::Array(Vec::new()),
22798            AvroValue::Map(std::mem::take(&mut empty_map)),
22799            AvroValue::Map(nested),
22800        ];
22801        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
22802        let transport = vec![json!({
22803            "schema": MESSAGE_STREAM_SCHEMA,
22804            "stream_name": "orders",
22805            "message_id": "message-1",
22806            "position": 1,
22807            "payload_envelope": payload,
22808        })];
22809
22810        for _ in 0..2 {
22811            let Some(MessageStreamDelivery::Message(message)) =
22812                decode_message_stream_delivery(transport.clone()).expect("delivery")
22813            else {
22814                panic!("message delivery expected");
22815            };
22816            assert_eq!(message.arguments, values);
22817            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
22818            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
22819        }
22820    }
22821
22822    #[test]
22823    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
22824        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
22825            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
22826                value.to_string(),
22827            )]))
22828            .expect("message payload");
22829            json!({
22830                "schema": MESSAGE_STREAM_SCHEMA,
22831                "stream_name": "orders",
22832                "message_id": message_id,
22833                "position": position,
22834                "payload_envelope": payload,
22835            })
22836        }
22837
22838        fn opened(sequence: u64) -> HistoryEvent {
22839            history_event(
22840                "SignalWaitOpened",
22841                json!({
22842                    "sequence": sequence,
22843                    "signal_name": MESSAGE_STREAM_SIGNAL,
22844                }),
22845            )
22846        }
22847
22848        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
22849            history_event(
22850                "SignalApplied",
22851                json!({
22852                    "sequence": sequence,
22853                    "signal_name": MESSAGE_STREAM_SIGNAL,
22854                    "value": fixture_envelope(json!([delivery])),
22855                }),
22856            )
22857        }
22858
22859        fn worker() -> Worker {
22860            let client = Client::new("http://127.0.0.1:8080").expect("client");
22861            let mut worker = Worker::new(client, "rust-workers");
22862            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
22863                let stream = ctx.message_stream("orders")?;
22864                let first = stream.receive_one().await?;
22865                let second = stream.receive_one().await?;
22866                Ok(json!([first.message_id, second.message_id]))
22867            });
22868            worker
22869        }
22870
22871        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
22872            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
22873            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
22874            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
22875            task
22876        }
22877
22878        let waiting = worker()
22879            .execute_workflow_task_decision(workflow_task(
22880                "rust.message-stream",
22881                Vec::new(),
22882                DEFAULT_CODEC,
22883            ))
22884            .expect("first worker opens the stream wait");
22885        assert_eq!(
22886            waiting.commands,
22887            vec![json!({
22888                "type": "open_signal_wait",
22889                "signal_name": MESSAGE_STREAM_SIGNAL,
22890            })]
22891        );
22892        assert!(waiting.message_stream_cursors.is_empty());
22893        assert_eq!(
22894            waiting.message_stream_waits,
22895            vec![json!({"stream_name": "orders", "after_position": 0})]
22896        );
22897
22898        let first_delivery = delivery("message-1", 1, "one");
22899        let first_arrival = worker()
22900            .execute_workflow_task_decision(task_with_resume(
22901                vec![opened(1)],
22902                first_delivery.clone(),
22903            ))
22904            .expect("replacement worker consumes the first arrival");
22905        assert_eq!(
22906            first_arrival.commands,
22907            vec![json!({
22908                "type": "open_signal_wait",
22909                "signal_name": MESSAGE_STREAM_SIGNAL,
22910            })]
22911        );
22912        assert_eq!(
22913            first_arrival.message_stream_cursors,
22914            vec![json!({"stream_name": "orders", "through_position": 1})]
22915        );
22916        assert_eq!(
22917            first_arrival.message_stream_waits,
22918            vec![json!({"stream_name": "orders", "after_position": 1})]
22919        );
22920
22921        let second_delivery = delivery("message-2", 2, "two");
22922        let first_applied = applied(1, first_delivery);
22923        let completed = worker()
22924            .execute_workflow_task_decision(task_with_resume(
22925                vec![opened(1), first_applied.clone(), opened(2)],
22926                second_delivery.clone(),
22927            ))
22928            .expect("next replacement worker consumes the second arrival");
22929        assert_eq!(completed.commands.len(), 1);
22930        assert_eq!(completed.commands[0]["type"], "complete_workflow");
22931        assert_eq!(
22932            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
22933                .expect("workflow result"),
22934            json!(["message-1", "message-2"])
22935        );
22936        assert_eq!(
22937            completed.message_stream_cursors,
22938            vec![json!({"stream_name": "orders", "through_position": 2})]
22939        );
22940        assert!(completed.message_stream_waits.is_empty());
22941
22942        let replay_history = vec![
22943            opened(1),
22944            first_applied,
22945            opened(2),
22946            applied(2, second_delivery),
22947        ];
22948        for _cold_worker_or_restart in 0..2 {
22949            let replayed = worker()
22950                .execute_workflow_task_decision(workflow_task(
22951                    "rust.message-stream",
22952                    replay_history.clone(),
22953                    DEFAULT_CODEC,
22954                ))
22955                .expect("cold worker replays each logical message exactly once");
22956            assert_eq!(replayed.commands.len(), 1);
22957            assert_eq!(
22958                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
22959                    .expect("replayed workflow result"),
22960                json!(["message-1", "message-2"])
22961            );
22962            assert_eq!(
22963                replayed.message_stream_cursors,
22964                vec![json!({"stream_name": "orders", "through_position": 2})]
22965            );
22966            assert!(replayed.message_stream_waits.is_empty());
22967        }
22968    }
22969
22970    #[test]
22971    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
22972        assert!(!worker_protocol_supports_message_streams("1.14"));
22973        assert!(worker_protocol_supports_message_streams("1.15"));
22974        assert!(worker_protocol_supports_message_streams("1.16"));
22975        assert!(worker_protocol_supports_message_streams(
22976            WORKER_PROTOCOL_VERSION
22977        ));
22978        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
22979    }
22980
22981    #[test]
22982    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
22983        let ctx = workflow_context(vec![
22984            history_event(
22985                "ConditionWaitOpened",
22986                json!({
22987                    "sequence": 1,
22988                    "condition_wait_id": "condition:1",
22989                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22990                    "condition_key": "signal:finish",
22991                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
22992                }),
22993            ),
22994            history_event(
22995                "ConditionWaitSatisfied",
22996                json!({
22997                    "sequence": 1,
22998                    "condition_wait_id": "condition:1",
22999                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23000                    "condition_key": "signal:finish",
23001                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
23002                }),
23003            ),
23004            history_event(
23005                "SignalReceived",
23006                json!({"signal_name": "finish", "arguments": []}),
23007            ),
23008        ]);
23009        let mut signal = Box::pin(ctx.wait_signal("finish"));
23010        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23011
23012        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23013            signal.as_mut().poll(&mut task_context)
23014        else {
23015            panic!("condition history must not resolve as a typed signal wait");
23016        };
23017        assert_eq!(failure.reason, "recorded_command_mismatch");
23018        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
23019    }
23020
23021    #[test]
23022    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
23023        let signal_then_timer = vec![
23024            history_event(
23025                "SignalWaitOpened",
23026                json!({"sequence": 1, "signal_name": "go"}),
23027            ),
23028            history_event(
23029                "SignalApplied",
23030                json!({
23031                    "sequence": 1,
23032                    "signal_name": "go",
23033                    "value": fixture_envelope(json!(["now"])),
23034                }),
23035            ),
23036            history_event(
23037                "TimerScheduled",
23038                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
23039            ),
23040            history_event(
23041                "TimerFired",
23042                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
23043            ),
23044        ];
23045
23046        let ctx = workflow_context(signal_then_timer.clone());
23047        let mut signal = Box::pin(ctx.wait_signal("go"));
23048        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23049        assert!(matches!(
23050            signal.as_mut().poll(&mut task_context),
23051            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
23052        ));
23053        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
23054        assert!(matches!(
23055            timer.as_mut().poll(&mut task_context),
23056            Poll::Ready(Ok(()))
23057        ));
23058        ctx.ensure_history_consumed()
23059            .expect("signal and timer history consumed in order");
23060
23061        let reordered = workflow_context(signal_then_timer);
23062        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
23063        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23064            timer_first.as_mut().poll(&mut task_context)
23065        else {
23066            panic!("timer cannot consume signal-wait-first history");
23067        };
23068        assert_eq!(failure.reason, "recorded_command_mismatch");
23069        assert_eq!(failure.sequence, Some(1));
23070        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
23071
23072        let timer_then_signal = vec![
23073            history_event(
23074                "TimerScheduled",
23075                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23076            ),
23077            history_event(
23078                "TimerFired",
23079                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23080            ),
23081            history_event(
23082                "SignalWaitOpened",
23083                json!({"sequence": 2, "signal_name": "go"}),
23084            ),
23085            history_event(
23086                "SignalApplied",
23087                json!({
23088                    "sequence": 2,
23089                    "signal_name": "go",
23090                    "value": fixture_envelope(json!([])),
23091                }),
23092            ),
23093        ];
23094        let reordered = workflow_context(timer_then_signal);
23095        let mut signal_first = Box::pin(reordered.wait_signal("go"));
23096        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23097            signal_first.as_mut().poll(&mut task_context)
23098        else {
23099            panic!("signal wait cannot consume timer-first history");
23100        };
23101        assert_eq!(failure.reason, "recorded_command_mismatch");
23102        assert_eq!(failure.sequence, Some(1));
23103        assert_eq!(failure.expected.as_deref(), Some("timer"));
23104    }
23105
23106    #[test]
23107    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
23108        let duplicate_timer = WorkflowState::new(
23109            vec![
23110                history_event(
23111                    "TimerScheduled",
23112                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23113                ),
23114                history_event(
23115                    "TimerScheduled",
23116                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23117                ),
23118            ],
23119            "rust-workers".to_string(),
23120            DEFAULT_CODEC.to_string(),
23121            None,
23122        )
23123        .expect_err("one workflow sequence cannot schedule two timers");
23124        assert!(matches!(
23125            duplicate_timer,
23126            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23127                if reason == "timer_schedule_missing_or_duplicate"
23128        ));
23129
23130        let colliding_kinds = WorkflowState::new(
23131            vec![
23132                history_event(
23133                    "TimerScheduled",
23134                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23135                ),
23136                history_event(
23137                    "ActivityCompleted",
23138                    json!({"sequence": 1, "activity_type": "same-sequence"}),
23139                ),
23140            ],
23141            "rust-workers".to_string(),
23142            DEFAULT_CODEC.to_string(),
23143            None,
23144        )
23145        .expect_err("one workflow sequence cannot identify two command kinds");
23146        assert!(matches!(
23147            colliding_kinds,
23148            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23149                if reason == "durable_command_sequence_collision"
23150        ));
23151
23152        let duplicate_signal_wait = WorkflowState::new(
23153            vec![
23154                history_event(
23155                    "SignalWaitOpened",
23156                    json!({"sequence": 1, "signal_name": "go"}),
23157                ),
23158                history_event(
23159                    "SignalWaitOpened",
23160                    json!({"sequence": 1, "signal_name": "go"}),
23161                ),
23162            ],
23163            "rust-workers".to_string(),
23164            DEFAULT_CODEC.to_string(),
23165            None,
23166        )
23167        .expect_err("one workflow sequence cannot open two signal waits");
23168        assert!(matches!(
23169            duplicate_signal_wait,
23170            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23171                if reason == "signal_wait_open_missing_or_duplicate"
23172        ));
23173    }
23174
23175    #[test]
23176    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
23177        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
23178            .expect("side-effect result");
23179        let ctx = workflow_context(vec![history_event(
23180            "SideEffectRecorded",
23181            json!({"sequence": 99, "result": result}),
23182        )]);
23183
23184        let replayed: Value = ctx
23185            .side_effect(|| panic!("recorded side effect must not run"))
23186            .expect("positive global workflow sequence is valid");
23187        assert_eq!(replayed, json!({"captured": true}));
23188        ctx.ensure_history_consumed().expect("history consumed");
23189    }
23190
23191    #[test]
23192    fn workflow_history_rejects_zero_and_descending_command_sequences() {
23193        let result =
23194            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
23195        let zero = WorkflowState::new(
23196            vec![history_event(
23197                "SideEffectRecorded",
23198                json!({"sequence": 0, "result": result.clone()}),
23199            )],
23200            "rust-workers".to_string(),
23201            DEFAULT_CODEC.to_string(),
23202            None,
23203        )
23204        .expect_err("durable command sequences must be positive");
23205        assert!(matches!(
23206            zero,
23207            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23208                if reason == "durable_command_sequence_invalid"
23209        ));
23210
23211        let descending = WorkflowState::new(
23212            vec![
23213                history_event(
23214                    "SideEffectRecorded",
23215                    json!({"sequence": 3, "result": result}),
23216                ),
23217                history_event(
23218                    "VersionMarkerRecorded",
23219                    json!({
23220                        "sequence": 2,
23221                        "change_id": "descending-marker",
23222                        "version": 1,
23223                        "min_supported": 1,
23224                        "max_supported": 1,
23225                    }),
23226                ),
23227            ],
23228            "rust-workers".to_string(),
23229            DEFAULT_CODEC.to_string(),
23230            None,
23231        )
23232        .expect_err("new durable commands must remain strictly ordered");
23233        let Error::NonDeterministicReplay(failure) = descending else {
23234            panic!("expected typed replay failure");
23235        };
23236        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
23237        assert_eq!(failure.sequence, Some(2));
23238        assert_eq!(
23239            failure.expected.as_deref(),
23240            Some("workflow sequence greater than 3")
23241        );
23242        assert_eq!(failure.actual.as_deref(), Some("2"));
23243    }
23244
23245    #[test]
23246    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
23247        fn worker() -> Worker {
23248            let client = Client::new("http://127.0.0.1:8080").expect("client");
23249            let mut worker = Worker::new(client, "rust-workers");
23250            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
23251                ctx.wait_signal("finish").await?;
23252                let marker: String =
23253                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
23254                assert_eq!(marker, "after-finish");
23255                Ok(json!("finished"))
23256            });
23257            worker
23258        }
23259
23260        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
23261            .expect("side-effect result");
23262        let task = workflow_task(
23263            "rust.finish-after-gaps",
23264            vec![
23265                history_event(
23266                    "SignalWaitOpened",
23267                    json!({"sequence": 1, "signal_name": "finish"}),
23268                ),
23269                history_event(
23270                    "SignalReceived",
23271                    json!({
23272                        "signal_id": "increment-3",
23273                        "signal_name": "increment",
23274                        "workflow_sequence": 2,
23275                        "payload_codec": DEFAULT_CODEC,
23276                        "arguments": fixture_envelope(json!([3])),
23277                    }),
23278                ),
23279                history_event(
23280                    "SignalReceived",
23281                    json!({
23282                        "signal_id": "increment-5",
23283                        "signal_name": "increment",
23284                        "workflow_sequence": 3,
23285                        "payload_codec": DEFAULT_CODEC,
23286                        "arguments": fixture_envelope(json!([5])),
23287                    }),
23288                ),
23289                history_event(
23290                    "SignalReceived",
23291                    json!({
23292                        "signal_id": "finish",
23293                        "signal_name": "finish",
23294                        "workflow_sequence": 4,
23295                        "payload_codec": DEFAULT_CODEC,
23296                        "arguments": fixture_envelope(json!([])),
23297                    }),
23298                ),
23299                history_event(
23300                    "SignalApplied",
23301                    json!({
23302                        "sequence": 1,
23303                        "signal_id": "finish",
23304                        "signal_name": "finish",
23305                        "payload_codec": DEFAULT_CODEC,
23306                        "value": fixture_envelope(json!([])),
23307                    }),
23308                ),
23309                history_event(
23310                    "SideEffectRecorded",
23311                    json!({"sequence": 5, "result": marker}),
23312                ),
23313            ],
23314            DEFAULT_CODEC,
23315        );
23316
23317        for _original_or_cold_worker in 0..2 {
23318            let commands = worker()
23319                .execute_workflow_task(task.clone())
23320                .expect("signal gaps preserve deterministic replay");
23321            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
23322            assert_eq!(commands[0]["type"], "complete_workflow");
23323            assert_eq!(
23324                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23325                json!("finished")
23326            );
23327        }
23328    }
23329
23330    #[test]
23331    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
23332        let ctx = workflow_context(Vec::new());
23333        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
23334        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23335        assert!(matches!(
23336            sleep.as_mut().poll(&mut task_context),
23337            Poll::Ready(Err(Error::TimerDurationOverflow))
23338        ));
23339        assert!(ctx.take_commands().expect("commands").is_empty());
23340    }
23341
23342    #[test]
23343    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
23344        let entries = AvroValue::Map(BTreeMap::from([
23345            ("text".to_string(), AvroValue::String("same".to_string())),
23346            (
23347                "nested".to_string(),
23348                AvroValue::Map(BTreeMap::from([
23349                    ("beta".to_string(), AvroValue::Long(2)),
23350                    ("alpha".to_string(), AvroValue::Long(1)),
23351                ])),
23352            ),
23353            ("long".to_string(), AvroValue::Long(7)),
23354            ("double".to_string(), AvroValue::Double(7.0)),
23355            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
23356        ]));
23357        let ctx = workflow_context(Vec::new());
23358        ctx.upsert_memo(entries.clone()).expect("valid memo update");
23359        let commands = ctx.take_commands().expect("commands");
23360
23361        assert_eq!(commands.len(), 1);
23362        assert_eq!(commands[0]["type"], "upsert_memo");
23363        let server_entries = json!({
23364            "codec": "avro",
23365            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
23366        });
23367        assert_eq!(
23368            commands[0]["entries"]
23369                .as_object()
23370                .expect("entries envelope")
23371                .keys()
23372                .collect::<Vec<_>>(),
23373            vec!["blob", "codec"]
23374        );
23375        assert_eq!(commands[0]["entries"], server_entries);
23376        let wire_entries =
23377            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
23378        assert_eq!(wire_entries, entries);
23379
23380        let history = vec![history_event(
23381            "MemoUpserted",
23382            json!({
23383                "sequence": 1,
23384                "entries": server_entries.clone(),
23385                "merged": server_entries,
23386            }),
23387        )];
23388        let replay = workflow_context(history.clone());
23389        replay
23390            .upsert_memo(entries.clone())
23391            .expect("matching replay identity");
23392        assert!(replay.take_commands().expect("replay commands").is_empty());
23393
23394        let changed_types = AvroValue::Map(BTreeMap::from([
23395            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
23396            (
23397                "nested".to_string(),
23398                AvroValue::Map(BTreeMap::from([
23399                    ("alpha".to_string(), AvroValue::Long(1)),
23400                    ("beta".to_string(), AvroValue::Long(2)),
23401                ])),
23402            ),
23403            ("long".to_string(), AvroValue::Double(7.0)),
23404            ("double".to_string(), AvroValue::Long(7)),
23405            ("binary".to_string(), AvroValue::String("same".to_string())),
23406        ]));
23407        let error = workflow_context(history)
23408            .upsert_memo(changed_types)
23409            .expect_err("memo replay identity must preserve Avro value types");
23410        assert!(matches!(
23411            error,
23412            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23413        ));
23414    }
23415
23416    #[test]
23417    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
23418        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
23419            .expect("memo envelope");
23420        let replay = workflow_context(vec![history_event(
23421            "MemoUpserted",
23422            json!({
23423                "sequence": 1,
23424                "entries": original.clone(),
23425                "merged": original
23426            }),
23427        )]);
23428        let error = replay
23429            .upsert_memo(json!({"stage": "changed"}))
23430            .expect_err("changed memo update must fail replay");
23431        assert!(matches!(
23432            error,
23433            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23434        ));
23435
23436        let invalid = workflow_context(Vec::new())
23437            .upsert_memo(
23438                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
23439            )
23440            .expect_err("oversized key");
23441        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
23442    }
23443
23444    #[test]
23445    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
23446        let negative_zero = AvroValue::Map(BTreeMap::from([(
23447            "reading".to_string(),
23448            AvroValue::Double(-0.0),
23449        )]));
23450        let negative_zero_envelope =
23451            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
23452        let history = vec![history_event(
23453            "MemoUpserted",
23454            json!({
23455                "sequence": 1,
23456                "entries": negative_zero_envelope.clone(),
23457                "merged": negative_zero_envelope,
23458            }),
23459        )];
23460
23461        workflow_context(history.clone())
23462            .upsert_memo(negative_zero)
23463            .expect("matching negative-zero history identity");
23464
23465        let error = workflow_context(history)
23466            .upsert_memo(AvroValue::Map(BTreeMap::from([(
23467                "reading".to_string(),
23468                AvroValue::Double(0.0),
23469            )])))
23470            .expect_err("positive zero must not consume negative-zero memo history");
23471        assert!(matches!(
23472            error,
23473            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
23474        ));
23475    }
23476
23477    #[test]
23478    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
23479        let supported = json!({
23480            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
23481            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
23482        });
23483        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
23484        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
23485            "workflow_memo_updates": {"supported": false},
23486            "supported_workflow_task_commands": ["upsert_memo"]
23487        }))));
23488        assert!(commands_use_workflow_memo_updates(&[json!({
23489            "type": "upsert_memo",
23490            "entries": {"stage": "processing"}
23491        })]));
23492    }
23493
23494    #[test]
23495    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
23496        let client = Client::new("http://127.0.0.1:8080").expect("client");
23497        let mut worker = Worker::new(client, "rust-workers");
23498        worker.register_workflow("rust.timer", |ctx, _input| async move {
23499            ctx.sleep(Duration::from_secs(5)).await?;
23500            ctx.activity("after-timer", json!([])).await
23501        });
23502
23503        let task = |history_events| WorkflowTask {
23504            task_id: "wft-rust-timer-1".to_string(),
23505            workflow_command_id: None,
23506            workflow_id: Some("wf-rust-timer".to_string()),
23507            run_id: Some("run-rust-timer".to_string()),
23508            workflow_type: "rust.timer".to_string(),
23509            cancel_requested: false,
23510            payload_codec: DEFAULT_CODEC.to_string(),
23511            arguments: Some(
23512                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23513            ),
23514            history_events,
23515            total_history_events: None,
23516            history_size_bytes: None,
23517            continue_as_new_recommended: None,
23518            history_budget_pressure: None,
23519            next_history_page_token: None,
23520            workflow_task_attempt: 1,
23521            workflow_signal_id: None,
23522            signal_name: None,
23523            signal_arguments: None,
23524            workflow_update_id: None,
23525            update_name: None,
23526            lease_owner: Some("rust-worker".to_string()),
23527        };
23528
23529        let initial = worker
23530            .execute_workflow_task(task(Vec::new()))
23531            .expect("initial timer task");
23532        assert_eq!(
23533            initial,
23534            vec![json!({"type": "start_timer", "delay_seconds": 5})]
23535        );
23536
23537        let activity_result =
23538            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
23539        let replayed = worker
23540            .execute_workflow_task(task(vec![
23541                history_event(
23542                    "TimerScheduled",
23543                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23544                ),
23545                history_event(
23546                    "TimerFired",
23547                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23548                ),
23549                history_event(
23550                    "ActivityCompleted",
23551                    json!({
23552                        "sequence": 2,
23553                        "activity_type": "after-timer",
23554                        "payload_codec": DEFAULT_CODEC,
23555                        "result": activity_result,
23556                    }),
23557                ),
23558            ]))
23559            .expect("replayed workflow task");
23560        assert_eq!(replayed.len(), 1);
23561        assert_eq!(replayed[0]["type"], "complete_workflow");
23562        assert_eq!(
23563            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
23564            json!("done")
23565        );
23566    }
23567
23568    #[test]
23569    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
23570        let client = Client::new("http://127.0.0.1:8080").expect("client");
23571        let mut worker = Worker::new(client, "rust-workers");
23572        worker.register_workflow("rust.continue", |ctx, _input| async move {
23573            ctx.continue_as_new_with_options(
23574                ContinueAsNewOptions::new()
23575                    .workflow_type("rust.next")
23576                    .task_queue("next-workers"),
23577                json!([2, {"cursor": "next"}]),
23578            )
23579        });
23580
23581        let commands = worker
23582            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
23583            .expect("continue-as-new command");
23584
23585        assert_eq!(commands.len(), 1);
23586        assert_eq!(commands[0]["type"], "continue_as_new");
23587        assert_eq!(commands[0]["workflow_type"], "rust.next");
23588        assert_eq!(commands[0]["queue"], "next-workers");
23589        assert_eq!(
23590            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
23591                .expect("continue-as-new arguments"),
23592            json!([2, {"cursor": "next"}])
23593        );
23594    }
23595
23596    #[test]
23597    fn continue_as_new_preserves_typed_arguments() {
23598        let client = Client::new("http://127.0.0.1:8080").expect("client");
23599        let mut worker = Worker::new(client, "rust-workers");
23600        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
23601            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
23602            unreachable!("continue-as-new returns a control-flow error")
23603        });
23604
23605        let commands = worker
23606            .execute_workflow_task(workflow_task(
23607                "rust.typed-continue",
23608                Vec::new(),
23609                DEFAULT_CODEC,
23610            ))
23611            .expect("typed continue-as-new command");
23612
23613        assert_eq!(commands[0]["type"], "continue_as_new");
23614        assert_eq!(
23615            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
23616                .expect("typed continue arguments"),
23617            AvroValue::Array(vec![typed_fidelity_probe()])
23618        );
23619    }
23620
23621    #[test]
23622    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
23623        let client = Client::new("http://127.0.0.1:8080").expect("client");
23624        let mut worker = Worker::new(client, "rust-workers");
23625        worker.register_workflow("rust.continue", |ctx, _input| async move {
23626            ctx.continue_as_new(json!([2]))
23627        });
23628        let task = workflow_task(
23629            "rust.continue",
23630            vec![history_event(
23631                "WorkflowContinuedAsNew",
23632                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
23633            )],
23634            DEFAULT_CODEC,
23635        );
23636
23637        for _worker_restart_or_redelivery in 0..2 {
23638            let commands = worker
23639                .execute_workflow_task(task.clone())
23640                .expect("recorded transition replays");
23641            assert!(
23642                commands.is_empty(),
23643                "replay must not emit another successor"
23644            );
23645        }
23646    }
23647
23648    #[test]
23649    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
23650        let ctx = workflow_context(Vec::new());
23651        let error = ctx
23652            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
23653            .expect_err("blank queue must be rejected");
23654
23655        let Error::InvalidContinueAsNewOptions(error) = error else {
23656            panic!("expected typed continue-as-new validation error");
23657        };
23658        assert_eq!(error.field, "task_queue");
23659        assert!(ctx.take_commands().expect("commands").is_empty());
23660    }
23661
23662    #[test]
23663    fn workflow_context_exposes_server_history_budget() {
23664        let client = Client::new("http://127.0.0.1:8080").expect("client");
23665        let mut worker = Worker::new(client, "rust-workers");
23666        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
23667            let budget = ctx.history_budget()?;
23668            Ok(json!({
23669                "events": budget.event_count,
23670                "bytes": budget.size_bytes,
23671                "recommended": budget.continue_as_new_recommended,
23672                "pressure": budget.pressure,
23673            }))
23674        });
23675        let task: WorkflowTask = serde_json::from_value(json!({
23676            "task_id": "task-history-budget",
23677            "workflow_type": "rust.history-budget",
23678            "payload_codec": DEFAULT_CODEC,
23679            "history_events": [],
23680            "total_history_events": 480,
23681            "history_size_bytes": 1_048_576,
23682            "continue_as_new_recommended": true,
23683            "history_budget_pressure": "continue_as_new_recommended",
23684        }))
23685        .expect("published workflow task");
23686
23687        let commands = worker
23688            .execute_workflow_task(task)
23689            .expect("history-budget workflow");
23690        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
23691        assert_eq!(result["events"], 480);
23692        assert_eq!(result["bytes"], 1_048_576);
23693        assert_eq!(result["recommended"], true);
23694        assert_eq!(result["pressure"], "continue_as_new_recommended");
23695    }
23696
23697    #[test]
23698    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
23699        let client = Client::new("http://127.0.0.1:8080").expect("client");
23700        let mut worker = Worker::new(client, "rust-workers");
23701        worker.register_workflow("rust.failing", |_ctx, _input| async move {
23702            Err(Error::Codec("rust_conformance_failure".to_string()))
23703        });
23704        let task = WorkflowTask {
23705            task_id: "wft-rust-failing-1".to_string(),
23706            workflow_command_id: None,
23707            workflow_id: Some("wf-rust-failing".to_string()),
23708            run_id: Some("run-rust-failing".to_string()),
23709            workflow_type: "rust.failing".to_string(),
23710            cancel_requested: false,
23711            payload_codec: DEFAULT_CODEC.to_string(),
23712            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
23713            history_events: Vec::new(),
23714            total_history_events: Some(0),
23715            history_size_bytes: None,
23716            continue_as_new_recommended: None,
23717            history_budget_pressure: None,
23718            next_history_page_token: None,
23719            workflow_task_attempt: 1,
23720            workflow_signal_id: None,
23721            signal_name: None,
23722            signal_arguments: None,
23723            workflow_update_id: None,
23724            update_name: None,
23725            lease_owner: Some("rust-worker".to_string()),
23726        };
23727
23728        let commands = worker
23729            .execute_workflow_task(task)
23730            .expect("handler failure becomes a workflow command");
23731
23732        assert_eq!(commands.len(), 1);
23733        assert_eq!(commands[0]["type"], "fail_workflow");
23734        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
23735        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
23736        assert_eq!(commands[0]["non_retryable"], false);
23737        assert_eq!(
23738            commands[0]["message"],
23739            "codec error: rust_conformance_failure"
23740        );
23741        assert_eq!(
23742            commands[0]["exception"]["message"],
23743            "codec error: rust_conformance_failure"
23744        );
23745    }
23746
23747    #[test]
23748    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
23749        let client = Client::new("http://127.0.0.1:8080").expect("client");
23750        let mut worker = Worker::new(client, "rust-workers");
23751        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
23752            let _: String = ctx.side_effect(|| "captured".to_string())?;
23753            Err(Error::WorkerLoop("application failure".to_string()))
23754        });
23755
23756        let commands = worker
23757            .execute_workflow_task(workflow_task(
23758                "rust.failing-after-side-effect",
23759                Vec::new(),
23760                DEFAULT_CODEC,
23761            ))
23762            .expect("ordinary failure remains a workflow decision");
23763
23764        assert_eq!(commands.len(), 2);
23765        assert_eq!(commands[0]["type"], "record_side_effect");
23766        assert_eq!(commands[1]["type"], "fail_workflow");
23767    }
23768
23769    #[test]
23770    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
23771        let client = Client::new("http://127.0.0.1:8080").expect("client");
23772        let mut worker = Worker::new(client, "rust-workers");
23773        worker.register_workflow("rust.redrive", |ctx, _input| async move {
23774            ctx.activity("greet", json!([])).await?;
23775            Ok(Value::Null)
23776        });
23777        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
23778            match ctx.activity("greet", json!([])).await {
23779                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
23780                result => result,
23781            }
23782        });
23783
23784        let failed = history_event(
23785            "ActivityFailed",
23786            json!({
23787                "sequence": 1,
23788                "activity_type": "greet",
23789                "activity_execution_id": "activity-1",
23790                "message": "failed"
23791            }),
23792        );
23793        let commands = worker
23794            .execute_workflow_task(workflow_task(
23795                "rust.redrive",
23796                vec![failed.clone()],
23797                DEFAULT_CODEC,
23798            ))
23799            .expect("recorded failure becomes a workflow command");
23800        assert_eq!(commands[0]["type"], "fail_workflow");
23801        assert_eq!(commands[0]["failed_step_sequence"], 1);
23802        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
23803
23804        let translated = worker
23805            .execute_workflow_task(workflow_task(
23806                "rust.redrive-translated",
23807                vec![failed],
23808                DEFAULT_CODEC,
23809            ))
23810            .expect("translated failure becomes a workflow command");
23811        assert_eq!(translated[0]["type"], "fail_workflow");
23812        assert!(translated[0].get("failed_step_sequence").is_none());
23813        assert!(translated[0].get("failed_activity_execution_id").is_none());
23814
23815        let without_identity = worker
23816            .execute_workflow_task(workflow_task(
23817                "rust.redrive",
23818                vec![history_event(
23819                    "ActivityFailed",
23820                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
23821                )],
23822                DEFAULT_CODEC,
23823            ))
23824            .expect("incomplete identity still fails the workflow");
23825        assert!(without_identity[0].get("failed_step_sequence").is_none());
23826
23827        let timed_out = worker
23828            .execute_workflow_task(workflow_task(
23829                "rust.redrive",
23830                vec![history_event(
23831                    "ActivityTimedOut",
23832                    json!({
23833                        "sequence": 1,
23834                        "activity_type": "greet",
23835                        "activity_execution_id": "activity-timeout",
23836                    }),
23837                )],
23838                DEFAULT_CODEC,
23839            ))
23840            .expect("timeout still fails the workflow");
23841        assert!(timed_out[0].get("failed_step_sequence").is_none());
23842    }
23843
23844    #[test]
23845    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
23846        let client = Client::new("http://127.0.0.1:8080").expect("client");
23847        let mut worker = Worker::new(client, "rust-workers");
23848        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
23849            let first = ctx.activity("first", json!([])).await?;
23850            let second = ctx.activity("second", json!([first.clone()])).await?;
23851            Ok(json!({"first": first, "second": second}))
23852        });
23853        let first = history_event(
23854            "ActivityCompleted",
23855            json!({
23856                "sequence": 1,
23857                "activity_type": "first",
23858                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
23859                "payload_codec": DEFAULT_CODEC,
23860                "reused_from_run_id": "failed-run",
23861                "reused_activity_execution_id": "original-first",
23862            }),
23863        );
23864
23865        let retry = worker
23866            .execute_workflow_task(workflow_task(
23867                "rust.redrive-successor",
23868                vec![first.clone()],
23869                DEFAULT_CODEC,
23870            ))
23871            .expect("reused result replays before failed step");
23872        assert_eq!(retry.len(), 1);
23873        assert_eq!(retry[0]["type"], "schedule_activity");
23874        assert_eq!(retry[0]["activity_type"], "second");
23875        assert_eq!(
23876            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
23877            json!(["recorded"]),
23878        );
23879
23880        let second = history_event(
23881            "ActivityCompleted",
23882            json!({
23883                "sequence": 2,
23884                "activity_type": "second",
23885                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
23886                "payload_codec": DEFAULT_CODEC,
23887            }),
23888        );
23889        let completed = worker
23890            .execute_workflow_task(workflow_task(
23891                "rust.redrive-successor",
23892                vec![first, second],
23893                DEFAULT_CODEC,
23894            ))
23895            .expect("retried step completes the successor");
23896        assert_eq!(completed.len(), 1);
23897        assert_eq!(completed[0]["type"], "complete_workflow");
23898        assert_eq!(
23899            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
23900            json!({"first": "recorded", "second": "retried"}),
23901        );
23902    }
23903
23904    #[test]
23905    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
23906        let client = Client::new("http://127.0.0.1:8080").expect("client");
23907        let mut worker = Worker::new(client, "rust-workers");
23908        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
23909            Err(Error::WorkerLoop("application failure".to_string()))
23910        });
23911        let result =
23912            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
23913
23914        let error = worker
23915            .execute_workflow_task(workflow_task(
23916                "rust.removed-side-effect",
23917                vec![history_event(
23918                    "SideEffectRecorded",
23919                    json!({"sequence": 1, "result": result}),
23920                )],
23921                DEFAULT_CODEC,
23922            ))
23923            .expect_err("removed committed history must not become fail_workflow");
23924
23925        let Error::NonDeterministicReplay(failure) = error else {
23926            panic!("expected typed replay failure");
23927        };
23928        assert_eq!(failure.reason, "recorded_commands_unconsumed");
23929        assert_eq!(failure.sequence, Some(1));
23930        assert_eq!(failure.expected.as_deref(), Some("side effect"));
23931    }
23932
23933    #[test]
23934    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
23935        let client = Client::new("http://127.0.0.1:8080").expect("client");
23936        let mut worker = Worker::new(client, "rust-workers");
23937        worker.register_workflow(
23938            "rust.side-effect-before-marker-error",
23939            |ctx, _input| async move {
23940                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
23941                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
23942                ctx.get_version("restart-safe", 2, 2)?;
23943                Ok(Value::Null)
23944            },
23945        );
23946
23947        let error = worker
23948            .execute_workflow_task(workflow_task(
23949                "rust.side-effect-before-marker-error",
23950                vec![history_event(
23951                    "VersionMarkerRecorded",
23952                    json!({
23953                        "sequence": 1,
23954                        "change_id": "restart-safe",
23955                        "version": 1,
23956                        "min_supported": 1,
23957                        "max_supported": 1,
23958                    }),
23959                )],
23960                DEFAULT_CODEC,
23961            ))
23962            .expect_err("replay error must return no queued workflow commands");
23963
23964        let Error::NonDeterministicReplay(failure) = error else {
23965            panic!("expected typed replay failure");
23966        };
23967        assert_eq!(failure.reason, "version_marker_incompatible_range");
23968        assert_eq!(failure.sequence, Some(1));
23969    }
23970
23971    #[test]
23972    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
23973        let client = Client::new("http://127.0.0.1:8080").expect("client");
23974        let mut worker = Worker::new(client, "rust-workers");
23975        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
23976            ctx.sleep(Duration::from_secs(5)).await?;
23977            Ok(json!({"status": "timer fired"}))
23978        });
23979
23980        let task = WorkflowTask {
23981            task_id: "wft-rust-timer-pending".to_string(),
23982            workflow_command_id: None,
23983            workflow_id: Some("wf-rust-timer".to_string()),
23984            run_id: Some("run-rust-timer".to_string()),
23985            workflow_type: "rust.timer.pending".to_string(),
23986            cancel_requested: false,
23987            payload_codec: DEFAULT_CODEC.to_string(),
23988            arguments: Some(
23989                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
23990            ),
23991            history_events: vec![history_event(
23992                "TimerScheduled",
23993                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23994            )],
23995            total_history_events: Some(1),
23996            history_size_bytes: None,
23997            continue_as_new_recommended: None,
23998            history_budget_pressure: None,
23999            next_history_page_token: None,
24000            workflow_task_attempt: 1,
24001            workflow_signal_id: None,
24002            signal_name: None,
24003            signal_arguments: None,
24004            workflow_update_id: None,
24005            update_name: None,
24006            lease_owner: Some("rust-worker".to_string()),
24007        };
24008
24009        for _redelivery_or_restart in 0..2 {
24010            let commands = worker
24011                .execute_workflow_task(task.clone())
24012                .expect("recorded timer remains pending");
24013            assert!(
24014                commands.is_empty(),
24015                "recorded timer must not be rescheduled"
24016            );
24017        }
24018    }
24019
24020    #[test]
24021    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
24022        let client = Client::new("http://127.0.0.1:8080").expect("client");
24023        let mut worker = Worker::new(client, "rust-workers");
24024        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
24025            Ok(json!({"status": "completed"}))
24026        });
24027        let task = WorkflowTask {
24028            task_id: "wft-rust-timer-removed".to_string(),
24029            workflow_command_id: None,
24030            workflow_id: Some("wf-rust-timer".to_string()),
24031            run_id: Some("run-rust-timer".to_string()),
24032            workflow_type: "rust.timer.removed".to_string(),
24033            cancel_requested: false,
24034            payload_codec: DEFAULT_CODEC.to_string(),
24035            arguments: Some(
24036                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24037            ),
24038            history_events: vec![
24039                history_event(
24040                    "TimerScheduled",
24041                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24042                ),
24043                history_event(
24044                    "TimerFired",
24045                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24046                ),
24047            ],
24048            total_history_events: Some(2),
24049            history_size_bytes: None,
24050            continue_as_new_recommended: None,
24051            history_budget_pressure: None,
24052            next_history_page_token: None,
24053            workflow_task_attempt: 1,
24054            workflow_signal_id: None,
24055            signal_name: None,
24056            signal_arguments: None,
24057            workflow_update_id: None,
24058            update_name: None,
24059            lease_owner: Some("rust-worker".to_string()),
24060        };
24061
24062        let Error::NonDeterministicReplay(failure) = worker
24063            .execute_workflow_task(task)
24064            .expect_err("removed timer must fail replay")
24065        else {
24066            panic!("expected typed replay failure");
24067        };
24068        assert_eq!(failure.reason, "recorded_commands_unconsumed");
24069        assert_eq!(failure.sequence, Some(1));
24070    }
24071
24072    #[test]
24073    fn workflow_context_emits_explicit_child_workflow_contract() {
24074        let ctx = WorkflowContext {
24075            cancellation_scope_id: "root".into(),
24076            state: Arc::new(Mutex::new(
24077                WorkflowState::new_with_identity(
24078                    Vec::new(),
24079                    Some("wf-parent".to_string()),
24080                    Some("run-parent".to_string()),
24081                    "parent-workers".to_string(),
24082                    DEFAULT_CODEC.to_string(),
24083                    None,
24084                )
24085                .expect("workflow state"),
24086            )),
24087        };
24088        let options = ChildWorkflowOptions::new("python-workers")
24089            .parent_close_policy(ParentClosePolicy::RequestCancel)
24090            .retry_policy(ChildWorkflowRetryPolicy {
24091                max_attempts: Some(3),
24092                backoff_seconds: vec![1, 5],
24093                non_retryable_error_types: vec!["ValidationError".to_string()],
24094            })
24095            .execution_timeout_seconds(600)
24096            .run_timeout_seconds(120);
24097        let mut call = Box::pin(ctx.start_child_workflow(
24098            "python.fulfil-order",
24099            options,
24100            json!([{"order_id": "order-42"}]),
24101        ));
24102        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24103
24104        assert!(matches!(
24105            call.as_mut().poll(&mut task_context),
24106            Poll::Pending
24107        ));
24108        let commands = ctx.take_commands().expect("commands");
24109        assert_eq!(commands.len(), 1);
24110        let command = &commands[0];
24111        assert_eq!(command["type"], "start_child_workflow");
24112        assert_eq!(command["workflow_type"], "python.fulfil-order");
24113        assert_eq!(command["queue"], "python-workers");
24114        assert_eq!(command["parent_close_policy"], "request_cancel");
24115        assert_eq!(command["retry_policy"]["max_attempts"], 3);
24116        assert_eq!(command["execution_timeout_seconds"], 600);
24117        assert_eq!(command["run_timeout_seconds"], 120);
24118        assert_eq!(
24119            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
24120            json!([{"order_id": "order-42"}])
24121        );
24122    }
24123
24124    fn child_parent_worker() -> Worker {
24125        let client = Client::new("http://127.0.0.1:8080").expect("client");
24126        let mut worker = Worker::new(client, "rust-parent-workers");
24127        worker.register_workflow("rust.parent", |ctx, _input| async move {
24128            let child = ctx
24129                .start_child_workflow(
24130                    "python.child",
24131                    ChildWorkflowOptions::new("python-child-workers")
24132                        .parent_close_policy(ParentClosePolicy::Terminate),
24133                    json!([{"codec_probe": [1, true, "rust"]}]),
24134                )
24135                .await?;
24136            Ok(json!({
24137                "parent_workflow_id": child.parent.workflow_id,
24138                "parent_run_id": child.parent.run_id,
24139                "child_workflow_id": child.child.workflow_id,
24140                "child_run_id": child.child.run_id,
24141                "child_workflow_type": child.child_workflow_type,
24142                "result": child.result,
24143            }))
24144        });
24145        worker
24146    }
24147
24148    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
24149        WorkflowTask {
24150            task_id: "wft-child-parent".to_string(),
24151            workflow_command_id: None,
24152            workflow_id: Some("wf-parent".to_string()),
24153            run_id: Some("run-parent".to_string()),
24154            workflow_type: "rust.parent".to_string(),
24155            cancel_requested: false,
24156            payload_codec: DEFAULT_CODEC.to_string(),
24157            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24158            history_events: vec![
24159                HistoryEvent {
24160                    event_type: "ChildWorkflowScheduled".to_string(),
24161                    payload: json!({
24162                        "sequence": 1,
24163                        "child_call_id": "call-child",
24164                        "child_workflow_instance_id": "wf-child",
24165                        "child_workflow_run_id": "run-child",
24166                        "child_workflow_type": "python.child",
24167                        "parent_close_policy": "terminate",
24168                    }),
24169                    raw: HashMap::new(),
24170                },
24171                HistoryEvent {
24172                    event_type: event_type.to_string(),
24173                    payload,
24174                    raw: HashMap::new(),
24175                },
24176            ],
24177            total_history_events: Some(2),
24178            history_size_bytes: None,
24179            continue_as_new_recommended: None,
24180            history_budget_pressure: None,
24181            next_history_page_token: None,
24182            workflow_task_attempt: 1,
24183            workflow_signal_id: None,
24184            signal_name: None,
24185            signal_arguments: None,
24186            workflow_update_id: None,
24187            update_name: None,
24188            lease_owner: Some("rust-worker".to_string()),
24189        }
24190    }
24191
24192    #[test]
24193    fn committed_child_result_replays_without_starting_a_duplicate() {
24194        let worker = child_parent_worker();
24195        let task = child_parent_task(
24196            "ChildRunCompleted",
24197            json!({
24198                "sequence": 1,
24199                "child_call_id": "call-child",
24200                "child_workflow_instance_id": "wf-child",
24201                "child_workflow_run_id": "run-child",
24202                "child_workflow_type": "python.child",
24203                "payload_codec": DEFAULT_CODEC,
24204                "result": fixture_envelope(json!({"from":"python","ok":true})),
24205            }),
24206        );
24207
24208        for _restart in 0..2 {
24209            let commands = worker
24210                .execute_workflow_task(task.clone())
24211                .expect("replayed parent task");
24212            assert_eq!(commands.len(), 1);
24213            assert_eq!(commands[0]["type"], "complete_workflow");
24214            assert!(!commands
24215                .iter()
24216                .any(|command| command["type"] == "start_child_workflow"));
24217            let output =
24218                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
24219            assert_eq!(output["parent_workflow_id"], "wf-parent");
24220            assert_eq!(output["parent_run_id"], "run-parent");
24221            assert_eq!(output["child_workflow_id"], "wf-child");
24222            assert_eq!(output["child_run_id"], "run-child");
24223            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
24224        }
24225    }
24226
24227    #[test]
24228    fn typed_child_arguments_and_results_survive_replay() {
24229        let client = Client::new("http://127.0.0.1:8080").expect("client");
24230        let mut worker = Worker::new(client, "rust-parent-workers");
24231        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
24232            let child = ctx
24233                .start_child_workflow_avro_value(
24234                    "python.typed-child",
24235                    ChildWorkflowOptions::new("python-workers"),
24236                    AvroValue::Array(vec![typed_fidelity_probe()]),
24237                )
24238                .await?;
24239            Ok(child.result)
24240        });
24241
24242        let initial = worker
24243            .execute_workflow_task(workflow_task(
24244                "rust.typed-parent",
24245                Vec::new(),
24246                DEFAULT_CODEC,
24247            ))
24248            .expect("typed child start");
24249        assert_eq!(initial[0]["type"], "start_child_workflow");
24250        assert_eq!(
24251            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
24252                .expect("typed child arguments"),
24253            AvroValue::Array(vec![typed_fidelity_probe()])
24254        );
24255
24256        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
24257            .expect("typed child result");
24258        let task = workflow_task(
24259            "rust.typed-parent",
24260            vec![
24261                history_event(
24262                    "ChildWorkflowScheduled",
24263                    json!({
24264                        "sequence": 1,
24265                        "child_call_id": "call-typed",
24266                        "child_workflow_instance_id": "wf-child",
24267                        "child_workflow_run_id": "run-child",
24268                        "child_workflow_type": "python.typed-child",
24269                    }),
24270                ),
24271                history_event(
24272                    "ChildRunCompleted",
24273                    json!({
24274                        "sequence": 1,
24275                        "child_call_id": "call-typed",
24276                        "child_workflow_instance_id": "wf-child",
24277                        "child_workflow_run_id": "run-child",
24278                        "child_workflow_type": "python.typed-child",
24279                        "payload_codec": DEFAULT_CODEC,
24280                        "result": result,
24281                    }),
24282                ),
24283            ],
24284            DEFAULT_CODEC,
24285        );
24286
24287        let commands = worker
24288            .execute_workflow_task(task)
24289            .expect("typed child replay");
24290        assert_eq!(commands[0]["type"], "complete_workflow");
24291        assert_eq!(
24292            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
24293                .expect("typed parent result"),
24294            typed_fidelity_probe()
24295        );
24296    }
24297
24298    #[test]
24299    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
24300        let worker = child_parent_worker();
24301        let mut task = child_parent_task("unused", Value::Null);
24302        task.history_events.truncate(1);
24303        task.total_history_events = Some(1);
24304
24305        for _redelivery_or_restart in 0..2 {
24306            let commands = worker
24307                .execute_workflow_task(task.clone())
24308                .expect("recorded child remains pending");
24309            assert!(
24310                commands.is_empty(),
24311                "recorded pending child must not be started again"
24312            );
24313        }
24314    }
24315
24316    #[test]
24317    fn child_cancellation_becomes_stable_parent_failure_command() {
24318        let worker = child_parent_worker();
24319        let task = child_parent_task(
24320            "ChildRunCancelled",
24321            json!({
24322                "sequence": 1,
24323                "child_workflow_instance_id": "wf-child",
24324                "child_workflow_run_id": "run-child",
24325                "child_workflow_type": "python.child",
24326                "failure_id": "failure-child",
24327                "failure_category": "cancelled",
24328                "message": "cancelled by parent-close policy",
24329            }),
24330        );
24331
24332        let commands = worker
24333            .execute_workflow_task(task)
24334            .expect("parent settlement");
24335        assert_eq!(commands.len(), 1);
24336        assert_eq!(commands[0]["type"], "fail_workflow");
24337        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
24338        assert_eq!(
24339            commands[0]["exception"]["properties"]["reason"],
24340            "cancelled"
24341        );
24342        assert_eq!(
24343            commands[0]["exception"]["properties"]["child_workflow_run_id"],
24344            "run-child"
24345        );
24346    }
24347
24348    #[test]
24349    fn workflow_can_handle_typed_child_failure() {
24350        let client = Client::new("http://127.0.0.1:8080").expect("client");
24351        let mut worker = Worker::new(client, "rust-parent-workers");
24352        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
24353            match ctx
24354                .start_child_workflow(
24355                    "python.child",
24356                    ChildWorkflowOptions::new("python-child-workers"),
24357                    json!([]),
24358                )
24359                .await
24360            {
24361                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
24362                    "reason": failure.reason,
24363                    "failure_id": failure.failure_id,
24364                    "exception_class": failure.exception_class,
24365                    "child_run_id": failure.child_workflow_run_id,
24366                })),
24367                Err(error) => Err(error),
24368                Ok(_) => Err(Error::WorkerLoop(
24369                    "child unexpectedly succeeded".to_string(),
24370                )),
24371            }
24372        });
24373        let mut task = child_parent_task(
24374            "ChildRunFailed",
24375            json!({
24376                "sequence": 1,
24377                "child_workflow_instance_id": "wf-child",
24378                "child_workflow_run_id": "run-child",
24379                "child_workflow_type": "python.child",
24380                "failure_id": "failure-child",
24381                "failure_category": "child_workflow",
24382                "message": "payment rejected",
24383                "exception": {
24384                    "type": "PaymentRejected",
24385                    "class": "payments.PaymentRejected",
24386                    "message": "payment rejected"
24387                }
24388            }),
24389        );
24390        task.workflow_type = "rust.handled-parent".to_string();
24391        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
24392
24393        let commands = worker.execute_workflow_task(task).expect("handled failure");
24394        assert_eq!(commands[0]["type"], "complete_workflow");
24395        let output =
24396            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
24397        assert_eq!(output["reason"], "child_workflow");
24398        assert_eq!(output["failure_id"], "failure-child");
24399        assert_eq!(output["exception_class"], "payments.PaymentRejected");
24400        assert_eq!(output["child_run_id"], "run-child");
24401    }
24402
24403    #[test]
24404    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
24405        let client = Client::new("http://127.0.0.1:8080").expect("client");
24406        let mut worker = Worker::new(client, "rust-workers");
24407
24408        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
24409            let signal = ctx.wait_signal("start").await?;
24410            let name = signal
24411                .first()
24412                .and_then(|value| value.as_str())
24413                .unwrap_or("world");
24414            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
24415            Ok(json!({
24416                "greeting": greeting,
24417                "language": "rust"
24418            }))
24419        });
24420
24421        let signal_arguments =
24422            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
24423        let task = WorkflowTask {
24424            task_id: "wft-rust-signal-1".to_string(),
24425            workflow_command_id: None,
24426            workflow_id: Some("wf-rust-hello".to_string()),
24427            run_id: Some("run-rust-hello".to_string()),
24428            workflow_type: "rust.hello_workflow".to_string(),
24429            cancel_requested: false,
24430            payload_codec: DEFAULT_CODEC.to_string(),
24431            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24432            history_events: vec![HistoryEvent {
24433                event_type: "SignalReceived".to_string(),
24434                payload: json!({
24435                    "signal_id": "sig-rust-1",
24436                    "signal_name": "start"
24437                }),
24438                raw: HashMap::new(),
24439            }],
24440            total_history_events: Some(1),
24441            history_size_bytes: None,
24442            continue_as_new_recommended: None,
24443            history_budget_pressure: None,
24444            next_history_page_token: None,
24445            workflow_task_attempt: 1,
24446            workflow_signal_id: Some("sig-rust-1".to_string()),
24447            signal_name: Some("start".to_string()),
24448            signal_arguments: Some(signal_arguments),
24449            workflow_update_id: None,
24450            update_name: None,
24451            lease_owner: Some("rust-worker".to_string()),
24452        };
24453
24454        let commands = worker.execute_workflow_task(task).expect("workflow task");
24455
24456        assert_eq!(commands.len(), 1);
24457        assert_eq!(commands[0]["type"], "schedule_activity");
24458        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
24459        assert_eq!(
24460            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
24461            json!(["Rust"])
24462        );
24463    }
24464
24465    #[test]
24466    fn workflow_task_appends_paginated_history_events() {
24467        let mut task = WorkflowTask {
24468            task_id: "wft-rust-pages-1".to_string(),
24469            workflow_command_id: None,
24470            workflow_id: Some("wf-rust-pages".to_string()),
24471            run_id: Some("run-rust-pages".to_string()),
24472            workflow_type: "rust.hello_workflow".to_string(),
24473            cancel_requested: false,
24474            payload_codec: DEFAULT_CODEC.to_string(),
24475            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24476            history_events: vec![HistoryEvent {
24477                event_type: "WorkflowStarted".to_string(),
24478                payload: json!({}),
24479                raw: HashMap::new(),
24480            }],
24481            total_history_events: Some(3),
24482            history_size_bytes: None,
24483            continue_as_new_recommended: None,
24484            history_budget_pressure: None,
24485            next_history_page_token: Some("MQ==".to_string()),
24486            workflow_task_attempt: 1,
24487            workflow_signal_id: None,
24488            signal_name: None,
24489            signal_arguments: None,
24490            workflow_update_id: None,
24491            update_name: None,
24492            lease_owner: Some("rust-worker".to_string()),
24493        };
24494
24495        task.append_history_page(WorkflowTaskHistoryPage {
24496            history_events: vec![
24497                HistoryEvent {
24498                    event_type: "SignalReceived".to_string(),
24499                    payload: json!({
24500                        "signal_id": "sig-rust-1",
24501                        "signal_name": "start",
24502                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
24503                            .expect("signal arguments")
24504                    }),
24505                    raw: HashMap::new(),
24506                },
24507                HistoryEvent {
24508                    event_type: "MarkerRecorded".to_string(),
24509                    payload: json!({"sequence": 3}),
24510                    raw: HashMap::new(),
24511                },
24512            ],
24513            total_history_events: Some(3),
24514            next_history_page_token: None,
24515        });
24516
24517        assert_eq!(task.history_events.len(), 3);
24518        assert_eq!(task.total_history_events, Some(3));
24519        assert_eq!(task.next_history_page_token, None);
24520
24521        let signal = task
24522            .history_events
24523            .iter()
24524            .find(|event| event.event_type == "SignalReceived")
24525            .expect("signal event");
24526        assert_eq!(
24527            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
24528            vec![AvroValue::String("Rust".to_string())]
24529        );
24530    }
24531
24532    #[tokio::test]
24533    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
24534        let client = Client::new("http://127.0.0.1:8080").expect("client");
24535        let mut worker = Worker::new(client, "rust-workers");
24536        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24537        worker.register_query("counter", "current", |ctx, _args| async move {
24538            let mut count = 0_i64;
24539            for signal in ctx.signal_events() {
24540                let value = signal
24541                    .arguments
24542                    .first()
24543                    .and_then(Value::as_i64)
24544                    .unwrap_or_default();
24545                match signal.name.as_str() {
24546                    "increment" => count += value,
24547                    "set" => count = value,
24548                    _ => {}
24549                }
24550            }
24551            Ok(json!(count))
24552        });
24553
24554        let task = QueryTask {
24555            query_task_id: "query-rust-counter".to_string(),
24556            query_task_attempt: 1,
24557            lease_owner: Some("rust-worker".to_string()),
24558            workflow_id: Some("counter-1".to_string()),
24559            run_id: Some("run-counter-1".to_string()),
24560            workflow_type: "counter".to_string(),
24561            query_name: "current".to_string(),
24562            payload_codec: DEFAULT_CODEC.to_string(),
24563            workflow_arguments: Some(
24564                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24565            ),
24566            query_arguments: Some(
24567                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
24568            ),
24569            history_events: vec![
24570                HistoryEvent {
24571                    event_type: "SignalReceived".to_string(),
24572                    payload: json!({
24573                        "signal_id": "php-signal-1",
24574                        "signal_name": "increment",
24575                        "workflow_sequence": 1,
24576                        "payload_codec": DEFAULT_CODEC,
24577                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
24578                    }),
24579                    raw: HashMap::new(),
24580                },
24581                HistoryEvent {
24582                    event_type: "SignalReceived".to_string(),
24583                    payload: json!({
24584                        "signal_id": "python-signal-2",
24585                        "signal_name": "increment",
24586                        "workflow_sequence": 2,
24587                        "payload_codec": DEFAULT_CODEC,
24588                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
24589                    }),
24590                    raw: HashMap::new(),
24591                },
24592                HistoryEvent {
24593                    event_type: "SignalReceived".to_string(),
24594                    payload: json!({
24595                        "signal_id": "rust-signal-3",
24596                        "signal_name": "set",
24597                        "workflow_sequence": 3,
24598                        "payload_codec": DEFAULT_CODEC,
24599                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
24600                    }),
24601                    raw: HashMap::new(),
24602                },
24603            ],
24604            history_export: None,
24605            run_status: Some("completed".to_string()),
24606        };
24607
24608        let result = worker.execute_query_task(task).await.expect("query result");
24609        assert_eq!(result.into_json().expect("query projection"), json!(0));
24610    }
24611
24612    #[tokio::test]
24613    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
24614        let worker = replay_counter_worker();
24615        let running_history = json!([
24616            {
24617                "type": "ActivityCompleted",
24618                "payload": {
24619                    "sequence": 1,
24620                    "activity_type": "load-counter",
24621                    "payload_codec": DEFAULT_CODEC,
24622                    "result": fixture_envelope(json!("loaded"))
24623                }
24624            },
24625            {
24626                "type": "SignalWaitOpened",
24627                "payload": {
24628                    "sequence": 3,
24629                    "signal_name": "increment"
24630                }
24631            },
24632            {
24633                "type": "SignalReceived",
24634                "payload": {
24635                    "signal_id": "signal-3",
24636                    "signal_name": "increment",
24637                    "workflow_sequence": 2,
24638                    "payload_codec": DEFAULT_CODEC,
24639                    "arguments": fixture_envelope(json!([3]))
24640                }
24641            },
24642            {
24643                "type": "SignalApplied",
24644                "payload": {
24645                    "sequence": 3,
24646                    "signal_id": "signal-3",
24647                    "signal_name": "increment",
24648                    "payload_codec": DEFAULT_CODEC,
24649                    "value": fixture_envelope(json!([3]))
24650                }
24651            }
24652        ]);
24653
24654        let running = worker
24655            .execute_query_task(replay_counter_query(
24656                "current",
24657                running_history.clone(),
24658                "running",
24659            ))
24660            .await
24661            .expect("running replay query");
24662        assert_eq!(
24663            running.clone().into_json().expect("query projection"),
24664            json!({"loaded": "loaded", "count": 3, "finished": false})
24665        );
24666
24667        let detached = worker
24668            .execute_query_task(replay_counter_query(
24669                "detached-mutation",
24670                running_history.clone(),
24671                "running",
24672            ))
24673            .await
24674            .expect("query mutates only its detached state clone");
24675        assert_eq!(detached.into_json().expect("query projection"), json!(999));
24676        let failed = worker
24677            .execute_query_task(replay_counter_query(
24678                "failed-mutation",
24679                running_history.clone(),
24680                "running",
24681            ))
24682            .await
24683            .expect_err("failed query");
24684        assert_eq!(failed.reason, "query_rejected");
24685        let unchanged = worker
24686            .execute_query_task(replay_counter_query("current", running_history, "running"))
24687            .await
24688            .expect("later query reconstructs unchanged state");
24689        assert_eq!(unchanged, running);
24690
24691        let restarted_worker = replay_counter_worker();
24692        let empty_arguments = fixture_envelope(json!([]));
24693        let loaded_result = fixture_envelope(json!("loaded"));
24694        let signal_three = fixture_blob(json!([3]));
24695        let signal_five = fixture_blob(json!([5]));
24696        let restarted_task: QueryTask = serde_json::from_value(json!({
24697            "query_task_id": "query-after-restart",
24698            "workflow_id": "counter-1",
24699            "run_id": "run-counter-1",
24700            "workflow_type": "replay-counter",
24701            "query_name": "current",
24702            "payload_codec": DEFAULT_CODEC,
24703            "workflow_arguments": empty_arguments.clone(),
24704            "query_arguments": empty_arguments,
24705            "history_events": [],
24706            "history_export": {
24707                "payloads": {"codec": DEFAULT_CODEC},
24708                "history_events": [
24709                    {
24710                        "type": "ActivityCompleted",
24711                        "payload": {
24712                            "sequence": 1,
24713                            "activity_type": "load-counter",
24714                            "payload_codec": DEFAULT_CODEC,
24715                            "result": null
24716                        }
24717                    },
24718                    {
24719                        "type": "SignalWaitOpened",
24720                        "payload": {
24721                            "sequence": 3,
24722                            "signal_name": "increment"
24723                        }
24724                    },
24725                    {
24726                        "type": "SignalReceived",
24727                        "payload": {
24728                            "signal_id": "signal-3",
24729                            "signal_name": "increment",
24730                            "workflow_sequence": 2
24731                        }
24732                    },
24733                    {
24734                        "type": "SignalApplied",
24735                        "payload": {
24736                            "sequence": 3,
24737                            "signal_id": "signal-3",
24738                            "signal_name": "increment"
24739                        }
24740                    },
24741                    {
24742                        "type": "SignalWaitOpened",
24743                        "payload": {
24744                            "sequence": 5,
24745                            "signal_name": "increment"
24746                        }
24747                    },
24748                    {
24749                        "type": "SignalReceived",
24750                        "payload": {
24751                            "signal_id": "signal-5",
24752                            "signal_name": "increment",
24753                            "workflow_sequence": 4
24754                        }
24755                    },
24756                    {
24757                        "type": "SignalApplied",
24758                        "payload": {
24759                            "sequence": 5,
24760                            "signal_id": "signal-5",
24761                            "signal_name": "increment"
24762                        }
24763                    }
24764                ],
24765                "activities": [{
24766                    "sequence": 1,
24767                    "activity_type": "load-counter",
24768                    "payload_codec": DEFAULT_CODEC,
24769                    "result": loaded_result
24770                }],
24771                "signals": [
24772                    {
24773                        "id": "signal-3",
24774                        "name": "increment",
24775                        "workflow_sequence": 2,
24776                        "payload_codec": DEFAULT_CODEC,
24777                        "arguments": signal_three
24778                    },
24779                    {
24780                        "id": "signal-5",
24781                        "name": "increment",
24782                        "workflow_sequence": 4,
24783                        "payload_codec": DEFAULT_CODEC,
24784                        "arguments": signal_five
24785                    }
24786                ]
24787            },
24788            "run_status": "completed"
24789        }))
24790        .expect("cold replay query task");
24791        let completed = restarted_worker
24792            .execute_query_task(restarted_task)
24793            .await
24794            .expect("completed cold replay query");
24795        assert_eq!(
24796            completed.into_json().expect("query projection"),
24797            json!({"loaded": "loaded", "count": 8, "finished": true})
24798        );
24799    }
24800
24801    #[tokio::test]
24802    async fn replayed_query_replay_failures_are_machine_readable() {
24803        let worker = replay_counter_worker();
24804        let task = replay_counter_query(
24805            "current",
24806            json!([{
24807                "type": "ActivityCompleted",
24808                "payload": {
24809                    "sequence": 1,
24810                    "payload_codec": DEFAULT_CODEC,
24811                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
24812                }
24813            }]),
24814            "running",
24815        );
24816        let failure = worker
24817            .execute_query_task(task)
24818            .await
24819            .expect_err("invalid replay history payload");
24820        assert_eq!(failure.reason, "query_payload_decode_failed");
24821        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
24822        assert!(failure.message.contains("invalid_payload_framing"));
24823    }
24824
24825    #[tokio::test]
24826    async fn query_task_restores_compact_history_from_export() {
24827        let client = Client::new("http://127.0.0.1:8080").expect("client");
24828        let mut worker = Worker::new(client, "rust-workers");
24829        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24830        worker.register_query("counter", "current", |ctx, _args| async move {
24831            Ok(json!(ctx.signals("increment")[0][0]))
24832        });
24833        let empty_arguments = fixture_envelope(json!([]));
24834        let exported_signal = fixture_blob(json!([9]));
24835        let task: QueryTask = serde_json::from_value(json!({
24836            "query_task_id": "query-export",
24837            "workflow_type": "counter",
24838            "query_name": "current",
24839            "payload_codec": DEFAULT_CODEC,
24840            "workflow_arguments": empty_arguments.clone(),
24841            "query_arguments": empty_arguments,
24842            "history_events": [],
24843            "history_export": {
24844                "payloads": {"codec": DEFAULT_CODEC},
24845                "history_events": [{
24846                    "type": "SignalReceived",
24847                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
24848                }],
24849                "signals": [{
24850                    "id": "signal-export",
24851                    "name": "increment",
24852                    "status": "applied",
24853                    "workflow_sequence": 1,
24854                    "payload_codec": DEFAULT_CODEC,
24855                    "arguments": exported_signal
24856                }]
24857            }
24858        }))
24859        .expect("query task");
24860
24861        let result = worker.execute_query_task(task).await.expect("query result");
24862        assert_eq!(result.into_json().expect("query projection"), json!(9));
24863    }
24864
24865    #[tokio::test]
24866    async fn query_task_failures_have_stable_reasons() {
24867        let client = Client::new("http://127.0.0.1:8080").expect("client");
24868        let mut worker = Worker::new(client, "rust-workers");
24869        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24870        worker.register_query(
24871            "counter",
24872            "current",
24873            |_ctx, _args| async move { Ok(json!(0)) },
24874        );
24875
24876        let base_task = QueryTask {
24877            query_task_id: "query-errors".to_string(),
24878            query_task_attempt: 1,
24879            lease_owner: None,
24880            workflow_id: Some("counter-errors".to_string()),
24881            run_id: Some("run-errors".to_string()),
24882            workflow_type: "counter".to_string(),
24883            query_name: "missing".to_string(),
24884            payload_codec: DEFAULT_CODEC.to_string(),
24885            workflow_arguments: Some(fixture_envelope(json!([]))),
24886            query_arguments: Some(fixture_envelope(json!([]))),
24887            history_events: Vec::new(),
24888            history_export: None,
24889            run_status: Some("running".to_string()),
24890        };
24891
24892        let unknown = worker
24893            .execute_query_task(base_task.clone())
24894            .await
24895            .expect_err("unknown query");
24896        assert_eq!(unknown.reason, "rejected_unknown_query");
24897
24898        let mut malformed = base_task;
24899        malformed.query_name = "current".to_string();
24900        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
24901        let malformed = worker
24902            .execute_query_task(malformed)
24903            .await
24904            .expect_err("malformed payload");
24905        assert_eq!(malformed.reason, "query_payload_decode_failed");
24906
24907        let client = Client::new("http://127.0.0.1:8080").expect("client");
24908        let mut unavailable_worker = Worker::new(client, "rust-workers");
24909        unavailable_worker
24910            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
24911        let empty_arguments = fixture_envelope(json!([]));
24912        let unavailable_task: QueryTask = serde_json::from_value(json!({
24913            "query_task_id": "query-unavailable",
24914            "workflow_type": "counter",
24915            "query_name": "current",
24916            "payload_codec": DEFAULT_CODEC,
24917            "workflow_arguments": empty_arguments.clone(),
24918            "query_arguments": empty_arguments
24919        }))
24920        .expect("query task");
24921        let unavailable = unavailable_worker
24922            .execute_query_task(unavailable_task)
24923            .await
24924            .expect_err("query handler unavailable");
24925        assert_eq!(unavailable.reason, "query_handler_unavailable");
24926    }
24927
24928    #[tokio::test]
24929    async fn client_query_decodes_result_and_typed_failure() {
24930        let server = MockWorkerServer::start();
24931        let client = Client::builder(server.base_url())
24932            .timeout(Duration::from_secs(2))
24933            .build()
24934            .expect("client");
24935
24936        let result = client
24937            .query_workflow("counter-1", "current", json!([]))
24938            .await
24939            .expect("query result");
24940        assert_eq!(result, json!({"count": 8}));
24941
24942        let error = client
24943            .query_workflow("counter-1", "missing", json!([]))
24944            .await
24945            .expect_err("unknown query");
24946        let Error::QueryFailed(failure) = error else {
24947            panic!("expected typed query failure");
24948        };
24949        assert_eq!(failure.status, 404);
24950        assert_eq!(failure.reason, "rejected_unknown_query");
24951    }
24952
24953    #[tokio::test]
24954    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
24955        let server = MockWorkerServer::start();
24956        let client = Client::builder(server.base_url())
24957            .timeout(Duration::from_secs(2))
24958            .build()
24959            .expect("client");
24960        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
24961
24962        client
24963            .start_workflow(
24964                "typed.echo",
24965                "rust-workers",
24966                "typed-start",
24967                arguments.clone(),
24968            )
24969            .await
24970            .expect("typed workflow start");
24971        assert_eq!(
24972            decode_wire_avro_value(
24973                &server.request_body("/api/workflows")["input"],
24974                DEFAULT_CODEC,
24975            )
24976            .expect("typed start input"),
24977            arguments
24978        );
24979
24980        client
24981            .signal_workflow("typed-1", "changed", arguments.clone())
24982            .await
24983            .expect("typed signal");
24984        assert_eq!(
24985            decode_wire_avro_value(
24986                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
24987                DEFAULT_CODEC,
24988            )
24989            .expect("typed signal input"),
24990            arguments
24991        );
24992
24993        assert_eq!(
24994            client
24995                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
24996                .await
24997                .expect("typed query"),
24998            typed_fidelity_probe()
24999        );
25000        assert_eq!(
25001            decode_wire_avro_value(
25002                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
25003                DEFAULT_CODEC,
25004            )
25005            .expect("typed query input"),
25006            arguments
25007        );
25008
25009        assert_eq!(
25010            client
25011                .update_workflow_avro_value(
25012                    "typed-1",
25013                    "replace",
25014                    arguments.clone(),
25015                    Some("typed-request"),
25016                )
25017                .await
25018                .expect("typed update"),
25019            typed_fidelity_probe()
25020        );
25021        let update = server.request_body("/api/workflows/typed-1/update/replace");
25022        assert_eq!(update["request_id"], "typed-request");
25023        assert_eq!(
25024            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
25025            arguments
25026        );
25027
25028        let handle = WorkflowHandle {
25029            client: client.clone(),
25030            workflow_id: "typed-1".to_string(),
25031            run_id: Some("run-typed-1".to_string()),
25032            workflow_type: "typed.echo".to_string(),
25033        };
25034        assert_eq!(
25035            handle
25036                .result_avro_value(WorkflowResultOptions::default())
25037                .await
25038                .expect("typed workflow result"),
25039            typed_fidelity_probe()
25040        );
25041
25042        client
25043            .complete_activity_task(
25044                "activity-typed",
25045                "attempt-typed",
25046                "rust-worker",
25047                typed_fidelity_probe(),
25048                DEFAULT_CODEC,
25049            )
25050            .await
25051            .expect("typed activity completion");
25052        assert_eq!(
25053            decode_wire_avro_value(
25054                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
25055                    ["result"],
25056                DEFAULT_CODEC,
25057            )
25058            .expect("typed activity result"),
25059            typed_fidelity_probe()
25060        );
25061        client
25062            .fail_activity_task(
25063                "activity-typed",
25064                "attempt-typed",
25065                "rust-worker",
25066                "typed failure",
25067                true,
25068            )
25069            .await
25070            .expect("activity failure");
25071    }
25072
25073    #[tokio::test]
25074    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
25075        let server = MockWorkerServer::start();
25076        let client = Client::builder(server.base_url())
25077            .timeout(Duration::from_secs(2))
25078            .build()
25079            .expect("client");
25080
25081        let options = WorkflowCommandOptions::new()
25082            .reason("cleanup requested")
25083            .request_id("cancel-17");
25084        let cancelled = client
25085            .cancel_workflow("wf-lifecycle", options)
25086            .await
25087            .expect("instance cancellation");
25088        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
25089        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
25090        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
25091        assert_eq!(
25092            server.request_body("/api/workflows/wf-lifecycle/cancel"),
25093            json!({"reason":"cleanup requested","request_id":"cancel-17"})
25094        );
25095
25096        let terminated = client
25097            .terminate_workflow(
25098                "wf-lifecycle",
25099                WorkflowCommandOptions::new().reason("forced stop"),
25100            )
25101            .await
25102            .expect("instance termination");
25103        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
25104        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
25105
25106        client
25107            .cancel_workflow_run(
25108                "wf-lifecycle",
25109                "run-current",
25110                WorkflowCommandOptions::default(),
25111            )
25112            .await
25113            .expect("selected run cancellation");
25114        client
25115            .terminate_workflow_run(
25116                "wf-lifecycle",
25117                "run-current",
25118                WorkflowCommandOptions::default(),
25119            )
25120            .await
25121            .expect("selected run termination");
25122
25123        for (command, error) in [
25124            (
25125                WorkflowCommandKind::Cancel,
25126                client
25127                    .cancel_workflow_run(
25128                        "wf-lifecycle",
25129                        "run-stale",
25130                        WorkflowCommandOptions::default(),
25131                    )
25132                    .await
25133                    .expect_err("stale cancellation must be rejected"),
25134            ),
25135            (
25136                WorkflowCommandKind::Terminate,
25137                client
25138                    .terminate_workflow_run(
25139                        "wf-lifecycle",
25140                        "run-stale",
25141                        WorkflowCommandOptions::default(),
25142                    )
25143                    .await
25144                    .expect_err("stale termination must be rejected"),
25145            ),
25146        ] {
25147            let Error::WorkflowCommandRejected(rejection) = error else {
25148                panic!("expected typed command rejection");
25149            };
25150            assert_eq!(rejection.command, command);
25151            assert_eq!(rejection.status, 409);
25152            assert_eq!(rejection.reason, "historical_run_command_rejected");
25153            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
25154            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
25155        }
25156    }
25157
25158    #[tokio::test]
25159    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
25160        let server = MockWorkerServer::start();
25161        let client = Client::builder(server.base_url())
25162            .timeout(Duration::from_secs(2))
25163            .build()
25164            .expect("client");
25165
25166        let result = client
25167            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
25168            .await
25169            .expect("redrive accepted");
25170        assert_eq!(result.workflow_id, "wf-lifecycle");
25171        assert_eq!(result.source_run_id, "run-failed");
25172        assert_eq!(result.run_id, "run-successor");
25173        assert_eq!(result.resume_step_sequence, 2);
25174        assert_eq!(
25175            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
25176            json!({"request_id":"retry-1"})
25177        );
25178
25179        let repeated = client
25180            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
25181            .await
25182            .expect("idempotent redrive response accepted");
25183        assert_eq!(repeated.run_id, "run-successor");
25184
25185        let error = client
25186            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
25187            .await
25188            .expect_err("completed run must be rejected");
25189        let Error::Http { status, body } = error else {
25190            panic!("expected HTTP redrive rejection");
25191        };
25192        assert_eq!(status.as_u16(), 409);
25193        assert!(body.contains("run_not_failed"));
25194        assert_eq!(
25195            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
25196            json!({})
25197        );
25198
25199        let handle = WorkflowHandle {
25200            client: client.clone(),
25201            workflow_id: "wf-lifecycle".to_string(),
25202            run_id: Some("run-failed".to_string()),
25203            workflow_type: "test".to_string(),
25204        };
25205        assert_eq!(
25206            handle.redrive(None).await.expect("handle redrive").run_id,
25207            "run-successor"
25208        );
25209        let missing_run = WorkflowHandle {
25210            run_id: None,
25211            ..handle
25212        };
25213        assert!(matches!(
25214            missing_run.redrive(None).await,
25215            Err(Error::Codec(_))
25216        ));
25217    }
25218
25219    #[tokio::test]
25220    async fn workflow_start_options_send_server_enforced_deadlines() {
25221        let server = MockWorkerServer::start();
25222        let client = Client::builder(server.base_url())
25223            .timeout(Duration::from_secs(2))
25224            .build()
25225            .expect("client");
25226
25227        let handle = client
25228            .start_workflow_with_options(
25229                "rust.timeout",
25230                "rust-timeouts",
25231                "wf-start-options",
25232                WorkflowStartOptions::new()
25233                    .execution_timeout_seconds(30)
25234                    .run_timeout_seconds(1),
25235                json!([]),
25236            )
25237            .await
25238            .expect("workflow start");
25239
25240        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
25241        let body = server.request_body("/api/workflows");
25242        assert_eq!(body["execution_timeout_seconds"], 30);
25243        assert_eq!(body["run_timeout_seconds"], 1);
25244
25245        let invalid = client
25246            .start_workflow_with_options(
25247                "rust.timeout",
25248                "rust-timeouts",
25249                "wf-invalid-options",
25250                WorkflowStartOptions::new()
25251                    .execution_timeout_seconds(1)
25252                    .run_timeout_seconds(2),
25253                json!([]),
25254            )
25255            .await
25256            .expect_err("invalid deadline ordering");
25257        assert!(invalid
25258            .to_string()
25259            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
25260    }
25261
25262    #[tokio::test]
25263    async fn workflow_result_returns_each_typed_terminal_outcome() {
25264        let server = MockWorkerServer::start();
25265        let client = Client::builder(server.base_url())
25266            .timeout(Duration::from_secs(2))
25267            .build()
25268            .expect("client");
25269        let options = WorkflowResultOptions {
25270            poll_interval: Duration::ZERO,
25271            timeout: Duration::from_secs(1),
25272        };
25273
25274        let failed = WorkflowHandle {
25275            client: client.clone(),
25276            workflow_id: "wf-failed".to_string(),
25277            run_id: Some("run-failed".to_string()),
25278            workflow_type: "failure".to_string(),
25279        }
25280        .result(options)
25281        .await
25282        .expect_err("failed outcome");
25283        let Error::WorkflowFailed(failure) = failed else {
25284            panic!("expected WorkflowFailed");
25285        };
25286        assert_eq!(failure.workflow_id, "wf-failed");
25287        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
25288        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
25289        assert_eq!(failure.failure_category.as_deref(), Some("application"));
25290        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
25291        assert_eq!(
25292            failure.exception_class.as_deref(),
25293            Some("billing::PaymentError")
25294        );
25295        assert_eq!(failure.non_retryable, Some(true));
25296
25297        for (workflow_id, expected_kind, expected_reason) in [
25298            (
25299                "wf-cancelled",
25300                WorkflowTerminalKind::Cancelled,
25301                "cleanup requested",
25302            ),
25303            (
25304                "wf-terminated",
25305                WorkflowTerminalKind::Terminated,
25306                "forced stop",
25307            ),
25308            (
25309                "wf-timed-out",
25310                WorkflowTerminalKind::TimedOut,
25311                "run_timeout",
25312            ),
25313        ] {
25314            let error = WorkflowHandle {
25315                client: client.clone(),
25316                workflow_id: workflow_id.to_string(),
25317                run_id: None,
25318                workflow_type: "terminal".to_string(),
25319            }
25320            .result(options)
25321            .await
25322            .expect_err("typed terminal outcome");
25323            let outcome = match error {
25324                Error::WorkflowCancelled(outcome) => outcome,
25325                Error::WorkflowTerminated(outcome) => outcome,
25326                Error::WorkflowTimedOut(outcome) => outcome,
25327                other => panic!("unexpected terminal error: {other}"),
25328            };
25329            assert_eq!(outcome.kind, expected_kind);
25330            assert_eq!(outcome.workflow_id, workflow_id);
25331            assert_eq!(outcome.reason, expected_reason);
25332        }
25333
25334        let wait_timeout = WorkflowHandle {
25335            client,
25336            workflow_id: "wf-waiting".to_string(),
25337            run_id: Some("run-waiting".to_string()),
25338            workflow_type: "waiting".to_string(),
25339        }
25340        .result(WorkflowResultOptions {
25341            poll_interval: Duration::ZERO,
25342            timeout: Duration::ZERO,
25343        })
25344        .await
25345        .expect_err("client wait timeout");
25346        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
25347            panic!("expected typed client timeout");
25348        };
25349        assert_eq!(timeout.reason, "result_wait_timeout");
25350        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
25351        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
25352    }
25353
25354    #[tokio::test]
25355    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
25356        let server = MockWorkerServer::start();
25357        let client = Client::builder(server.base_url())
25358            .timeout(Duration::from_secs(2))
25359            .build()
25360            .expect("client");
25361
25362        let handle = WorkflowHandle {
25363            client,
25364            workflow_id: "wf-selected".to_string(),
25365            run_id: Some("run-selected".to_string()),
25366            workflow_type: "selected".to_string(),
25367        };
25368        let options = WorkflowResultOptions {
25369            poll_interval: Duration::ZERO,
25370            timeout: Duration::from_secs(1),
25371        };
25372
25373        let current = handle
25374            .result(options)
25375            .await
25376            .expect("instance result follows the current run");
25377        assert_eq!(current, json!("current run output"));
25378
25379        let error = handle
25380            .result_selected_run(options)
25381            .await
25382            .expect_err("the selected run is cancelled even though the current run completed");
25383
25384        let Error::WorkflowCancelled(outcome) = error else {
25385            panic!("expected selected run cancellation");
25386        };
25387        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
25388        assert_eq!(outcome.reason, "selected run cancelled");
25389        assert_eq!(
25390            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
25391            1
25392        );
25393        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
25394    }
25395
25396    #[tokio::test]
25397    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
25398        let server = MockWorkerServer::draining_polls();
25399        let client = Client::builder(server.base_url())
25400            .timeout(Duration::from_secs(2))
25401            .build()
25402            .expect("client");
25403
25404        let workflow = client
25405            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
25406            .await
25407            .expect("workflow drain response");
25408        let activity = client
25409            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
25410            .await
25411            .expect("activity drain response");
25412        let query = client
25413            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
25414            .await
25415            .expect("query drain response");
25416
25417        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
25418            assert_eq!(
25419                outcome,
25420                WorkerPollOutcome::Stop {
25421                    poll_status: Some("draining".to_string()),
25422                    reason: Some("worker_draining".to_string()),
25423                }
25424            );
25425        }
25426
25427        assert!(client
25428            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
25429            .await
25430            .expect("compatibility poll")
25431            .is_none());
25432    }
25433
25434    #[tokio::test]
25435    async fn managed_worker_honors_drain_stop_for_every_task_family() {
25436        let server = MockWorkerServer::draining_polls();
25437        let client = Client::builder(server.base_url())
25438            .timeout(Duration::from_secs(2))
25439            .build()
25440            .expect("client");
25441
25442        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
25443            .worker_id("draining-workflow-worker")
25444            .poll_timeout(Duration::ZERO);
25445        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
25446        workflow_worker
25447            .run()
25448            .await
25449            .expect("workflow drain is a clean stop");
25450
25451        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
25452            .worker_id("draining-activity-worker")
25453            .poll_timeout(Duration::ZERO);
25454        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
25455        activity_worker
25456            .run()
25457            .await
25458            .expect("activity drain is a clean stop");
25459
25460        let mut query_worker = Worker::new(client, "rust-workers")
25461            .worker_id("draining-query-worker")
25462            .poll_timeout(Duration::ZERO);
25463        query_worker.register_query("counter", "current", |_ctx, _args| async {
25464            Ok(Value::Null)
25465        });
25466        query_worker
25467            .run()
25468            .await
25469            .expect("query drain is a clean stop");
25470    }
25471
25472    #[tokio::test]
25473    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
25474        let server = MockWorkerServer::start();
25475        let client = Client::builder(server.base_url())
25476            .timeout(Duration::from_secs(2))
25477            .build()
25478            .expect("client");
25479
25480        let heartbeat = client
25481            .heartbeat_activity_task(
25482                "activity-cancel",
25483                "attempt-cancel",
25484                "rust-worker",
25485                typed_fidelity_probe(),
25486            )
25487            .await
25488            .expect("cancellation heartbeat");
25489        assert!(heartbeat.cancel_requested);
25490        assert!(heartbeat.should_stop());
25491        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
25492        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
25493        let heartbeat_body =
25494            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
25495        assert_eq!(heartbeat_body["details"]["codec"], DEFAULT_CODEC);
25496        assert_eq!(
25497            decode_wire_avro_value(&heartbeat_body["details"], DEFAULT_CODEC)
25498                .expect("typed heartbeat details"),
25499            typed_fidelity_probe()
25500        );
25501
25502        let error = client
25503            .complete_activity_task(
25504                "activity-cancel",
25505                "attempt-cancel",
25506                "rust-worker",
25507                json!({"late":true}),
25508                DEFAULT_CODEC,
25509            )
25510            .await
25511            .expect_err("late completion must be refused");
25512        assert!(activity_task_rejection_is_final(&error));
25513        let Error::ActivityTaskRejected(rejection) = error else {
25514            panic!("expected typed activity rejection");
25515        };
25516        assert_eq!(rejection.status, 409);
25517        assert_eq!(rejection.reason, "run_cancelled");
25518        assert!(rejection.cancel_requested);
25519        assert_eq!(rejection.can_continue, Some(false));
25520    }
25521
25522    #[tokio::test]
25523    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
25524        let server = MockWorkerServer::cancelled_activity();
25525        let client = Client::builder(server.base_url())
25526            .timeout(Duration::from_secs(2))
25527            .build()
25528            .expect("client");
25529        let cancellation_observed = Arc::new(AtomicBool::new(false));
25530        let observed = Arc::clone(&cancellation_observed);
25531        let mut worker = Worker::new(client.clone(), "rust-workers")
25532            .worker_id("rust-cancel-worker")
25533            .poll_timeout(Duration::from_millis(10));
25534        worker.register_activity("cancel-aware", move |ctx, _args| {
25535            let observed = Arc::clone(&observed);
25536            async move {
25537                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
25538                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
25539                Ok(json!({"late":"completion"}))
25540            }
25541        });
25542
25543        assert_eq!(
25544            worker.run_once().await.expect("cancelled attempt handled"),
25545            1
25546        );
25547        assert!(cancellation_observed.load(Ordering::SeqCst));
25548        assert_eq!(
25549            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
25550            1
25551        );
25552
25553        let mut restarted = Worker::new(client, "rust-workers")
25554            .worker_id("rust-cancel-worker-restarted")
25555            .poll_timeout(Duration::from_millis(10));
25556        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
25557        assert_eq!(
25558            restarted
25559                .run_once()
25560                .await
25561                .expect("replacement worker continues polling"),
25562            0
25563        );
25564    }
25565
25566    #[tokio::test]
25567    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
25568        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"}"#;
25569        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
25570        let client = Client::builder(server.base_url())
25571            .timeout(Duration::from_secs(2))
25572            .build()
25573            .expect("client");
25574
25575        let direct_error = client
25576            .complete_workflow_task(
25577                "workflow-timeout-task",
25578                "timeout-worker",
25579                3,
25580                vec![json!({
25581                    "type": "complete_workflow",
25582                    "result": fixture_envelope(Value::Null)
25583                })],
25584            )
25585            .await
25586            .expect_err("the low-level client preserves the completion rejection");
25587        let Error::Http { status, body } = direct_error else {
25588            panic!("expected the original HTTP completion rejection");
25589        };
25590        assert_eq!(status, reqwest::StatusCode::CONFLICT);
25591        assert_eq!(
25592            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
25593            "run_timed_out"
25594        );
25595
25596        let mut worker = Worker::new(client, "rust-workers")
25597            .worker_id("timeout-worker")
25598            .poll_timeout(Duration::from_millis(10));
25599        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
25600            Ok(json!({"late": "result"}))
25601        });
25602
25603        assert_eq!(
25604            worker
25605                .run_once()
25606                .await
25607                .expect("authoritative selected-run timeout settles the tick"),
25608            1
25609        );
25610        assert_eq!(
25611            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
25612            2,
25613            "both the direct client proof and managed worker must see the rejection"
25614        );
25615    }
25616
25617    #[tokio::test]
25618    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
25619        for (name, status, response) in [
25620            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
25621            (
25622                "command was recorded",
25623                "409 Conflict",
25624                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25625            ),
25626            (
25627                "lease conflict",
25628                "409 Conflict",
25629                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
25630            ),
25631            (
25632                "nonterminal run",
25633                "409 Conflict",
25634                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
25635            ),
25636            (
25637                "different selected run",
25638                "409 Conflict",
25639                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"}"#,
25640            ),
25641            (
25642                "different task attempt",
25643                "409 Conflict",
25644                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25645            ),
25646            (
25647                "authentication failure",
25648                "401 Unauthorized",
25649                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25650            ),
25651            (
25652                "authorization failure",
25653                "403 Forbidden",
25654                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25655            ),
25656            (
25657                "protocol failure",
25658                "400 Bad Request",
25659                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
25660            ),
25661            (
25662                "malformed command",
25663                "422 Unprocessable Entity",
25664                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25665            ),
25666            (
25667                "transient server failure",
25668                "503 Service Unavailable",
25669                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
25670            ),
25671        ] {
25672            let server = MockWorkerServer::workflow_completion(status, response);
25673            let client = Client::builder(server.base_url())
25674                .timeout(Duration::from_secs(2))
25675                .build()
25676                .expect("client");
25677            let mut worker = Worker::new(client, "rust-workers")
25678                .worker_id("timeout-worker")
25679                .poll_timeout(Duration::from_millis(10));
25680            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
25681                Ok(json!({"late": "result"}))
25682            });
25683
25684            let error = worker
25685                .run_once()
25686                .await
25687                .expect_err(&format!("{name} must remain an error"));
25688            assert!(
25689                matches!(error, Error::Http { .. } | Error::Protocol(_)),
25690                "{name} returned an unexpected error variant: {error}"
25691            );
25692        }
25693    }
25694
25695    #[tokio::test]
25696    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
25697        let server = MockWorkerServer::start();
25698        let client = Client::builder(server.base_url())
25699            .worker_token(Some("worker-secret".to_string()))
25700            .namespace("orders")
25701            .timeout(Duration::from_secs(2))
25702            .build()
25703            .expect("client");
25704        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
25705
25706        let result = client
25707            .deregister_worker_registration("worker/α space")
25708            .await
25709            .expect("deregister worker registration");
25710
25711        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
25712        assert_eq!(
25713            server.worker_protocol_for(path).as_deref(),
25714            Some(WORKER_PROTOCOL_VERSION)
25715        );
25716        assert_eq!(server.control_protocol_for(path), None);
25717        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
25718        assert_eq!(
25719            server.authorization_for(path).as_deref(),
25720            Some("Bearer worker-secret")
25721        );
25722        assert_eq!(
25723            result,
25724            WorkerDeregistrationEnvelope {
25725                worker_id: "deregistered-worker".to_string(),
25726                outcome: "deregistered".to_string(),
25727                recovered_workflow_task_count: 2,
25728            }
25729        );
25730    }
25731
25732    #[tokio::test]
25733    async fn low_level_registration_rejects_update_validators_before_transport() {
25734        let server = MockWorkerServer::start();
25735        let client = Client::builder(server.base_url())
25736            .timeout(Duration::from_secs(2))
25737            .build()
25738            .expect("client");
25739
25740        for update_validators in [json!(["approve"]), json!("approve")] {
25741            let error = client
25742                .register_worker_with_command_contracts(
25743                    "validator-claiming-worker",
25744                    "rust-workers",
25745                    vec!["orders".to_string()],
25746                    vec![],
25747                    1,
25748                    1,
25749                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
25750                    json!({
25751                        "orders": {
25752                            "queries": ["current"],
25753                            "updates": ["approve"],
25754                            "update_validators": update_validators,
25755                        },
25756                    }),
25757                )
25758                .await
25759                .expect_err("unsupported validator claims must fail before registration");
25760
25761            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
25762                panic!("expected typed unsupported-validator failure");
25763            };
25764            assert_eq!(workflow_type, "orders");
25765        }
25766        assert_eq!(server.request_count("/api/worker/register"), 0);
25767    }
25768
25769    #[tokio::test]
25770    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
25771        let server = MockWorkerServer::start();
25772        let client = Client::builder(server.base_url())
25773            .timeout(Duration::from_secs(2))
25774            .build()
25775            .expect("client");
25776        let mut worker = Worker::new(client, "rust-workers");
25777        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
25778        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
25779        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
25780        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
25781        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
25782        worker
25783            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
25784            .expect("declare workflow signals");
25785
25786        worker.register().await.expect("register handler contracts");
25787
25788        let declaration =
25789            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
25790        let expected_contracts = json!([
25791            {
25792                "name": "a-avro",
25793                "parameters": [{
25794                    "name": "args", "position": 0, "required": false,
25795                    "variadic": true, "type": null, "allows_null": true,
25796                    "default_available": false, "default": null,
25797                }],
25798            },
25799            {
25800                "name": "z-json",
25801                "parameters": [{
25802                    "name": "args", "position": 0, "required": false,
25803                    "variadic": true, "type": null, "allows_null": true,
25804                    "default_available": false, "default": null,
25805                }],
25806            },
25807        ]);
25808        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
25809        assert_eq!(declaration["query_contracts"], expected_contracts);
25810        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
25811        assert_eq!(declaration["update_contracts"], expected_contracts);
25812        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
25813        assert_eq!(declaration["signal_contracts"], expected_contracts);
25814        assert_eq!(declaration["update_validators"], json!([]));
25815    }
25816
25817    #[tokio::test]
25818    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
25819        let server = MockWorkerServer::start();
25820        let client = Client::new(server.base_url()).expect("client");
25821        let mut worker = Worker::new(client, "rust-workers");
25822        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
25823        assert!(worker
25824            .declare_workflow_signals("missing", &["finish"])
25825            .is_err());
25826        worker
25827            .declare_workflow_signals("orders", &["finish"])
25828            .unwrap();
25829        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
25830            assert!(worker.declare_workflow_signals("orders", names).is_err());
25831        }
25832        worker.register().await.unwrap();
25833        assert_eq!(
25834            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
25835                ["signals"],
25836            json!(["finish"])
25837        );
25838        worker.declare_workflow_signals("orders", &[]).unwrap();
25839        worker.register().await.unwrap();
25840        let registrations = server.request_bodies("/api/worker/register");
25841        assert_eq!(
25842            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
25843            json!([])
25844        );
25845        assert_eq!(
25846            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
25847            json!([])
25848        );
25849    }
25850
25851    #[tokio::test]
25852    async fn low_level_registration_preserves_query_and_update_contracts() {
25853        let server = MockWorkerServer::start();
25854        let client = Client::builder(server.base_url())
25855            .timeout(Duration::from_secs(2))
25856            .build()
25857            .expect("client");
25858        let contracts = json!({
25859            "orders": {
25860                "queries": ["current"],
25861                "updates": ["approve"],
25862                "update_validators": [],
25863            },
25864            "payments": {
25865                "queries": ["status"],
25866                "updates": ["capture"],
25867            },
25868        });
25869
25870        client
25871            .register_worker_with_command_contracts(
25872                "command-worker",
25873                "rust-workers",
25874                vec!["orders".to_string(), "payments".to_string()],
25875                vec![],
25876                1,
25877                1,
25878                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
25879                contracts.clone(),
25880            )
25881            .await
25882            .expect("query and update contracts must remain supported");
25883
25884        assert_eq!(
25885            server.request_body("/api/worker/register")["workflow_command_contracts"],
25886            contracts
25887        );
25888        assert!(server
25889            .request_body("/api/worker/register")
25890            .get("workflow_definition_fingerprints")
25891            .is_none());
25892    }
25893
25894    #[tokio::test]
25895    async fn rust_worker_advertises_source_backed_definition_and_clears_it_on_reregistration() {
25896        let server = MockWorkerServer::start();
25897        let client = Client::builder(server.base_url())
25898            .timeout(Duration::from_secs(2))
25899            .build()
25900            .expect("client");
25901        let mut worker = Worker::new(client, "rust-workers");
25902        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
25903
25904        assert!(worker
25905            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
25906            .is_err());
25907        assert!(worker
25908            .set_workflow_definition_sources("orders", &[])
25909            .is_err());
25910        worker
25911            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
25912            .expect("embed workflow source");
25913        worker.register().await.expect("register worker");
25914        let first = server.request_bodies("/api/worker/register")[0]
25915            ["workflow_definition_fingerprints"]["orders"]
25916            .as_str()
25917            .expect("source-backed fingerprint")
25918            .to_string();
25919        assert!(first.starts_with("sha256:"));
25920
25921        worker
25922            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
25923            .expect("change embedded helper source");
25924        worker.register().await.expect("register changed source");
25925        let changed = server.request_bodies("/api/worker/register")[1]
25926            ["workflow_definition_fingerprints"]["orders"]
25927            .as_str()
25928            .expect("changed fingerprint")
25929            .to_string();
25930        assert_ne!(first, changed);
25931
25932        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
25933        worker
25934            .register()
25935            .await
25936            .expect("register replacement handler");
25937        assert_eq!(
25938            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
25939            json!({})
25940        );
25941    }
25942
25943    #[tokio::test]
25944    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
25945        let server = MockWorkerServer::start();
25946        let control_only = Client::builder(server.base_url())
25947            .control_token(Some("control-secret".to_string()))
25948            .build()
25949            .expect("control client");
25950
25951        let error = control_only
25952            .register_worker("worker", "queue", vec![], vec![], 1, 1)
25953            .await
25954            .expect_err("control token must not authorize a worker request");
25955        assert!(matches!(
25956            error,
25957            Error::MissingRoleCredentials { role: "worker", .. }
25958        ));
25959        assert_eq!(server.request_count("/api/worker/register"), 0);
25960
25961        let worker_only = Client::builder(server.base_url())
25962            .worker_token(Some("worker-secret".to_string()))
25963            .build()
25964            .expect("worker client");
25965        let error = worker_only
25966            .health()
25967            .await
25968            .expect_err("worker token must not authorize a control request");
25969        assert!(matches!(
25970            error,
25971            Error::MissingRoleCredentials {
25972                role: "control",
25973                ..
25974            }
25975        ));
25976        assert_eq!(server.request_count("/api/health"), 0);
25977    }
25978
25979    #[tokio::test]
25980    async fn shared_token_supports_worker_and_control_planes() {
25981        let server = MockWorkerServer::start();
25982        let client = Client::builder(server.base_url())
25983            .token(Some("shared-secret".to_string()))
25984            .build()
25985            .expect("client");
25986
25987        client.health().await.expect("control request");
25988        client
25989            .register_worker("worker", "queue", vec![], vec![], 1, 1)
25990            .await
25991            .expect("worker request");
25992
25993        assert_eq!(
25994            server.authorization_for("/api/health").as_deref(),
25995            Some("Bearer shared-secret")
25996        );
25997        assert_eq!(
25998            server.control_protocol_for("/api/health").as_deref(),
25999            Some(CONTROL_PLANE_VERSION)
26000        );
26001        assert_eq!(
26002            server.authorization_for("/api/worker/register").as_deref(),
26003            Some("Bearer shared-secret")
26004        );
26005        assert_eq!(
26006            server
26007                .worker_protocol_for("/api/worker/register")
26008                .as_deref(),
26009            Some(WORKER_PROTOCOL_VERSION)
26010        );
26011    }
26012
26013    #[tokio::test]
26014    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
26015        let server = MockWorkerServer::start();
26016        let client = Client::builder(server.base_url())
26017            .timeout(Duration::from_secs(2))
26018            .build()
26019            .expect("client");
26020
26021        client
26022            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
26023            .await
26024            .expect("register");
26025        client
26026            .heartbeat_worker("capture-worker", 1, 1)
26027            .await
26028            .expect("heartbeat");
26029        client
26030            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
26031            .await
26032            .expect("workflow poll");
26033        client
26034            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
26035            .await
26036            .expect("activity poll");
26037
26038        for path in [
26039            "/api/worker/register",
26040            "/api/worker/heartbeat",
26041            "/api/worker/workflow-tasks/poll",
26042            "/api/worker/activity-tasks/poll",
26043        ] {
26044            assert_eq!(
26045                server.worker_protocol_for(path).as_deref(),
26046                Some(WORKER_PROTOCOL_VERSION),
26047                "unexpected protocol for {path}"
26048            );
26049        }
26050
26051        assert_eq!(
26052            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
26053            1
26054        );
26055        assert_eq!(
26056            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
26057            500
26058        );
26059        assert_eq!(
26060            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
26061            1
26062        );
26063        assert!(
26064            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
26065                .as_str()
26066                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
26067        );
26068        assert!(
26069            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
26070                .as_str()
26071                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
26072        );
26073    }
26074
26075    #[tokio::test]
26076    async fn query_task_endpoints_send_the_query_feature_protocol() {
26077        let server = MockWorkerServer::start();
26078        let client = Client::builder(server.base_url())
26079            .timeout(Duration::from_secs(2))
26080            .build()
26081            .expect("client");
26082
26083        client
26084            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26085            .await
26086            .expect("query poll");
26087        client
26088            .complete_query_task(
26089                "query-capture",
26090                "capture-worker",
26091                1,
26092                json!(8),
26093                DEFAULT_CODEC,
26094            )
26095            .await
26096            .expect("query complete");
26097        client
26098            .fail_query_task(
26099                "query-capture",
26100                "capture-worker",
26101                1,
26102                "failed",
26103                "query_rejected",
26104                "QueryFailed",
26105            )
26106            .await
26107            .expect("query fail");
26108
26109        for path in [
26110            "/api/worker/query-tasks/poll",
26111            "/api/worker/query-tasks/query-capture/complete",
26112            "/api/worker/query-tasks/query-capture/fail",
26113        ] {
26114            assert_eq!(
26115                server.worker_protocol_for(path).as_deref(),
26116                Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
26117                "unexpected protocol for {path}"
26118            );
26119        }
26120
26121        assert_eq!(
26122            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
26123            1
26124        );
26125        assert!(
26126            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
26127                .as_str()
26128                .is_some_and(|id| id.starts_with("rust-query-poll-"))
26129        );
26130    }
26131
26132    #[tokio::test]
26133    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
26134        let server = MockWorkerServer::transient_worker_failures();
26135        let client = Client::builder(server.base_url())
26136            .timeout(Duration::from_secs(2))
26137            .build()
26138            .expect("client");
26139
26140        client
26141            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
26142            .await
26143            .expect("workflow poll retry");
26144        client
26145            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
26146            .await
26147            .expect("activity poll retry");
26148        client
26149            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26150            .await
26151            .expect("query poll retry");
26152
26153        for path in [
26154            "/api/worker/workflow-tasks/poll",
26155            "/api/worker/activity-tasks/poll",
26156            "/api/worker/query-tasks/poll",
26157        ] {
26158            let bodies = server.request_bodies(path);
26159            assert_eq!(bodies.len(), 2, "{path} must be retried once");
26160            assert_eq!(
26161                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
26162                "{path} must preserve the request binding across retry"
26163            );
26164        }
26165    }
26166
26167    #[tokio::test]
26168    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
26169        let server = MockWorkerServer::consecutive_poll_failures(2);
26170        let client = Client::builder(server.base_url())
26171            .timeout(Duration::from_secs(2))
26172            .build()
26173            .expect("client");
26174        let mut worker = Worker::new(client, "capture")
26175            .worker_id("capture-worker")
26176            .poll_timeout(Duration::from_millis(10))
26177            .retry_policy(WorkerRetryPolicy {
26178                max_retries: 2,
26179                initial_backoff: Duration::from_millis(1),
26180                max_backoff: Duration::from_millis(1),
26181            });
26182        worker.register_workflow(
26183            "capture.workflow",
26184            |_ctx, _input| async move { Ok(Value::Null) },
26185        );
26186        worker.register_activity(
26187            "capture.activity",
26188            |_ctx, _input| async move { Ok(Value::Null) },
26189        );
26190        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
26191            Ok(Value::Null)
26192        });
26193
26194        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
26195
26196        for path in [
26197            "/api/worker/workflow-tasks/poll",
26198            "/api/worker/activity-tasks/poll",
26199            "/api/worker/query-tasks/poll",
26200        ] {
26201            let bodies = server.request_bodies(path);
26202            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
26203            assert!(
26204                bodies
26205                    .iter()
26206                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
26207                "{path} must preserve one request binding across every retry"
26208            );
26209        }
26210    }
26211
26212    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
26213        let reason = if unavailable {
26214            "storage_admission_unavailable"
26215        } else {
26216            "storage_pressure"
26217        };
26218        let mut body = json!({
26219            "reason": reason,
26220            "storage_state": if unavailable { "fenced" } else { "draining" },
26221            "retryable": true,
26222            "retry_after_seconds": 1,
26223        });
26224        if !mid_poll {
26225            body["request_admitted"] = json!(false);
26226        }
26227        if let Some(id) = poll_id {
26228            body["task"] = Value::Null;
26229            body["poll_status"] = json!(reason);
26230            body["poll_request_id"] = json!(id);
26231            body["retry_same_poll_request_id"] = json!(true);
26232            body["claim_admitted"] = json!(false);
26233        }
26234        body
26235    }
26236
26237    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
26238        let operation = match path {
26239            "/api/worker/register" => "register_worker",
26240            "/api/worker/heartbeat" => "heartbeat_worker",
26241            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
26242            "/api/worker/activity-tasks/poll" => "poll_activity_task",
26243            "/api/worker/query-tasks/poll" => "poll_query_task",
26244            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
26245            _ => return None,
26246        };
26247        let request: Value = serde_json::from_str(request).ok()?;
26248        let mut response = json!({
26249            "reason": "backend_unavailable",
26250            "operation": operation,
26251            "outcome": "unknown",
26252            "retryable": true,
26253            "retry_after_seconds": 1,
26254            "worker_id": request["worker_id"],
26255            "task_queue": request.get("task_queue"),
26256        });
26257        if path.ends_with("/poll") {
26258            response["task"] = Value::Null;
26259            response["poll_status"] = json!("backend_unavailable");
26260            response["poll_request_id"] = request["poll_request_id"].clone();
26261            response["retry_same_poll_request_id"] = json!(true);
26262        }
26263        Some(response)
26264    }
26265
26266    fn backend_retry_override(
26267        path: &str,
26268        request: &str,
26269        number: usize,
26270    ) -> Option<(&'static str, String)> {
26271        if number > 8 {
26272            return None;
26273        }
26274        Some((
26275            "503 Service Unavailable",
26276            backend_refusal(path, request)?.to_string(),
26277        ))
26278    }
26279
26280    fn backend_unavailable_override(
26281        path: &str,
26282        request: &str,
26283        _number: usize,
26284    ) -> Option<(&'static str, String)> {
26285        Some((
26286            "503 Service Unavailable",
26287            backend_refusal(path, request)?.to_string(),
26288        ))
26289    }
26290
26291    fn storage_worker(server: &MockWorkerServer) -> Worker {
26292        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
26293            .worker_id("storage-worker")
26294            .retry_policy(WorkerRetryPolicy {
26295                max_retries: 1,
26296                initial_backoff: Duration::from_millis(1),
26297                max_backoff: Duration::from_millis(1),
26298            })
26299    }
26300
26301    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
26302        let requests = server.requests.lock().expect("requests");
26303        let bodies: Vec<_> = requests
26304            .iter()
26305            .filter(|request| request.path == path)
26306            .map(|request| &request.body)
26307            .collect();
26308        assert_eq!(bodies.len(), count, "{path}");
26309        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
26310    }
26311
26312    #[test]
26313    fn backend_recovery_requires_the_explicit_worker_contract() {
26314        for (path, operation) in [
26315            ("/worker/register", "register_worker"),
26316            ("/worker/heartbeat", "heartbeat_worker"),
26317            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
26318            ("/worker/activity-tasks/poll", "poll_activity_task"),
26319            ("/worker/query-tasks/poll", "poll_query_task"),
26320            (
26321                "/worker/update-validation-tasks/poll",
26322                "poll_update_validation_task",
26323            ),
26324        ] {
26325            let poll_id = path.ends_with("/poll").then_some("same-poll");
26326            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
26327            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
26328                .expect("worker operation");
26329            assert_eq!(body["operation"], operation);
26330            let error = Error::Http {
26331                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26332                body: body.to_string(),
26333            };
26334            assert_eq!(
26335                worker_backend_unavailable_retry_after(&error, path, poll_id),
26336                Some(Duration::from_secs(1))
26337            );
26338            assert!(!worker_operation_is_retryable(&error));
26339            for (field, value) in [
26340                ("operation", json!("wrong_operation")),
26341                ("outcome", json!("completed")),
26342                ("retryable", json!(false)),
26343                ("retry_after_seconds", json!(0)),
26344                ("worker_id", json!("")),
26345            ] {
26346                let mut invalid = body.clone();
26347                invalid[field] = value;
26348                let error = Error::Http {
26349                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26350                    body: invalid.to_string(),
26351                };
26352                assert!(
26353                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
26354                    "{path}: {field}"
26355                );
26356                assert!(!worker_operation_is_retryable(&error));
26357            }
26358            if let Some(poll_id) = poll_id {
26359                for (field, value) in [
26360                    ("poll_request_id", json!("wrong-poll")),
26361                    ("poll_status", json!("empty")),
26362                    ("task", json!({"task_id":"claimed"})),
26363                    ("retry_same_poll_request_id", json!(false)),
26364                ] {
26365                    let mut invalid = body.clone();
26366                    invalid[field] = value;
26367                    let error = Error::Http {
26368                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26369                        body: invalid.to_string(),
26370                    };
26371                    assert!(
26372                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
26373                            .is_none(),
26374                        "{path}: {field}"
26375                    );
26376                }
26377            }
26378            let error = Error::Http {
26379                status: reqwest::StatusCode::UNAUTHORIZED,
26380                body: body.to_string(),
26381            };
26382            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
26383            assert!(!worker_operation_is_retryable(&error));
26384        }
26385    }
26386
26387    #[tokio::test]
26388    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
26389        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26390            request_override: Some(backend_retry_override),
26391            ..MockWorkerBehavior::default()
26392        });
26393        let mut worker =
26394            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26395        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
26396        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
26397        worker.register_query("backend.workflow", "state", |_, _| async {
26398            Ok(Value::Null)
26399        });
26400        worker.register().await.expect("registration recovery");
26401        worker
26402            .client
26403            .heartbeat_worker("storage-worker", 1, 1)
26404            .await
26405            .expect("heartbeat recovery");
26406        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
26407        for path in [
26408            "/api/worker/register",
26409            "/api/worker/heartbeat",
26410            "/api/worker/workflow-tasks/poll",
26411            "/api/worker/activity-tasks/poll",
26412            "/api/worker/query-tasks/poll",
26413        ] {
26414            assert_identical_requests(&server, path, 9);
26415        }
26416    }
26417
26418    #[tokio::test]
26419    async fn backend_recovery_wait_stops_with_worker() {
26420        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26421            request_override: Some(backend_unavailable_override),
26422            ..MockWorkerBehavior::default()
26423        });
26424        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
26425            max_retries: 1,
26426            initial_backoff: Duration::from_secs(2),
26427            max_backoff: Duration::from_secs(2),
26428        });
26429        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
26430        let started = tokio::time::Instant::now();
26431        let _ = tokio::time::timeout(
26432            Duration::from_secs(1),
26433            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
26434        )
26435        .await
26436        .expect("shutdown interrupts backend wait");
26437        assert!(started.elapsed() < Duration::from_secs(1));
26438        assert!(server.request_count("/api/worker/register") >= 1);
26439    }
26440
26441    #[test]
26442    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
26443        for unavailable in [false, true] {
26444            for mid_poll in [false, true] {
26445                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
26446                let error = Error::Http {
26447                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26448                    body: body.to_string(),
26449                };
26450                assert_eq!(
26451                    worker_storage_admission_retry_after(&error, Some("same-poll")),
26452                    Some(Duration::from_secs(1))
26453                );
26454                assert!(
26455                    !worker_operation_is_retryable(&error),
26456                    "storage is not a bounded generic retry"
26457                );
26458                for (field, value) in [
26459                    ("poll_request_id", json!("wrong-poll")),
26460                    ("task", json!({"task_id":"claimed"})),
26461                    ("retryable", json!(false)),
26462                    ("retry_after_seconds", json!(0)),
26463                    ("retry_after_seconds", json!(true)),
26464                    ("retry_after_seconds", json!(1.0)),
26465                    ("storage_state", json!("normal")),
26466                    ("poll_status", json!("empty")),
26467                    ("claim_admitted", json!(true)),
26468                    ("retry_same_poll_request_id", json!(false)),
26469                    ("request_admitted", json!(true)),
26470                ] {
26471                    let mut invalid = body.clone();
26472                    invalid[field] = value;
26473                    let error = Error::Http {
26474                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26475                        body: invalid.to_string(),
26476                    };
26477                    assert!(
26478                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
26479                        "{field}"
26480                    );
26481                }
26482            }
26483        }
26484        let body = storage_refusal(None, false, false);
26485        let error = Error::Http {
26486            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26487            body: body.to_string(),
26488        };
26489        assert!(worker_storage_admission_retry_after(&error, None).is_some());
26490        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
26491        let error = Error::Http {
26492            status: reqwest::StatusCode::FORBIDDEN,
26493            body: body.to_string(),
26494        };
26495        assert!(worker_storage_admission_retry_after(&error, None).is_none());
26496        let body = storage_refusal(None, false, true);
26497        let error = Error::Http {
26498            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26499            body: body.to_string(),
26500        };
26501        assert!(worker_storage_admission_retry_after(&error, None).is_none());
26502    }
26503
26504    #[tokio::test]
26505    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
26506        for unavailable in [false, true] {
26507            for mid_poll in [false, true] {
26508                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26509                    poll_failures_per_path: 1,
26510                    storage_refusals: 7,
26511                    storage_path: Some("/poll"),
26512                    storage_unavailable: unavailable,
26513                    storage_mid_poll: mid_poll,
26514                    ..MockWorkerBehavior::default()
26515                });
26516                let mut worker = storage_worker(&server);
26517                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
26518                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
26519                for path in [
26520                    "/api/worker/workflow-tasks/poll",
26521                    "/api/worker/activity-tasks/poll",
26522                    "/api/worker/query-tasks/poll",
26523                ] {
26524                    assert_identical_requests(&server, path, 9);
26525                }
26526            }
26527        }
26528    }
26529
26530    #[tokio::test]
26531    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
26532        struct CountedBody(Arc<AtomicUsize>);
26533        impl Serialize for CountedBody {
26534            fn serialize<S: Serializer>(
26535                &self,
26536                serializer: S,
26537            ) -> std::result::Result<S::Ok, S::Error> {
26538                let count = self.0.fetch_add(1, Ordering::SeqCst);
26539                json!({"serialization":count,"lease_owner":"worker","attempt":7})
26540                    .serialize(serializer)
26541            }
26542        }
26543        for path in [
26544            "/api/worker/register",
26545            "/api/worker/heartbeat",
26546            "/api/worker/workflow-tasks/storage-task/complete",
26547            "/api/worker/workflow-tasks/storage-task/fail",
26548            "/api/worker/activity-tasks/storage-task/complete",
26549            "/api/worker/activity-tasks/storage-task/fail",
26550            "/api/worker/activity-tasks/storage-task/heartbeat",
26551            "/api/worker/query-tasks/storage-task/complete",
26552            "/api/worker/query-tasks/storage-task/fail",
26553        ] {
26554            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26555                storage_refusals: 7,
26556                storage_path: Some(path),
26557                ..MockWorkerBehavior::default()
26558            });
26559            let worker =
26560                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26561            let calls = Arc::new(AtomicUsize::new(0));
26562            let _: Value = worker
26563                .client
26564                .request_json(
26565                    reqwest::Method::POST,
26566                    &path[4..],
26567                    RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
26568                    Some(&CountedBody(Arc::clone(&calls))),
26569                )
26570                .await
26571                .expect("prepared request recovery");
26572            assert_eq!(calls.load(Ordering::SeqCst), 1);
26573            assert_identical_requests(&server, path, 8);
26574        }
26575        for worker_scope in [false, true] {
26576            let path = if worker_scope {
26577                "/api/health"
26578            } else {
26579                "/api/worker/register"
26580            };
26581            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26582                storage_refusals: usize::MAX,
26583                storage_path: Some(path),
26584                ..MockWorkerBehavior::default()
26585            });
26586            let worker = storage_worker(&server);
26587            let client = worker.client.clone();
26588            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
26589            let error = if worker_scope {
26590                worker
26591                    .client
26592                    .health()
26593                    .await
26594                    .expect_err("control plane is not retried")
26595            } else {
26596                client
26597                    .request_json::<Value, Value>(
26598                        reqwest::Method::POST,
26599                        "/worker/register",
26600                        RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
26601                        Some(&json!({})),
26602                    )
26603                    .await
26604                    .expect_err("direct client is not retried")
26605            };
26606            assert!(worker_storage_admission_body(&error).is_some());
26607            assert_eq!(server.request_count(path), 1);
26608        }
26609    }
26610
26611    #[tokio::test]
26612    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
26613        for fail in [false, true] {
26614            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26615                storage_activity: true,
26616                storage_refusals: 7,
26617                storage_path: Some("/storage-activity/"),
26618                ..MockWorkerBehavior::default()
26619            });
26620            let mut worker = storage_worker(&server);
26621            let calls = Arc::new(AtomicUsize::new(0));
26622            let observed = Arc::clone(&calls);
26623            worker.register_activity("storage.activity", move |ctx, _| {
26624                let calls = Arc::clone(&observed);
26625                async move {
26626                    calls.fetch_add(1, Ordering::SeqCst);
26627                    ctx.heartbeat(json!({"step":2})).await?;
26628                    if fail {
26629                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
26630                    } else {
26631                        Ok(json!({"receipt":true}))
26632                    }
26633                }
26634            });
26635            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
26636            assert_eq!(calls.load(Ordering::SeqCst), 1);
26637            assert_identical_requests(
26638                &server,
26639                "/api/worker/activity-tasks/storage-activity/heartbeat",
26640                8,
26641            );
26642            let suffix = if fail { "fail" } else { "complete" };
26643            assert_identical_requests(
26644                &server,
26645                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
26646                8,
26647            );
26648            let other = if fail { "complete" } else { "fail" };
26649            assert_eq!(
26650                server.request_count(&format!(
26651                    "/api/worker/activity-tasks/storage-activity/{other}"
26652                )),
26653                0
26654            );
26655        }
26656    }
26657
26658    #[tokio::test]
26659    async fn storage_waits_are_interruptible_without_false_activity_failure() {
26660        for path in [
26661            "/api/worker/register",
26662            "/api/worker/heartbeat",
26663            "/api/worker/activity-tasks/poll",
26664            "/api/worker/activity-tasks/storage-activity/heartbeat",
26665            "/api/worker/activity-tasks/storage-activity/complete",
26666        ] {
26667            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26668                storage_activity: true,
26669                storage_refusals: usize::MAX,
26670                storage_path: Some(path),
26671                ..MockWorkerBehavior::default()
26672            });
26673            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
26674            worker.register_activity("storage.activity", |ctx, _| async move {
26675                ctx.heartbeat(json!({"step":2})).await?;
26676                Ok(json!({"receipt":true}))
26677            });
26678            let shutdown = async {
26679                while server.request_count(path) == 0 {
26680                    tokio::time::sleep(Duration::from_millis(1)).await;
26681                }
26682            };
26683            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
26684                .await
26685                .expect("shutdown interrupts admission");
26686            assert!(
26687                result.is_err(),
26688                "a refused operation must not appear acknowledged: {path}, {result:?}"
26689            );
26690            assert_eq!(server.request_count(path), 1);
26691            assert_eq!(
26692                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
26693                0
26694            );
26695            assert_eq!(
26696                server.request_count("/api/worker/registrations/mock-worker"),
26697                usize::from(!path.ends_with("/register"))
26698            );
26699        }
26700    }
26701
26702    #[tokio::test]
26703    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
26704        for fail in [false, true] {
26705            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26706                storage_query: true,
26707                storage_refusals: 7,
26708                storage_path: Some("/storage-query/"),
26709                ..MockWorkerBehavior::default()
26710            });
26711            let mut worker = storage_worker(&server);
26712            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
26713            let calls = Arc::new(AtomicUsize::new(0));
26714            let observed = Arc::clone(&calls);
26715            worker.register_query("storage.workflow", "state", move |_, _| {
26716                let calls = Arc::clone(&observed);
26717                async move {
26718                    calls.fetch_add(1, Ordering::SeqCst);
26719                    if fail {
26720                        Err(Error::WorkerLoop("intentional query failure".to_string()))
26721                    } else {
26722                        Ok(json!({"state":"waiting"}))
26723                    }
26724                }
26725            });
26726            assert_eq!(worker.run_once().await.expect("query settled"), 1);
26727            assert_eq!(calls.load(Ordering::SeqCst), 1);
26728            let suffix = if fail { "fail" } else { "complete" };
26729            assert_identical_requests(
26730                &server,
26731                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
26732                8,
26733            );
26734            let other = if fail { "complete" } else { "fail" };
26735            assert_eq!(
26736                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
26737                0
26738            );
26739        }
26740    }
26741
26742    #[tokio::test]
26743    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
26744        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26745            storage_refusals: 7,
26746            storage_path: Some("/poll"),
26747            unauthorized_polls: true,
26748            ..MockWorkerBehavior::default()
26749        });
26750        let error = storage_worker(&server)
26751            .run_once()
26752            .await
26753            .expect_err("auth remains terminal");
26754        assert!(matches!(
26755            error,
26756            Error::Http {
26757                status: reqwest::StatusCode::UNAUTHORIZED,
26758                ..
26759            }
26760        ));
26761        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
26762
26763        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26764            storage_refusals: 7,
26765            storage_path: Some("/activity-cancel/complete"),
26766            ..MockWorkerBehavior::default()
26767        });
26768        let worker =
26769            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
26770        let error = worker
26771            .client
26772            .complete_activity_task(
26773                "activity-cancel",
26774                "attempt-cancel",
26775                "worker",
26776                json!({}),
26777                DEFAULT_CODEC,
26778            )
26779            .await
26780            .expect_err("cancellation remains terminal");
26781        assert!(activity_task_rejection_is_final(&error));
26782        assert_identical_requests(
26783            &server,
26784            "/api/worker/activity-tasks/activity-cancel/complete",
26785            8,
26786        );
26787
26788        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26789            storage_refusals: usize::MAX,
26790            storage_path: Some("/poll"),
26791            storage_wrong_poll_id: true,
26792            ..MockWorkerBehavior::default()
26793        });
26794        assert!(storage_worker(&server).run_once().await.is_err());
26795        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
26796    }
26797
26798    #[tokio::test]
26799    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
26800        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
26801            storage_refusals: usize::MAX,
26802            storage_path: Some("/poll"),
26803            ..MockWorkerBehavior::default()
26804        });
26805        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
26806        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
26807        let run = tokio::spawn(async move { worker.run().await });
26808        tokio::time::timeout(Duration::from_secs(2), async {
26809            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
26810                tokio::time::sleep(Duration::from_millis(1)).await;
26811            }
26812        })
26813        .await
26814        .expect("poll started");
26815        run.abort();
26816        assert!(run.await.expect_err("cancelled run").is_cancelled());
26817        tokio::time::sleep(Duration::from_millis(250)).await;
26818        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
26819    }
26820
26821    #[tokio::test]
26822    async fn query_protocol_rejection_from_older_server_is_typed() {
26823        let server = MockWorkerServer::reject_query_protocol();
26824        let client = Client::builder(server.base_url())
26825            .timeout(Duration::from_secs(2))
26826            .build()
26827            .expect("client");
26828
26829        let error = client
26830            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26831            .await
26832            .expect_err("server below query protocol floor must reject");
26833        let Error::Protocol(failure) = error else {
26834            panic!("expected typed protocol failure");
26835        };
26836
26837        assert_eq!(failure.status, 400);
26838        assert_eq!(failure.reason, "unsupported_protocol_version");
26839        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
26840        assert_eq!(
26841            failure.requested_version.as_deref(),
26842            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
26843        );
26844        assert_eq!(
26845            server
26846                .worker_protocol_for("/api/worker/query-tasks/poll")
26847                .as_deref(),
26848            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
26849        );
26850    }
26851
26852    #[tokio::test]
26853    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
26854        let server = MockWorkerServer::reject_query_protocol();
26855        let client = Client::builder(server.base_url())
26856            .timeout(Duration::from_secs(2))
26857            .build()
26858            .expect("client");
26859        let mut worker = Worker::new(client, "rust-workers")
26860            .worker_id("baseline-worker")
26861            .poll_timeout(Duration::from_millis(10));
26862
26863        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
26864            Ok(Value::Null)
26865        });
26866
26867        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
26868        assert_eq!(
26869            server
26870                .worker_protocol_for("/api/worker/workflow-tasks/poll")
26871                .as_deref(),
26872            Some(WORKER_PROTOCOL_VERSION)
26873        );
26874        assert_eq!(
26875            server.worker_protocol_for("/api/worker/query-tasks/poll"),
26876            None,
26877            "a worker without query handlers must not use the query-task endpoint"
26878        );
26879    }
26880
26881    #[tokio::test]
26882    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
26883        let server = MockWorkerServer::reject_query_completion();
26884        let client = Client::builder(server.base_url())
26885            .timeout(Duration::from_secs(2))
26886            .build()
26887            .expect("client");
26888
26889        let error = client
26890            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
26891            .await
26892            .expect_err("expired completion must be rejected");
26893        let Error::QueryFailed(failure) = error else {
26894            panic!("expected typed query failure");
26895        };
26896        assert_eq!(failure.status, 409);
26897        assert_eq!(failure.reason, "query_task_timed_out");
26898
26899        let mut worker = Worker::new(client, "rust-workers")
26900            .worker_id("late-worker")
26901            .poll_timeout(Duration::from_millis(10));
26902        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26903        worker.register_query(
26904            "counter",
26905            "current",
26906            |_ctx, _args| async move { Ok(json!(8)) },
26907        );
26908
26909        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
26910        assert_eq!(
26911            worker
26912                .run_once()
26913                .await
26914                .expect("worker continues after late completion"),
26915            0
26916        );
26917        assert_eq!(
26918            server.request_count("/api/worker/query-tasks/query-late/complete"),
26919            2
26920        );
26921        assert_eq!(
26922            server.request_count("/api/worker/query-tasks/query-late/fail"),
26923            0,
26924            "a server completion rejection must not be reported as an encoding failure"
26925        );
26926    }
26927
26928    #[tokio::test]
26929    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
26930        let server = MockWorkerServer::start();
26931        let client = Client::builder(server.base_url())
26932            .timeout(Duration::from_secs(2))
26933            .build()
26934            .expect("client");
26935        let mut worker = Worker::new(client, "rust-workers")
26936            .worker_id("joined-worker")
26937            .poll_timeout(Duration::from_millis(10));
26938        worker.register_workflow(
26939            "joined.workflow",
26940            |_ctx, _input| async move { Ok(Value::Null) },
26941        );
26942        worker.register_activity(
26943            "joined.activity",
26944            |_ctx, _input| async move { Ok(Value::Null) },
26945        );
26946        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
26947            Ok(Value::Null)
26948        });
26949
26950        worker
26951            .run_until(tokio::time::sleep(Duration::from_millis(20)))
26952            .await
26953            .expect("normal shutdown");
26954
26955        let deregistration_path = "/api/worker/registrations/mock-worker";
26956        assert_eq!(server.request_count(deregistration_path), 1);
26957        for poll_path in [
26958            "/api/worker/workflow-tasks/poll",
26959            "/api/worker/activity-tasks/poll",
26960            "/api/worker/query-tasks/poll",
26961        ] {
26962            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
26963        }
26964        assert_eq!(
26965            server.captured_paths().last().map(String::as_str),
26966            Some(deregistration_path),
26967            "deregistration must start only after every poller has joined"
26968        );
26969    }
26970
26971    #[tokio::test]
26972    async fn registration_failure_does_not_deregister() {
26973        let server = MockWorkerServer::rejected_registration();
26974        let client = Client::builder(server.base_url())
26975            .timeout(Duration::from_secs(2))
26976            .build()
26977            .expect("client");
26978        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
26979
26980        let error = worker
26981            .run_until(async {})
26982            .await
26983            .expect_err("registration must fail");
26984        assert!(matches!(
26985            error,
26986            Error::Http {
26987                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
26988                ..
26989            }
26990        ));
26991        assert!(server
26992            .captured_paths()
26993            .iter()
26994            .all(|path| !path.starts_with("/api/worker/registrations/")));
26995    }
26996
26997    #[tokio::test]
26998    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
26999        let server = MockWorkerServer::rejected_registration_protocol();
27000        let client = Client::builder(server.base_url())
27001            .timeout(Duration::from_secs(2))
27002            .build()
27003            .expect("client");
27004        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
27005
27006        let error = worker
27007            .run_until(async {})
27008            .await
27009            .expect_err("a protocol 1.16 server must reject this worker");
27010        let Error::Protocol(failure) = error else {
27011            panic!("expected typed protocol rejection");
27012        };
27013        assert_eq!(failure.reason, "unsupported_protocol_version");
27014        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
27015        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
27016        assert_eq!(
27017            server
27018                .worker_protocol_for("/api/worker/register")
27019                .as_deref(),
27020            Some(WORKER_PROTOCOL_VERSION)
27021        );
27022    }
27023
27024    #[tokio::test]
27025    async fn declined_registration_does_not_deregister() {
27026        let server = MockWorkerServer::declined_registration();
27027        let client = Client::builder(server.base_url())
27028            .timeout(Duration::from_secs(2))
27029            .build()
27030            .expect("client");
27031        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
27032
27033        let error = worker
27034            .run_until(async {})
27035            .await
27036            .expect_err("declined registration must fail");
27037        assert!(matches!(error, Error::WorkerLoop(_)));
27038        assert!(error.to_string().contains("was not accepted"));
27039        assert!(server
27040            .captured_paths()
27041            .iter()
27042            .all(|path| !path.starts_with("/api/worker/registrations/")));
27043    }
27044
27045    #[tokio::test]
27046    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
27047        let server = MockWorkerServer::rejected_deregistration();
27048        let client = Client::builder(server.base_url())
27049            .timeout(Duration::from_secs(2))
27050            .build()
27051            .expect("client");
27052        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
27053
27054        let error = worker
27055            .run_until(async {})
27056            .await
27057            .expect_err("deregistration must fail");
27058        assert!(matches!(
27059            error,
27060            Error::Http {
27061                status: reqwest::StatusCode::FORBIDDEN,
27062                ..
27063            }
27064        ));
27065        assert_eq!(
27066            server.request_count("/api/worker/registrations/mock-worker"),
27067            1
27068        );
27069    }
27070
27071    #[tokio::test]
27072    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
27073        let server = MockWorkerServer::rejected_deregistration_protocol();
27074        let client = Client::builder(server.base_url())
27075            .timeout(Duration::from_secs(2))
27076            .build()
27077            .expect("client");
27078        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
27079
27080        let error = worker
27081            .run_until(async {})
27082            .await
27083            .expect_err("protocol rejection must fail shutdown");
27084        let Error::Protocol(failure) = error else {
27085            panic!("expected typed protocol failure");
27086        };
27087        assert_eq!(failure.reason, "unsupported_protocol_version");
27088        assert_eq!(
27089            failure.requested_version.as_deref(),
27090            Some(WORKER_PROTOCOL_VERSION)
27091        );
27092        assert_eq!(
27093            server.request_count("/api/worker/registrations/mock-worker"),
27094            1
27095        );
27096    }
27097
27098    #[tokio::test]
27099    async fn primary_poller_error_retains_deregistration_failure_context() {
27100        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
27101        let client = Client::builder(server.base_url())
27102            .timeout(Duration::from_secs(2))
27103            .build()
27104            .expect("client");
27105        let mut worker = Worker::new(client, "rust-workers")
27106            .worker_id("combined-failure")
27107            .poll_timeout(Duration::from_millis(10));
27108        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
27109            Ok(Value::Null)
27110        });
27111
27112        let error = worker
27113            .run()
27114            .await
27115            .expect_err("worker and cleanup must fail");
27116        let summary = error.to_string();
27117        assert!(summary.contains("authentication_failed"));
27118        assert!(summary.contains("worker cannot deregister"));
27119        let Error::WorkerShutdown {
27120            primary,
27121            deregistration,
27122        } = error
27123        else {
27124            panic!("expected combined worker shutdown error");
27125        };
27126        assert!(matches!(
27127            *primary,
27128            Error::Http {
27129                status: reqwest::StatusCode::UNAUTHORIZED,
27130                ..
27131            }
27132        ));
27133        assert!(matches!(
27134            *deregistration,
27135            Error::Http {
27136                status: reqwest::StatusCode::FORBIDDEN,
27137                ..
27138            }
27139        ));
27140        assert_eq!(
27141            server.request_count("/api/worker/registrations/mock-worker"),
27142            1
27143        );
27144    }
27145
27146    #[tokio::test]
27147    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
27148        let server = MockWorkerServer::start();
27149        let client = Client::builder(server.base_url())
27150            .timeout(Duration::from_secs(2))
27151            .build()
27152            .expect("client");
27153        let mut worker = Worker::new(client, "rust-workers")
27154            .worker_id("activity-only-worker")
27155            .poll_timeout(Duration::from_millis(10));
27156
27157        worker.register_activity(
27158            "activity.only",
27159            |_ctx, _args| async move { Ok(Value::Null) },
27160        );
27161
27162        worker.run_until(async {}).await.expect("run worker");
27163    }
27164
27165    #[tokio::test]
27166    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
27167        let server = MockWorkerServer::start();
27168        let client = Client::builder(server.base_url())
27169            .timeout(Duration::from_secs(2))
27170            .build()
27171            .expect("client");
27172        let mut worker = Worker::new(client, "rust-workers")
27173            .worker_id("workflow-only-worker")
27174            .poll_timeout(Duration::from_millis(10));
27175
27176        worker.register_workflow(
27177            "workflow.only",
27178            |_ctx, _input| async move { Ok(Value::Null) },
27179        );
27180
27181        worker.run_until(async {}).await.expect("run worker");
27182    }
27183
27184    #[tokio::test]
27185    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
27186        let server = MockWorkerServer::start();
27187        let client = Client::builder(server.base_url())
27188            .timeout(Duration::from_secs(2))
27189            .build()
27190            .expect("client");
27191        let observations = Arc::new(Mutex::new(Vec::new()));
27192        let observed = Arc::clone(&observations);
27193        let mut worker = Worker::new(client, "rust-workers")
27194            .worker_id("observed-heartbeat-worker")
27195            .poll_timeout(Duration::from_millis(10))
27196            .on_worker_heartbeat(move |observation| {
27197                observed
27198                    .lock()
27199                    .expect("heartbeat observations")
27200                    .push(observation.clone());
27201            });
27202
27203        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
27204            Ok(Value::Null)
27205        });
27206        let acknowledged = Arc::clone(&observations);
27207        worker
27208            .run_until(async move {
27209                tokio::time::timeout(Duration::from_secs(2), async move {
27210                    loop {
27211                        if !acknowledged
27212                            .lock()
27213                            .expect("heartbeat observations")
27214                            .is_empty()
27215                        {
27216                            break;
27217                        }
27218                        tokio::time::sleep(Duration::from_millis(1)).await;
27219                    }
27220                })
27221                .await
27222                .expect("heartbeat acknowledgement within timeout");
27223            })
27224            .await
27225            .expect("run worker");
27226
27227        let observations = observations.lock().expect("heartbeat observations");
27228        let first = observations.first().expect("heartbeat acknowledgement");
27229        assert_eq!(first.worker_id, "observed-heartbeat-worker");
27230        assert_eq!(first.task_queue, "rust-workers");
27231        assert!(first.acknowledged_at_unix_millis > 0);
27232        assert_eq!(first.acknowledgement, json!({}));
27233    }
27234
27235    #[tokio::test]
27236    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
27237        let server = MockWorkerServer::delayed_heartbeat_worker();
27238        let client = Client::builder(server.base_url())
27239            .timeout(Duration::from_secs(3))
27240            .build()
27241            .expect("client");
27242        let observations = Arc::new(Mutex::new(Vec::new()));
27243        let observed = Arc::clone(&observations);
27244        let mut worker = Worker::new(client, "rust-snapshot-workers")
27245            .worker_id("rust-snapshot-worker")
27246            .poll_timeout(Duration::from_millis(10))
27247            .on_worker_heartbeat(move |observation| {
27248                observed
27249                    .lock()
27250                    .expect("heartbeat observations")
27251                    .push(observation.clone());
27252            });
27253
27254        worker.register_workflow("snapshot", |ctx, _input| async move {
27255            ctx.wait_signal("finish").await?;
27256            Ok(json!({"status": "finished"}))
27257        });
27258        worker.register_query("snapshot", "current", |ctx, _args| async move {
27259            Ok(json!(ctx
27260                .signals("increment")
27261                .iter()
27262                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
27263                .sum::<i64>()))
27264        });
27265        worker.register_activity("cancel-aware", |_ctx, _args| async move {
27266            Ok(json!({"late": "completion"}))
27267        });
27268
27269        worker
27270            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
27271            .await
27272            .expect("delayed heartbeat must allow a clean worker shutdown");
27273
27274        let observations = observations.lock().expect("heartbeat observations");
27275        assert!(
27276            observations.len() >= 3,
27277            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
27278        );
27279        assert!(
27280            observations.windows(2).all(|pair| {
27281                pair[1].acknowledged_at_unix_millis
27282                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
27283                    >= 850
27284            }),
27285            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
27286        );
27287        drop(observations);
27288
27289        let heartbeat_times = server.request_times("/api/worker/heartbeat");
27290        let delayed_request_at = *heartbeat_times
27291            .get(1)
27292            .expect("intentionally delayed heartbeat request");
27293        let delay_window_start = delayed_request_at + Duration::from_millis(100);
27294        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
27295        for path in [
27296            "/api/worker/workflow-tasks/poll",
27297            "/api/worker/activity-tasks/poll",
27298            "/api/worker/query-tasks/poll",
27299        ] {
27300            assert!(
27301                server
27302                    .request_times(path)
27303                    .iter()
27304                    .any(|received_at| *received_at >= delay_window_start
27305                        && *received_at <= delay_window_end),
27306                "{path} must keep polling while a heartbeat acknowledgement is delayed"
27307            );
27308        }
27309        assert!(
27310            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
27311            "workflow work must be settled"
27312        );
27313        assert!(
27314            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
27315            "activity work must be settled"
27316        );
27317        assert!(
27318            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
27319            "query work must be settled"
27320        );
27321    }
27322
27323    #[tokio::test]
27324    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
27325        let server = MockWorkerServer::heartbeat_retry_worker();
27326        let client = Client::builder(server.base_url())
27327            .timeout(Duration::from_secs(2))
27328            .build()
27329            .expect("client");
27330        let observations = Arc::new(Mutex::new(Vec::new()));
27331        let observed = Arc::clone(&observations);
27332        let worker = Worker::new(client, "rust-workers")
27333            .worker_id("heartbeat-retry-worker")
27334            .retry_policy(WorkerRetryPolicy {
27335                max_retries: 1,
27336                initial_backoff: Duration::from_millis(300),
27337                max_backoff: Duration::from_millis(300),
27338            })
27339            .on_worker_heartbeat(move |observation| {
27340                observed
27341                    .lock()
27342                    .expect("heartbeat observations")
27343                    .push(observation.clone());
27344            });
27345
27346        worker
27347            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
27348            .await
27349            .expect("retryable heartbeat failure must remain bounded and recover");
27350
27351        let observations = observations.lock().expect("heartbeat observations");
27352        assert!(observations.len() >= 3, "heartbeat retry must recover");
27353        assert!(
27354            observations.windows(2).all(|pair| {
27355                pair[1]
27356                    .acknowledged_at_unix_millis
27357                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
27358                    >= 850
27359            }),
27360            "a successful retry must start a fresh advertised cadence: {observations:?}"
27361        );
27362        assert_eq!(
27363            server.request_count("/api/worker/heartbeat"),
27364            observations.len() + 1,
27365            "one retryable failure must add exactly one bounded request"
27366        );
27367    }
27368
27369    #[tokio::test]
27370    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
27371        let server = MockWorkerServer::waiting_query_worker();
27372        let client = Client::builder(server.base_url())
27373            .timeout(Duration::from_secs(2))
27374            .build()
27375            .expect("client");
27376        let observations = Arc::new(Mutex::new(Vec::new()));
27377        let observed = Arc::clone(&observations);
27378        let mut worker = Worker::new(client, "rust-snapshot-workers")
27379            .worker_id("rust-snapshot-worker")
27380            .poll_timeout(Duration::from_millis(10))
27381            .on_worker_heartbeat(move |observation| {
27382                observed
27383                    .lock()
27384                    .expect("heartbeat observations")
27385                    .push(observation.clone());
27386            });
27387
27388        worker.register_workflow("snapshot", |ctx, _input| async move {
27389            ctx.wait_signal("finish").await?;
27390            Ok(json!({"status": "finished"}))
27391        });
27392        worker.register_query("snapshot", "current", |ctx, _args| async move {
27393            let current = ctx
27394                .signals("increment")
27395                .iter()
27396                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
27397                .sum::<i64>();
27398            Ok(json!(current))
27399        });
27400        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
27401        worker
27402            .declare_workflow_signals("snapshot", &["finish"])
27403            .expect("declare finish signal");
27404
27405        worker
27406            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
27407            .await
27408            .expect("pending workflow and query poller must remain live until shutdown");
27409
27410        assert!(
27411            observations.lock().expect("heartbeat observations").len() >= 4,
27412            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
27413        );
27414        assert!(
27415            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
27416            "workflow polling must continue after empty replay acknowledgements"
27417        );
27418        assert!(
27419            server.request_count("/api/worker/query-tasks/poll") >= 2,
27420            "query polling must continue after serving the current query"
27421        );
27422        assert_eq!(
27423            server.request_body("/api/worker/register")["capabilities"],
27424            json!([
27425                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
27426                DURABLE_SELECTION_CAPABILITY,
27427                MEMO_UPSERTS_CAPABILITY,
27428                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
27429                QUERY_TASKS_CAPABILITY,
27430                WORKFLOW_UPDATES_CAPABILITY,
27431                MESSAGE_STREAMS_CAPABILITY
27432            ])
27433        );
27434        assert_eq!(
27435            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
27436            json!({
27437                "queries": ["current"],
27438                "query_contracts": [{
27439                    "name": "current",
27440                    "parameters": [{
27441                        "name": "args", "position": 0, "required": false,
27442                        "variadic": true, "type": null, "allows_null": true,
27443                        "default_available": false, "default": null,
27444                    }],
27445                }],
27446                "signals": ["finish"],
27447                "signal_contracts": [{
27448                    "name": "finish",
27449                    "parameters": [{
27450                        "name": "args", "position": 0, "required": false,
27451                        "variadic": true, "type": null, "allows_null": true,
27452                        "default_available": false, "default": null,
27453                    }],
27454                }],
27455                "updates": ["replace"],
27456                "update_contracts": [{
27457                    "name": "replace",
27458                    "parameters": [{
27459                        "name": "args", "position": 0, "required": false,
27460                        "variadic": true, "type": null, "allows_null": true,
27461                        "default_available": false, "default": null,
27462                    }],
27463                }],
27464                "update_validators": [],
27465            })
27466        );
27467
27468        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
27469        assert_eq!(
27470            opened["commands"],
27471            json!([{
27472                "type": "open_signal_wait",
27473                "signal_name": "finish",
27474            }])
27475        );
27476
27477        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
27478            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
27479            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
27480            let failure = server.request_body(&fail_path);
27481            assert_eq!(
27482                failure["failure"]["type"],
27483                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
27484            );
27485            assert_eq!(server.request_count(&completion_path), 0);
27486        }
27487
27488        let query_completion =
27489            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
27490        assert_eq!(query_completion["result"], json!(8));
27491
27492        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
27493        assert_eq!(
27494            server.request_count(terminal_path),
27495            1,
27496            "the matching signal must settle the workflow exactly once"
27497        );
27498        let terminal = server.request_body(terminal_path);
27499        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
27500        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
27501        assert_eq!(
27502            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
27503                .expect("terminal workflow result"),
27504            json!({"status": "finished"})
27505        );
27506    }
27507
27508    #[tokio::test]
27509    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
27510        let server = MockWorkerServer::transient_worker_failures();
27511        let client = Client::builder(server.base_url())
27512            .timeout(Duration::from_secs(2))
27513            .build()
27514            .expect("client");
27515        let mut worker = Worker::new(client, "rust-workers")
27516            .worker_id("retry-worker")
27517            .poll_timeout(Duration::from_millis(10))
27518            .retry_policy(WorkerRetryPolicy {
27519                max_retries: 2,
27520                initial_backoff: Duration::from_millis(1),
27521                max_backoff: Duration::from_millis(1),
27522            });
27523        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27524        worker.register_activity(
27525            "counter.activity",
27526            |_ctx, _input| async move { Ok(Value::Null) },
27527        );
27528        worker.register_query(
27529            "counter",
27530            "current",
27531            |_ctx, _args| async move { Ok(json!(8)) },
27532        );
27533
27534        worker
27535            .run_until(tokio::time::sleep(Duration::from_millis(75)))
27536            .await
27537            .expect("transient failures must not stop the worker");
27538
27539        for path in [
27540            "/api/worker/heartbeat",
27541            "/api/worker/workflow-tasks/poll",
27542            "/api/worker/activity-tasks/poll",
27543            "/api/worker/query-tasks/poll",
27544        ] {
27545            assert!(
27546                server.request_count(path) >= 2,
27547                "{path} must continue after its transient failure"
27548            );
27549        }
27550    }
27551
27552    #[tokio::test]
27553    async fn worker_continues_after_long_poll_capacity_backpressure() {
27554        let server = MockWorkerServer::capacity_limited_activity_poll();
27555        let client = Client::builder(server.base_url())
27556            .timeout(Duration::from_secs(2))
27557            .build()
27558            .expect("client");
27559        let mut worker = Worker::new(client, "rust-workers")
27560            .worker_id("capacity-worker")
27561            .poll_timeout(Duration::from_millis(10))
27562            .retry_policy(WorkerRetryPolicy {
27563                max_retries: 0,
27564                initial_backoff: Duration::from_millis(1),
27565                max_backoff: Duration::from_millis(1),
27566            });
27567        worker.register_activity("capacity.activity", |_ctx, _input| async move {
27568            Ok(json!({"handled": true}))
27569        });
27570
27571        worker
27572            .run_until(tokio::time::sleep(Duration::from_millis(50)))
27573            .await
27574            .expect("capacity backpressure must not stop the worker");
27575
27576        assert!(
27577            server.request_count("/api/worker/activity-tasks/poll") >= 2,
27578            "the activity poller must continue after capacity backpressure"
27579        );
27580        assert_eq!(
27581            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
27582            1,
27583            "the worker must complete work returned after capacity recovers"
27584        );
27585    }
27586
27587    #[test]
27588    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
27589        let capacity = Error::Http {
27590            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27591            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
27592        };
27593        assert_eq!(
27594            worker_poll_capacity_retry_after(&capacity),
27595            Some(Duration::from_secs(3))
27596        );
27597
27598        let rejected_capacity = Error::Http {
27599            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27600            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
27601        };
27602        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
27603        assert!(!worker_operation_is_retryable(&rejected_capacity));
27604
27605        let ordinary_rate_limit = Error::Http {
27606            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
27607            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
27608                .to_string(),
27609        };
27610        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
27611        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
27612    }
27613
27614    #[tokio::test]
27615    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
27616        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27617            poll_failures_per_path: 8,
27618            heartbeat_failures: 8,
27619            ..MockWorkerBehavior::default()
27620        });
27621        let client = Client::builder(server.base_url())
27622            .timeout(Duration::from_secs(2))
27623            .build()
27624            .expect("client");
27625        let acknowledgements = Arc::new(AtomicUsize::new(0));
27626        let observed = Arc::clone(&acknowledgements);
27627        let mut worker = Worker::new(client, "rust-workers")
27628            .recover_transient_outages(true)
27629            .poll_timeout(Duration::from_millis(10))
27630            .retry_policy(WorkerRetryPolicy {
27631                max_retries: 2,
27632                initial_backoff: Duration::from_millis(2),
27633                max_backoff: Duration::from_millis(5),
27634            })
27635            .on_worker_heartbeat(move |_| {
27636                observed.fetch_add(1, Ordering::SeqCst);
27637            });
27638        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27639        worker.register_activity(
27640            "counter.activity",
27641            |_ctx, _input| async move { Ok(Value::Null) },
27642        );
27643        worker.register_query("counter", "current", |_ctx, _args| async move {
27644            Ok(Value::Null)
27645        });
27646
27647        worker
27648            .run_until(tokio::time::sleep(Duration::from_millis(500)))
27649            .await
27650            .expect("a recoverable outage must not stop the service worker");
27651
27652        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
27653        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
27654        for path in [
27655            "/api/worker/workflow-tasks/poll",
27656            "/api/worker/activity-tasks/poll",
27657            "/api/worker/query-tasks/poll",
27658        ] {
27659            let bodies = server.request_bodies(path);
27660            assert!(bodies.len() >= 10, "{path} must resume after recovery");
27661            let first = &bodies[0]["poll_request_id"];
27662            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
27663            for body in &bodies[..9] {
27664                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
27665            }
27666            assert_ne!(&bodies[9]["poll_request_id"], first);
27667            let times = server.request_times(path);
27668            for pair in times[..9].windows(2) {
27669                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
27670            }
27671        }
27672    }
27673
27674    #[tokio::test]
27675    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
27676        for heartbeat_outage in [false, true] {
27677            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27678                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
27679                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
27680                ..MockWorkerBehavior::default()
27681            });
27682            let client = Client::builder(server.base_url()).build().expect("client");
27683            let mut worker = Worker::new(client, "rust-workers")
27684                .recover_transient_outages(true)
27685                .retry_policy(WorkerRetryPolicy {
27686                    max_retries: 1,
27687                    initial_backoff: Duration::from_secs(5),
27688                    max_backoff: Duration::from_secs(5),
27689                });
27690            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27691            let started = Instant::now();
27692            worker
27693                .run_until(tokio::time::sleep(Duration::from_millis(200)))
27694                .await
27695                .expect("shutdown during an outage is a normal stop");
27696            assert!(started.elapsed() < Duration::from_secs(1));
27697            let path = if heartbeat_outage {
27698                "/api/worker/heartbeat"
27699            } else {
27700                "/api/worker/workflow-tasks/poll"
27701            };
27702            assert_eq!(server.request_count(path), 1);
27703            assert_eq!(
27704                server.request_count("/api/worker/registrations/mock-worker"),
27705                1
27706            );
27707        }
27708    }
27709
27710    #[tokio::test]
27711    async fn worker_outage_recovery_keeps_run_once_bounded() {
27712        let server = MockWorkerServer::unavailable_polls();
27713        let client = Client::builder(server.base_url()).build().expect("client");
27714        let mut worker = Worker::new(client, "rust-workers")
27715            .recover_transient_outages(true)
27716            .retry_policy(WorkerRetryPolicy {
27717                max_retries: 2,
27718                initial_backoff: Duration::from_millis(1),
27719                max_backoff: Duration::from_millis(1),
27720            });
27721        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27722        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
27723        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
27724    }
27725
27726    #[tokio::test]
27727    async fn worker_outage_recovery_respects_disabled_retries() {
27728        let server = MockWorkerServer::unavailable_polls();
27729        let client = Client::builder(server.base_url()).build().expect("client");
27730        let mut worker = Worker::new(client, "rust-workers")
27731            .recover_transient_outages(true)
27732            .retry_policy(WorkerRetryPolicy {
27733                max_retries: 0,
27734                ..WorkerRetryPolicy::default()
27735            });
27736        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27737        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
27738        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27739    }
27740
27741    #[tokio::test]
27742    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
27743        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27744            heartbeat_failures: usize::MAX,
27745            unauthorized_polls: true,
27746            ..MockWorkerBehavior::default()
27747        });
27748        let client = Client::builder(server.base_url()).build().expect("client");
27749        let mut worker = Worker::new(client, "rust-workers")
27750            .recover_transient_outages(true)
27751            .retry_policy(WorkerRetryPolicy {
27752                max_retries: 1,
27753                initial_backoff: Duration::from_secs(5),
27754                max_backoff: Duration::from_secs(5),
27755            });
27756        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27757        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
27758            .await
27759            .expect("fatal poll errors must interrupt heartbeat recovery")
27760            .expect_err("authentication failure is terminal");
27761        assert!(
27762            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
27763        );
27764        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27765    }
27766
27767    #[tokio::test]
27768    async fn worker_bounds_transport_retries() {
27769        let server = MockWorkerServer::unavailable_polls();
27770        let client = Client::builder(server.base_url())
27771            .timeout(Duration::from_secs(2))
27772            .build()
27773            .expect("client");
27774        let mut worker = Worker::new(client, "rust-workers")
27775            .worker_id("bounded-retry-worker")
27776            .poll_timeout(Duration::from_millis(10))
27777            .retry_policy(WorkerRetryPolicy {
27778                max_retries: 2,
27779                initial_backoff: Duration::from_millis(1),
27780                max_backoff: Duration::from_millis(1),
27781            });
27782        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27783
27784        let error = worker.run().await.expect_err("retry bound must terminate");
27785        assert!(matches!(error, Error::Transport(_)));
27786        assert_eq!(
27787            server.request_count("/api/worker/workflow-tasks/poll"),
27788            3,
27789            "one initial request plus exactly two retries"
27790        );
27791    }
27792
27793    #[tokio::test]
27794    async fn worker_retry_policy_can_disable_poll_retries() {
27795        let server = MockWorkerServer::unavailable_polls();
27796        let client = Client::builder(server.base_url())
27797            .timeout(Duration::from_secs(2))
27798            .build()
27799            .expect("client");
27800        let mut worker = Worker::new(client, "rust-workers")
27801            .worker_id("no-retry-worker")
27802            .poll_timeout(Duration::from_millis(10))
27803            .retry_policy(WorkerRetryPolicy {
27804                max_retries: 0,
27805                initial_backoff: Duration::from_millis(1),
27806                max_backoff: Duration::from_millis(1),
27807            });
27808        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27809
27810        let error = worker
27811            .run_once()
27812            .await
27813            .expect_err("disabled retries must return the first transport failure");
27814        assert!(matches!(error, Error::Transport(_)));
27815        assert_eq!(
27816            server.request_count("/api/worker/workflow-tasks/poll"),
27817            1,
27818            "max_retries=0 must send only the initial request"
27819        );
27820    }
27821
27822    #[tokio::test]
27823    async fn worker_does_not_retry_authentication_failures() {
27824        let server = MockWorkerServer::unauthorized_polls();
27825        let client = Client::builder(server.base_url())
27826            .timeout(Duration::from_secs(2))
27827            .build()
27828            .expect("client");
27829        let mut worker = Worker::new(client, "rust-workers")
27830            .worker_id("unauthorized-worker")
27831            .recover_transient_outages(true)
27832            .poll_timeout(Duration::from_millis(10));
27833        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27834
27835        let error = worker
27836            .run()
27837            .await
27838            .expect_err("authentication must terminate");
27839        let Error::Http { status, body } = error else {
27840            panic!("expected stable HTTP authentication error");
27841        };
27842        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
27843        assert!(body.contains("authentication_failed"));
27844        assert_eq!(
27845            server.request_count("/api/worker/workflow-tasks/poll"),
27846            1,
27847            "authentication failures must not be retried"
27848        );
27849    }
27850
27851    #[derive(Clone, Debug)]
27852    struct CapturedRequest {
27853        headers: String,
27854        method: String,
27855        path: String,
27856        authorization: Option<String>,
27857        namespace: Option<String>,
27858        worker_protocol: Option<String>,
27859        control_protocol: Option<String>,
27860        body: String,
27861        received_at: Instant,
27862    }
27863
27864    struct MockWorkerServer {
27865        addr: SocketAddr,
27866        stop: Arc<AtomicBool>,
27867        requests: Arc<Mutex<Vec<CapturedRequest>>>,
27868        thread: Option<thread::JoinHandle<()>>,
27869    }
27870
27871    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
27872
27873    #[derive(Clone, Copy, Default)]
27874    struct MockWorkerBehavior {
27875        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
27876        request_override: Option<RequestOverride>,
27877        storage_refusals: usize,
27878        storage_path: Option<&'static str>,
27879        storage_unavailable: bool,
27880        storage_mid_poll: bool,
27881        storage_activity: bool,
27882        storage_query: bool,
27883        storage_wrong_poll_id: bool,
27884        reject_query_protocol: bool,
27885        reject_query_completion: bool,
27886        waiting_query_worker: bool,
27887        decline_registration: bool,
27888        complete_named_signal: bool,
27889        poll_failures_per_path: usize,
27890        long_poll_capacity_responses_per_path: usize,
27891        heartbeat_failures: usize,
27892        heartbeat_failure_request: Option<usize>,
27893        delayed_heartbeat_request: Option<usize>,
27894        heartbeat_response_delay: Duration,
27895        concurrent_requests: bool,
27896        unauthorized_polls: bool,
27897        reject_registration: bool,
27898        reject_registration_protocol: bool,
27899        reject_deregistration: bool,
27900        reject_deregistration_protocol: bool,
27901        cancelled_activity: bool,
27902        draining_polls: bool,
27903        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
27904        workflow_completion_status: Option<&'static str>,
27905        workflow_completion_body: Option<&'static str>,
27906    }
27907
27908    impl MockWorkerServer {
27909        fn start() -> Self {
27910            Self::start_with_behavior(MockWorkerBehavior::default())
27911        }
27912
27913        fn reject_query_protocol() -> Self {
27914            Self::start_with_behavior(MockWorkerBehavior {
27915                reject_query_protocol: true,
27916                ..MockWorkerBehavior::default()
27917            })
27918        }
27919
27920        fn reject_query_completion() -> Self {
27921            Self::start_with_behavior(MockWorkerBehavior {
27922                reject_query_completion: true,
27923                ..MockWorkerBehavior::default()
27924            })
27925        }
27926
27927        fn waiting_query_worker() -> Self {
27928            Self::start_with_behavior(MockWorkerBehavior {
27929                waiting_query_worker: true,
27930                complete_named_signal: true,
27931                ..MockWorkerBehavior::default()
27932            })
27933        }
27934
27935        fn transient_worker_failures() -> Self {
27936            Self::start_with_behavior(MockWorkerBehavior {
27937                poll_failures_per_path: 1,
27938                heartbeat_failures: 1,
27939                ..MockWorkerBehavior::default()
27940            })
27941        }
27942
27943        fn consecutive_poll_failures(count: usize) -> Self {
27944            Self::start_with_behavior(MockWorkerBehavior {
27945                poll_failures_per_path: count,
27946                ..MockWorkerBehavior::default()
27947            })
27948        }
27949
27950        fn capacity_limited_activity_poll() -> Self {
27951            Self::start_with_behavior(MockWorkerBehavior {
27952                long_poll_capacity_responses_per_path: 1,
27953                ..MockWorkerBehavior::default()
27954            })
27955        }
27956
27957        fn delayed_heartbeat_worker() -> Self {
27958            Self::start_with_behavior(MockWorkerBehavior {
27959                waiting_query_worker: true,
27960                delayed_heartbeat_request: Some(2),
27961                heartbeat_response_delay: Duration::from_millis(1_500),
27962                concurrent_requests: true,
27963                cancelled_activity: true,
27964                ..MockWorkerBehavior::default()
27965            })
27966        }
27967
27968        fn heartbeat_retry_worker() -> Self {
27969            Self::start_with_behavior(MockWorkerBehavior {
27970                waiting_query_worker: true,
27971                heartbeat_failure_request: Some(2),
27972                concurrent_requests: true,
27973                ..MockWorkerBehavior::default()
27974            })
27975        }
27976
27977        fn unavailable_polls() -> Self {
27978            Self::start_with_behavior(MockWorkerBehavior {
27979                poll_failures_per_path: usize::MAX,
27980                ..MockWorkerBehavior::default()
27981            })
27982        }
27983
27984        fn unauthorized_polls() -> Self {
27985            Self::start_with_behavior(MockWorkerBehavior {
27986                unauthorized_polls: true,
27987                ..MockWorkerBehavior::default()
27988            })
27989        }
27990
27991        fn rejected_registration() -> Self {
27992            Self::start_with_behavior(MockWorkerBehavior {
27993                reject_registration: true,
27994                ..MockWorkerBehavior::default()
27995            })
27996        }
27997
27998        fn rejected_registration_protocol() -> Self {
27999            Self::start_with_behavior(MockWorkerBehavior {
28000                reject_registration_protocol: true,
28001                ..MockWorkerBehavior::default()
28002            })
28003        }
28004
28005        fn declined_registration() -> Self {
28006            Self::start_with_behavior(MockWorkerBehavior {
28007                decline_registration: true,
28008                ..MockWorkerBehavior::default()
28009            })
28010        }
28011
28012        fn rejected_deregistration() -> Self {
28013            Self::start_with_behavior(MockWorkerBehavior {
28014                reject_deregistration: true,
28015                ..MockWorkerBehavior::default()
28016            })
28017        }
28018
28019        fn rejected_deregistration_protocol() -> Self {
28020            Self::start_with_behavior(MockWorkerBehavior {
28021                reject_deregistration_protocol: true,
28022                ..MockWorkerBehavior::default()
28023            })
28024        }
28025
28026        fn unauthorized_polls_and_rejected_deregistration() -> Self {
28027            Self::start_with_behavior(MockWorkerBehavior {
28028                unauthorized_polls: true,
28029                reject_deregistration: true,
28030                ..MockWorkerBehavior::default()
28031            })
28032        }
28033
28034        fn cancelled_activity() -> Self {
28035            Self::start_with_behavior(MockWorkerBehavior {
28036                cancelled_activity: true,
28037                ..MockWorkerBehavior::default()
28038            })
28039        }
28040
28041        fn draining_polls() -> Self {
28042            Self::start_with_behavior(MockWorkerBehavior {
28043                draining_polls: true,
28044                ..MockWorkerBehavior::default()
28045            })
28046        }
28047
28048        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
28049            Self::start_with_behavior(MockWorkerBehavior {
28050                invalid_task_payload_codec: Some(codec),
28051                ..MockWorkerBehavior::default()
28052            })
28053        }
28054
28055        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
28056            Self::start_with_behavior(MockWorkerBehavior {
28057                workflow_completion_status: Some(status),
28058                workflow_completion_body: Some(body),
28059                ..MockWorkerBehavior::default()
28060            })
28061        }
28062
28063        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
28064            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
28065            listener
28066                .set_nonblocking(true)
28067                .expect("configure mock listener");
28068            let addr = listener.local_addr().expect("mock server address");
28069            let stop = Arc::new(AtomicBool::new(false));
28070            let server_stop = Arc::clone(&stop);
28071            let requests = Arc::new(Mutex::new(Vec::new()));
28072            let server_requests = Arc::clone(&requests);
28073            let thread = thread::spawn(move || {
28074                let mut request_threads = Vec::new();
28075                while !server_stop.load(Ordering::SeqCst) {
28076                    match listener.accept() {
28077                        Ok((mut stream, _)) => {
28078                            if behavior.concurrent_requests {
28079                                let requests = Arc::clone(&server_requests);
28080                                request_threads.push(thread::spawn(move || {
28081                                    handle_mock_worker_request(&mut stream, &requests, behavior)
28082                                }));
28083                            } else {
28084                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
28085                            }
28086                        }
28087                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
28088                            let mut index = 0;
28089                            while index < request_threads.len() {
28090                                if request_threads[index].is_finished() {
28091                                    request_threads
28092                                        .swap_remove(index)
28093                                        .join()
28094                                        .expect("join mock request");
28095                                } else {
28096                                    index += 1;
28097                                }
28098                            }
28099                            thread::sleep(Duration::from_millis(5));
28100                        }
28101                        Err(_) => break,
28102                    }
28103                }
28104                for request_thread in request_threads {
28105                    request_thread.join().expect("join mock request");
28106                }
28107            });
28108
28109            Self {
28110                addr,
28111                stop,
28112                requests,
28113                thread: Some(thread),
28114            }
28115        }
28116
28117        fn base_url(&self) -> String {
28118            format!("http://{}", self.addr)
28119        }
28120
28121        fn worker_protocol_for(&self, path: &str) -> Option<String> {
28122            self.requests
28123                .lock()
28124                .expect("captured requests")
28125                .iter()
28126                .find(|request| request.path == path)
28127                .and_then(|request| request.worker_protocol.clone())
28128        }
28129
28130        fn control_protocol_for(&self, path: &str) -> Option<String> {
28131            self.requests
28132                .lock()
28133                .expect("captured requests")
28134                .iter()
28135                .find(|request| request.path == path)
28136                .and_then(|request| request.control_protocol.clone())
28137        }
28138
28139        fn method_for(&self, path: &str) -> Option<String> {
28140            self.requests
28141                .lock()
28142                .expect("captured requests")
28143                .iter()
28144                .find(|request| request.path == path)
28145                .map(|request| request.method.clone())
28146        }
28147
28148        fn authorization_for(&self, path: &str) -> Option<String> {
28149            self.requests
28150                .lock()
28151                .expect("captured requests")
28152                .iter()
28153                .find(|request| request.path == path)
28154                .and_then(|request| request.authorization.clone())
28155        }
28156
28157        fn namespace_for(&self, path: &str) -> Option<String> {
28158            self.requests
28159                .lock()
28160                .expect("captured requests")
28161                .iter()
28162                .find(|request| request.path == path)
28163                .and_then(|request| request.namespace.clone())
28164        }
28165
28166        fn request_count(&self, path: &str) -> usize {
28167            self.requests
28168                .lock()
28169                .expect("captured requests")
28170                .iter()
28171                .filter(|request| request.path == path)
28172                .count()
28173        }
28174
28175        fn captured_paths(&self) -> Vec<String> {
28176            self.requests
28177                .lock()
28178                .expect("captured requests")
28179                .iter()
28180                .map(|request| request.path.clone())
28181                .collect()
28182        }
28183
28184        fn request_times(&self, path: &str) -> Vec<Instant> {
28185            self.requests
28186                .lock()
28187                .expect("captured requests")
28188                .iter()
28189                .filter(|request| request.path == path)
28190                .map(|request| request.received_at)
28191                .collect()
28192        }
28193
28194        fn request_body(&self, path: &str) -> Value {
28195            let requests = self.requests.lock().expect("captured requests");
28196            let body = &requests
28197                .iter()
28198                .find(|request| request.path == path)
28199                .unwrap_or_else(|| panic!("missing request for {path}"))
28200                .body;
28201            serde_json::from_str(body).unwrap_or_else(|error| {
28202                panic!("invalid JSON request body for {path}: {error}: {body:?}")
28203            })
28204        }
28205
28206        fn request_bodies(&self, path: &str) -> Vec<Value> {
28207            self.requests
28208                .lock()
28209                .expect("captured requests")
28210                .iter()
28211                .filter(|request| request.path == path)
28212                .map(|request| {
28213                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
28214                        panic!(
28215                            "invalid JSON request body for {path}: {error}: {:?}",
28216                            request.body
28217                        )
28218                    })
28219                })
28220                .collect()
28221        }
28222    }
28223
28224    impl Drop for MockWorkerServer {
28225        fn drop(&mut self) {
28226            self.stop.store(true, Ordering::SeqCst);
28227            let _ = TcpStream::connect(self.addr);
28228
28229            if let Some(thread) = self.thread.take() {
28230                thread.join().expect("join mock server");
28231            }
28232        }
28233    }
28234
28235    fn handle_mock_worker_request(
28236        stream: &mut TcpStream,
28237        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
28238        behavior: MockWorkerBehavior,
28239    ) {
28240        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
28241        let mut buffer = [0_u8; 8192];
28242        let mut request = Vec::new();
28243
28244        loop {
28245            match stream.read(&mut buffer) {
28246                Ok(0) => break,
28247                Ok(read) => {
28248                    request.extend_from_slice(&buffer[..read]);
28249                    if mock_request_is_complete(&request) {
28250                        break;
28251                    }
28252                }
28253                Err(error)
28254                    if matches!(
28255                        error.kind(),
28256                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
28257                    ) =>
28258                {
28259                    break;
28260                }
28261                Err(_) => return,
28262            }
28263        }
28264
28265        let request = String::from_utf8_lossy(&request);
28266        let body = request
28267            .split_once("\r\n\r\n")
28268            .map(|(_, body)| body)
28269            .unwrap_or_default();
28270        let path = request
28271            .lines()
28272            .next()
28273            .and_then(|line| line.split_whitespace().nth(1))
28274            .unwrap_or_default();
28275        let method = request
28276            .lines()
28277            .next()
28278            .and_then(|line| line.split_whitespace().next())
28279            .unwrap_or_default();
28280        let authorization = request.lines().find_map(|line| {
28281            let (name, value) = line.split_once(':')?;
28282            name.eq_ignore_ascii_case("Authorization")
28283                .then(|| value.trim().to_string())
28284        });
28285        let namespace = request.lines().find_map(|line| {
28286            let (name, value) = line.split_once(':')?;
28287            name.eq_ignore_ascii_case("X-Namespace")
28288                .then(|| value.trim().to_string())
28289        });
28290        let worker_protocol = request.lines().find_map(|line| {
28291            let (name, value) = line.split_once(':')?;
28292            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
28293                .then(|| value.trim().to_string())
28294        });
28295        let control_protocol = request.lines().find_map(|line| {
28296            let (name, value) = line.split_once(':')?;
28297            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
28298                .then(|| value.trim().to_string())
28299        });
28300        let request_number = {
28301            let mut requests = requests.lock().expect("captured requests");
28302            requests.push(CapturedRequest {
28303                headers: request
28304                    .split_once("\r\n\r\n")
28305                    .map_or("", |(headers, _)| headers)
28306                    .to_owned(),
28307                method: method.to_string(),
28308                path: path.to_string(),
28309                authorization,
28310                namespace,
28311                worker_protocol: worker_protocol.clone(),
28312                control_protocol,
28313                body: body.to_string(),
28314                received_at: Instant::now(),
28315            });
28316            requests
28317                .iter()
28318                .filter(|request| request.path == path)
28319                .count()
28320        };
28321
28322        if let Some(response) = behavior
28323            .request_override
28324            .and_then(|handler| handler(path, body, request_number))
28325        {
28326            write_mock_response(stream, response.0, &response.1);
28327            return;
28328        }
28329        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
28330            write_mock_response(stream, response.0, &response.1);
28331            return;
28332        }
28333        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
28334            return;
28335        }
28336        let pressure_path = behavior
28337            .storage_path
28338            .is_some_and(|part| path.contains(part));
28339        let prior_failures = if path.ends_with("/poll") {
28340            behavior.poll_failures_per_path
28341        } else {
28342            0
28343        };
28344        if pressure_path
28345            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
28346        {
28347            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
28348            let poll_id = path
28349                .ends_with("/poll")
28350                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
28351            let mut refusal = storage_refusal(
28352                poll_id,
28353                behavior.storage_unavailable,
28354                behavior.storage_mid_poll,
28355            );
28356            if behavior.storage_wrong_poll_id {
28357                refusal["poll_request_id"] = json!("wrong-poll");
28358            }
28359            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
28360            return;
28361        }
28362        if path.contains("/storage-task/")
28363            || path.contains("/storage-activity/")
28364            || path.contains("/storage-query/")
28365        {
28366            write_mock_response(stream, "200 OK", "{}");
28367            return;
28368        }
28369        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
28370            write_mock_response(stream, "200 OK", &json!({"task":{
28371                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
28372                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
28373                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28374                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28375                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
28376            }}).to_string());
28377            return;
28378        }
28379        if behavior.storage_activity
28380            && path == "/api/worker/activity-tasks/poll"
28381            && request_number == 1
28382        {
28383            write_mock_response(stream, "200 OK", &json!({"task":{
28384                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
28385                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
28386                "attempt_number":7, "lease_owner":"storage-worker"
28387            }}).to_string());
28388            return;
28389        }
28390
28391        if path == "/api/worker/register" {
28392            if behavior.reject_registration_protocol {
28393                write_mock_response(
28394                    stream,
28395                    "400 Bad Request",
28396                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
28397                );
28398                return;
28399            }
28400            if behavior.reject_registration {
28401                write_mock_response(
28402                    stream,
28403                    "503 Service Unavailable",
28404                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
28405                );
28406                return;
28407            }
28408        }
28409
28410        if path.starts_with("/api/worker/registrations/") {
28411            if behavior.reject_deregistration_protocol {
28412                write_mock_response(
28413                    stream,
28414                    "400 Bad Request",
28415                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.19"}"#,
28416                );
28417            } else if behavior.reject_deregistration {
28418                write_mock_response(
28419                    stream,
28420                    "403 Forbidden",
28421                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
28422                );
28423            } else {
28424                write_mock_response(
28425                    stream,
28426                    "200 OK",
28427                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
28428                );
28429            }
28430            return;
28431        }
28432
28433        let is_poll = matches!(
28434            path,
28435            "/api/worker/workflow-tasks/poll"
28436                | "/api/worker/activity-tasks/poll"
28437                | "/api/worker/query-tasks/poll"
28438        );
28439        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
28440            write_mock_response(
28441                stream,
28442                "429 Too Many Requests",
28443                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
28444            );
28445            return;
28446        }
28447        if is_poll && request_number <= behavior.poll_failures_per_path {
28448            return;
28449        }
28450        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
28451            return;
28452        }
28453        if path == "/api/worker/heartbeat"
28454            && behavior.heartbeat_failure_request == Some(request_number)
28455        {
28456            return;
28457        }
28458        if path == "/api/worker/heartbeat"
28459            && behavior.delayed_heartbeat_request == Some(request_number)
28460        {
28461            thread::sleep(behavior.heartbeat_response_delay);
28462        }
28463        if behavior.unauthorized_polls && is_poll {
28464            write_mock_response(
28465                stream,
28466                "401 Unauthorized",
28467                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
28468            );
28469            return;
28470        }
28471        if behavior.draining_polls && is_poll {
28472            write_mock_response(
28473                stream,
28474                "409 Conflict",
28475                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
28476            );
28477            return;
28478        }
28479
28480        if let Some(codec_case) = behavior.invalid_task_payload_codec {
28481            if is_poll && request_number == 1 {
28482                let mut task = match path {
28483                    "/api/worker/workflow-tasks/poll" => json!({
28484                        "task_id": "codec-workflow",
28485                        "workflow_type": "codec.workflow",
28486                        "payload_codec": DEFAULT_CODEC,
28487                        "workflow_task_attempt": 1,
28488                        "lease_owner": "codec-worker"
28489                    }),
28490                    "/api/worker/activity-tasks/poll" => json!({
28491                        "task_id": "codec-activity",
28492                        "activity_attempt_id": "codec-activity-attempt",
28493                        "activity_type": "codec.activity",
28494                        "payload_codec": DEFAULT_CODEC,
28495                        "attempt_number": 1,
28496                        "lease_owner": "codec-worker"
28497                    }),
28498                    "/api/worker/query-tasks/poll" => json!({
28499                        "query_task_id": "codec-query",
28500                        "query_task_attempt": 1,
28501                        "workflow_type": "codec.workflow",
28502                        "query_name": "known",
28503                        "payload_codec": DEFAULT_CODEC,
28504                        "lease_owner": "codec-worker"
28505                    }),
28506                    _ => unreachable!("is_poll limits task codec probe paths"),
28507                };
28508                codec_case.apply(&mut task);
28509                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
28510                return;
28511            }
28512
28513            if matches!(
28514                path,
28515                "/api/worker/workflow-tasks/codec-workflow/fail"
28516                    | "/api/worker/activity-tasks/codec-activity/fail"
28517                    | "/api/worker/query-tasks/codec-query/fail"
28518            ) {
28519                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
28520                return;
28521            }
28522        }
28523
28524        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
28525            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
28526            let body = format!(
28527                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
28528            );
28529            write_mock_response(stream, "400 Bad Request", &body);
28530            return;
28531        }
28532
28533        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
28534        {
28535            write_mock_response(
28536                stream,
28537                "409 Conflict",
28538                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
28539            );
28540            return;
28541        }
28542
28543        if behavior.workflow_completion_status.is_some()
28544            && path == "/api/worker/workflow-tasks/poll"
28545            && request_number == 1
28546        {
28547            write_mock_response(
28548                stream,
28549                "200 OK",
28550                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"}}"#,
28551            );
28552            return;
28553        }
28554
28555        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
28556            if let (Some(status), Some(body)) = (
28557                behavior.workflow_completion_status,
28558                behavior.workflow_completion_body,
28559            ) {
28560                write_mock_response(stream, status, body);
28561                return;
28562            }
28563        }
28564
28565        if behavior.waiting_query_worker {
28566            if behavior.complete_named_signal
28567                && path == "/api/worker/workflow-tasks/poll"
28568                && request_number == 1
28569            {
28570                let body = json!({
28571                    "task": {
28572                        "task_id": "snapshot-open",
28573                        "workflow_id": "snapshot-1",
28574                        "run_id": "snapshot-run-1",
28575                        "workflow_type": "snapshot",
28576                        "payload_codec": DEFAULT_CODEC,
28577                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28578                            .expect("Avro workflow arguments"),
28579                        "history_events": [],
28580                        "workflow_task_attempt": 1,
28581                        "lease_owner": "rust-snapshot-worker"
28582                    }
28583                })
28584                .to_string();
28585                write_mock_response(stream, "200 OK", &body);
28586                return;
28587            }
28588
28589            let signal_request = request_number - usize::from(behavior.complete_named_signal);
28590            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
28591            if path == "/api/worker/workflow-tasks/poll"
28592                && signal_request >= 1
28593                && signal_request <= signal_request_limit
28594            {
28595                let finish = behavior.complete_named_signal && signal_request == 3;
28596                let amounts = if signal_request == 1 {
28597                    vec![3]
28598                } else {
28599                    vec![3, 5]
28600                };
28601                let task_id = if signal_request == 1 {
28602                    "snapshot-wait-3"
28603                } else if finish {
28604                    "snapshot-finish"
28605                } else {
28606                    "snapshot-wait-5"
28607                };
28608                let mut history_events = std::iter::once(json!({
28609                    "event_type": "SignalWaitOpened",
28610                    "payload": {"sequence": 1, "signal_name": "finish"}
28611                }))
28612                .chain(amounts.iter().enumerate().map(|(index, amount)| {
28613                    json!({
28614                        "event_type": "SignalReceived",
28615                        "payload": {
28616                            "signal_id": format!("increment-{amount}"),
28617                            "signal_name": "increment",
28618                            "workflow_sequence": index + 2,
28619                            "payload_codec": DEFAULT_CODEC,
28620                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28621                                .expect("Avro signal envelope")
28622                        }
28623                    })
28624                }))
28625                .collect::<Vec<_>>();
28626                let (resume_id, resume_name, resume_arguments) = if finish {
28627                    history_events.push(json!({
28628                        "event_type": "SignalReceived",
28629                        "payload": {
28630                            "signal_id": "finish",
28631                            "signal_name": "finish",
28632                            "workflow_sequence": 4,
28633                            "payload_codec": DEFAULT_CODEC,
28634                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28635                                .expect("Avro finish signal envelope")
28636                        }
28637                    }));
28638                    (
28639                        "finish".to_string(),
28640                        "finish".to_string(),
28641                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
28642                            .expect("Avro finish resume signal"),
28643                    )
28644                } else {
28645                    let amount = amounts.last().expect("amount");
28646                    (
28647                        format!("increment-{amount}"),
28648                        "increment".to_string(),
28649                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28650                            .expect("Avro increment resume signal"),
28651                    )
28652                };
28653                let body = json!({
28654                    "task": {
28655                        "task_id": task_id,
28656                        "workflow_id": "snapshot-1",
28657                        "run_id": "snapshot-run-1",
28658                        "workflow_type": "snapshot",
28659                        "payload_codec": DEFAULT_CODEC,
28660                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28661                            .expect("Avro workflow arguments"),
28662                        "history_events": history_events,
28663                        "workflow_task_attempt": 1,
28664                        "workflow_signal_id": resume_id,
28665                        "signal_name": resume_name,
28666                        "signal_arguments": resume_arguments,
28667                        "lease_owner": "rust-snapshot-worker"
28668                    }
28669                })
28670                .to_string();
28671                write_mock_response(stream, "200 OK", &body);
28672                return;
28673            }
28674
28675            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
28676                let history_events = [3, 5]
28677                    .into_iter()
28678                    .enumerate()
28679                    .map(|(index, amount)| {
28680                        json!({
28681                            "event_type": "SignalReceived",
28682                            "payload": {
28683                                "signal_id": format!("increment-{amount}"),
28684                                "signal_name": "increment",
28685                                "workflow_sequence": index + 2,
28686                                "payload_codec": DEFAULT_CODEC,
28687                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
28688                                    .expect("Avro query signal envelope")
28689                            }
28690                        })
28691                    })
28692                    .collect::<Vec<_>>();
28693                let body = json!({
28694                    "task": {
28695                        "query_task_id": "snapshot-current",
28696                        "query_task_attempt": 1,
28697                        "lease_owner": "rust-snapshot-worker",
28698                        "workflow_id": "snapshot-1",
28699                        "run_id": "snapshot-run-1",
28700                        "workflow_type": "snapshot",
28701                        "query_name": "current",
28702                        "payload_codec": DEFAULT_CODEC,
28703                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28704                            .expect("Avro workflow arguments"),
28705                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
28706                            .expect("Avro query arguments"),
28707                        "history_events": history_events,
28708                        "run_status": "waiting"
28709                    }
28710                })
28711                .to_string();
28712                write_mock_response(stream, "200 OK", &body);
28713                return;
28714            }
28715
28716            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
28717                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
28718            {
28719                write_mock_response(
28720                    stream,
28721                    "200 OK",
28722                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
28723                );
28724                return;
28725            }
28726
28727            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
28728                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
28729                return;
28730            }
28731
28732            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
28733                write_mock_response(
28734                    stream,
28735                    "200 OK",
28736                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
28737                );
28738                return;
28739            }
28740
28741            if path == "/api/worker/query-tasks/snapshot-current/complete" {
28742                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
28743                return;
28744            }
28745        }
28746
28747        if matches!(
28748            path,
28749            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
28750        ) {
28751            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
28752                .expect("typed mock result");
28753            let body = json!({
28754                "result": typed_fidelity_probe().into_json().expect("result projection"),
28755                "result_envelope": result,
28756            })
28757            .to_string();
28758            write_mock_response(stream, "200 OK", &body);
28759            return;
28760        }
28761
28762        if path == "/api/workflows/typed-1" {
28763            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
28764                .expect("typed mock result");
28765            let body = json!({
28766                "workflow_id": "typed-1",
28767                "run_id": "run-typed-1",
28768                "workflow_type": "typed.echo",
28769                "status": "completed",
28770                "output": typed_fidelity_probe().into_json().expect("output projection"),
28771                "output_envelope": result,
28772            })
28773            .to_string();
28774            write_mock_response(stream, "200 OK", &body);
28775            return;
28776        }
28777
28778        let (status, body) = match path {
28779            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
28780            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
28781            "/api/workflows" => (
28782                "201 Created",
28783                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
28784            ),
28785            "/api/worker/register" if behavior.decline_registration => (
28786                "200 OK",
28787                r#"{"worker_id":"declined-worker","registered":false}"#,
28788            ),
28789            "/api/worker/register" if behavior.waiting_query_worker => (
28790                "200 OK",
28791                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
28792            ),
28793            "/api/worker/register" => (
28794                "200 OK",
28795                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
28796            ),
28797            "/api/worker/heartbeat" => ("200 OK", "{}"),
28798            "/api/worker/activity-tasks/poll"
28799                if behavior.cancelled_activity && request_number == 1 =>
28800            {
28801                (
28802                    "200 OK",
28803                    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"}}"#,
28804                )
28805            }
28806            "/api/worker/activity-tasks/poll"
28807                if behavior.long_poll_capacity_responses_per_path > 0
28808                    && request_number
28809                        == behavior
28810                            .long_poll_capacity_responses_per_path
28811                            .saturating_add(1) =>
28812            {
28813                (
28814                    "200 OK",
28815                    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"}}"#,
28816                )
28817            }
28818            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
28819                ("200 OK", r#"{"task":null}"#)
28820            }
28821            "/api/worker/query-tasks/poll"
28822                if behavior.reject_query_completion && request_number == 1 =>
28823            {
28824                (
28825                    "200 OK",
28826                    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"}}"#,
28827                )
28828            }
28829            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
28830            "/api/worker/query-tasks/query-capture/complete"
28831            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
28832            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
28833                "200 OK",
28834                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
28835            ),
28836            "/api/worker/activity-tasks/activity-cancel/complete" => (
28837                "409 Conflict",
28838                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
28839            ),
28840            "/api/worker/activity-tasks/activity-typed/complete"
28841            | "/api/worker/activity-tasks/activity-typed/fail"
28842            | "/api/worker/activity-tasks/capacity-activity/complete"
28843            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
28844            "/api/workflows/counter-1/query/current" => (
28845                "200 OK",
28846                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
28847            ),
28848            "/api/workflows/counter-1/query/missing" => (
28849                "404 Not Found",
28850                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
28851            ),
28852            "/api/workflows/wf-lifecycle/cancel" => (
28853                "200 OK",
28854                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
28855            ),
28856            "/api/workflows/wf-lifecycle/terminate" => (
28857                "200 OK",
28858                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
28859            ),
28860            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
28861                "200 OK",
28862                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
28863            ),
28864            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
28865                "200 OK",
28866                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
28867            ),
28868            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
28869                "202 Accepted",
28870                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
28871            ),
28872            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
28873                "200 OK",
28874                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}"#,
28875            ),
28876            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
28877                "409 Conflict",
28878                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
28879            ),
28880            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
28881            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
28882                "409 Conflict",
28883                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
28884            ),
28885            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
28886                "200 OK",
28887                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"}]}}"#,
28888            ),
28889            "/api/workflows/wf-cancelled" => (
28890                "200 OK",
28891                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
28892            ),
28893            "/api/workflows/wf-terminated" => (
28894                "200 OK",
28895                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
28896            ),
28897            "/api/workflows/wf-timed-out" => (
28898                "200 OK",
28899                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
28900            ),
28901            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
28902                "200 OK",
28903                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
28904            ),
28905            "/api/workflows/wf-selected" => (
28906                "200 OK",
28907                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
28908            ),
28909            "/api/workflows/wf-selected/runs/run-selected" => (
28910                "200 OK",
28911                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
28912            ),
28913            _ => ("404 Not Found", r#"{"message":"not found"}"#),
28914        };
28915        write_mock_response(stream, status, body);
28916    }
28917
28918    fn mock_request_is_complete(request: &[u8]) -> bool {
28919        let Some(header_end) = request
28920            .windows(4)
28921            .position(|window| window == b"\r\n\r\n")
28922            .map(|position| position + 4)
28923        else {
28924            return false;
28925        };
28926        let headers = String::from_utf8_lossy(&request[..header_end]);
28927        let content_length = headers.lines().find_map(|line| {
28928            let (name, value) = line.split_once(':')?;
28929            name.eq_ignore_ascii_case("content-length")
28930                .then(|| value.trim().parse::<usize>().ok())
28931                .flatten()
28932        });
28933
28934        request.len() >= header_end + content_length.unwrap_or(0)
28935    }
28936
28937    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
28938        let response = format!(
28939            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
28940            body.len()
28941        );
28942
28943        let _ = stream.write_all(response.as_bytes());
28944        let _ = stream.flush();
28945    }
28946
28947    fn activity_completion_backend_recovery(
28948        path: &str,
28949        _body: &str,
28950        request_number: usize,
28951    ) -> Option<(&'static str, String)> {
28952        match path {
28953            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
28954                "200 OK",
28955                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(),
28956            )),
28957            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
28958                "503 Service Unavailable",
28959                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(),
28960            )),
28961            "/api/worker/activity-tasks/recover-activity/complete" => Some((
28962                "200 OK",
28963                r#"{"outcome":"completed","recorded":true}"#.to_string(),
28964            )),
28965            _ => None,
28966        }
28967    }
28968
28969    fn workflow_completion_backend_recovery(
28970        path: &str,
28971        _body: &str,
28972        request_number: usize,
28973    ) -> Option<(&'static str, String)> {
28974        match path {
28975            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
28976                "200 OK",
28977                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
28978            )),
28979            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
28980                "503 Service Unavailable",
28981                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(),
28982            )),
28983            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
28984                "200 OK",
28985                r#"{"outcome":"completed","recorded":true}"#.to_string(),
28986            )),
28987            _ => None,
28988        }
28989    }
28990
28991    fn activity_completion_stale_after_backend_recovery(
28992        path: &str,
28993        body: &str,
28994        request_number: usize,
28995    ) -> Option<(&'static str, String)> {
28996        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
28997            return Some((
28998                "409 Conflict",
28999                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(),
29000            ));
29001        }
29002        activity_completion_backend_recovery(path, body, request_number)
29003    }
29004
29005    fn activity_completion_remains_unavailable(
29006        path: &str,
29007        body: &str,
29008        request_number: usize,
29009    ) -> Option<(&'static str, String)> {
29010        if path == "/api/worker/activity-tasks/recover-activity/complete" {
29011            return activity_completion_backend_recovery(path, body, 1);
29012        }
29013        activity_completion_backend_recovery(path, body, request_number)
29014    }
29015
29016    #[tokio::test]
29017    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
29018        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29019            request_override: Some(activity_completion_backend_recovery),
29020            ..MockWorkerBehavior::default()
29021        });
29022        let client = Client::builder(server.base_url())
29023            .timeout(Duration::from_secs(2))
29024            .build()
29025            .expect("client");
29026        let handler_calls = Arc::new(AtomicUsize::new(0));
29027        let mut worker = Worker::new(client, "recover-queue")
29028            .worker_id("recover-worker")
29029            .poll_timeout(Duration::from_millis(10));
29030        worker.register_activity("recover.activity", {
29031            let handler_calls = Arc::clone(&handler_calls);
29032            move |_ctx, _args| {
29033                let handler_calls = Arc::clone(&handler_calls);
29034                async move {
29035                    handler_calls.fetch_add(1, Ordering::SeqCst);
29036                    Ok(json!("done"))
29037                }
29038            }
29039        });
29040
29041        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
29042        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
29043        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
29044        assert_eq!(bodies.len(), 2);
29045        assert_eq!(bodies[0], bodies[1]);
29046    }
29047
29048    #[tokio::test]
29049    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
29050        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29051            request_override: Some(workflow_completion_backend_recovery),
29052            ..MockWorkerBehavior::default()
29053        });
29054        let client = Client::builder(server.base_url())
29055            .timeout(Duration::from_secs(2))
29056            .build()
29057            .expect("client");
29058        let handler_calls = Arc::new(AtomicUsize::new(0));
29059        let mut worker = Worker::new(client, "recover-queue")
29060            .worker_id("recover-worker")
29061            .poll_timeout(Duration::from_millis(10));
29062        worker.register_workflow("recover.workflow", {
29063            let handler_calls = Arc::clone(&handler_calls);
29064            move |_ctx, _args| {
29065                let handler_calls = Arc::clone(&handler_calls);
29066                async move {
29067                    handler_calls.fetch_add(1, Ordering::SeqCst);
29068                    Ok(json!("done"))
29069                }
29070            }
29071        });
29072
29073        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
29074        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
29075        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
29076        assert_eq!(bodies.len(), 2);
29077        assert_eq!(bodies[0], bodies[1]);
29078    }
29079
29080    #[tokio::test]
29081    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
29082        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29083            request_override: Some(activity_completion_stale_after_backend_recovery),
29084            ..MockWorkerBehavior::default()
29085        });
29086        let client = Client::builder(server.base_url())
29087            .timeout(Duration::from_secs(2))
29088            .build()
29089            .expect("client");
29090        let handler_calls = Arc::new(AtomicUsize::new(0));
29091        let mut worker = Worker::new(client, "recover-queue")
29092            .worker_id("recover-worker")
29093            .poll_timeout(Duration::from_millis(10));
29094        worker.register_activity("recover.activity", {
29095            let handler_calls = Arc::clone(&handler_calls);
29096            move |_ctx, _args| {
29097                let handler_calls = Arc::clone(&handler_calls);
29098                async move {
29099                    handler_calls.fetch_add(1, Ordering::SeqCst);
29100                    Ok(json!("done"))
29101                }
29102            }
29103        });
29104
29105        assert_eq!(
29106            worker
29107                .run_once()
29108                .await
29109                .expect("authoritative stale outcome"),
29110            1
29111        );
29112        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
29113        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
29114        assert_eq!(bodies.len(), 2);
29115        assert_eq!(bodies[0], bodies[1]);
29116    }
29117
29118    #[test]
29119    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
29120        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
29121        let response = json!({
29122            "reason":"backend_unavailable", "operation":"complete_activity_task",
29123            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
29124            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
29125            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
29126        });
29127        let path = "/worker/activity-tasks/recover-activity/complete";
29128        let error = |body: Value| Error::Http {
29129            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29130            body: body.to_string(),
29131        };
29132        assert_eq!(
29133            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
29134            Some(Duration::from_secs(1))
29135        );
29136
29137        for (field, invalid) in [
29138            ("operation", json!("poll_activity_task")),
29139            ("outcome", json!("rejected")),
29140            ("worker_id", json!("another-worker")),
29141            ("task_queue", json!("recover-queue")),
29142            ("retryable", json!(false)),
29143            ("retry_after_seconds", json!(0)),
29144            ("task_id", json!("another-task")),
29145            ("lease_owner", json!("another-worker")),
29146            ("activity_attempt_id", json!("another-attempt")),
29147        ] {
29148            let mut invalid_response = response.clone();
29149            invalid_response[field] = invalid;
29150            assert_eq!(
29151                worker_fenced_completion_retry_after(
29152                    &error(invalid_response),
29153                    path,
29154                    Some(&request)
29155                ),
29156                None,
29157                "must not retry mismatched {field}"
29158            );
29159        }
29160        assert_eq!(
29161            worker_fenced_completion_retry_after(&error(response), path, None),
29162            None
29163        );
29164    }
29165
29166    #[tokio::test]
29167    async fn shutdown_interrupts_fenced_completion_backend_wait() {
29168        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29169            request_override: Some(activity_completion_remains_unavailable),
29170            ..MockWorkerBehavior::default()
29171        });
29172        let client = Client::builder(server.base_url())
29173            .timeout(Duration::from_secs(2))
29174            .build()
29175            .expect("client");
29176        let stop = Arc::new(AtomicBool::new(false));
29177        let worker = Worker::new(client, "recover-queue")
29178            .worker_id("recover-worker")
29179            .with_storage_admission(Arc::clone(&stop));
29180        let completion = tokio::spawn(async move {
29181            worker
29182                .client
29183                .complete_activity_task(
29184                    "recover-activity",
29185                    "recover-attempt",
29186                    "recover-worker",
29187                    json!("done"),
29188                    DEFAULT_CODEC,
29189                )
29190                .await
29191        });
29192        let path = "/api/worker/activity-tasks/recover-activity/complete";
29193        tokio::time::timeout(Duration::from_secs(2), async {
29194            while server.request_count(path) == 0 {
29195                tokio::time::sleep(Duration::from_millis(10)).await;
29196            }
29197        })
29198        .await
29199        .expect("first completion request");
29200        stop.store(true, Ordering::SeqCst);
29201        let error = tokio::time::timeout(Duration::from_secs(1), completion)
29202            .await
29203            .expect("shutdown must interrupt retry wait")
29204            .expect("completion task")
29205            .expect_err("backend is still unavailable");
29206        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
29207        assert_eq!(server.request_count(path), 1);
29208    }
29209}