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 sticky_worker;
13mod sticky_workflow_cache;
14mod worker_session;
15
16pub use cancellation_context::{
17    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
18};
19pub use cancellation_scope::CancellationScopeOpenReceipt;
20#[doc(hidden)]
21pub use cancellation_scope_history::{
22    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
23};
24#[doc(hidden)]
25pub use cancellation_scope_replay::CancellationScopeRequested;
26
27pub use cooperative_cancellation::{
28    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
29    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
30    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
31    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
32};
33
34use std::{
35    any::{type_name, Any, TypeId},
36    collections::{BTreeMap, BTreeSet, HashMap},
37    future::Future,
38    io::{self, Read},
39    pin::Pin,
40    sync::{
41        atomic::{AtomicBool, Ordering},
42        Arc, Mutex, OnceLock,
43    },
44    task::{Context as TaskContext, Poll},
45    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
46};
47
48use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
49use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
50use chrono::DateTime;
51use futures_util::{
52    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
53};
54pub use local_activity::LocalActivityOptions;
55use serde::{
56    de::DeserializeOwned,
57    ser::{SerializeMap, SerializeSeq},
58    Deserialize, Deserializer, Serialize, Serializer,
59};
60pub use serde_json::{json, Value};
61use sha2::{Digest, Sha256};
62pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
63use thiserror::Error;
64pub use uuid::Uuid;
65pub use worker_session::{WorkerSession, WorkerSessionOptions};
66
67pub const WORKER_PROTOCOL_VERSION: &str = "1.19";
68const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
69/// First additive worker protocol that defines portable worker-affinity features.
70pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
71pub const CONTROL_PLANE_VERSION: &str = "2";
72pub const DEFAULT_CODEC: &str = "avro";
73pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
74/// Worker-registration capability for authored condition-wait occurrence identity.
75pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
76    "condition_wait_occurrence_identity";
77/// Worker-registration capability for portable memo upserts.
78pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
79/// Worker-registration capability for server-routed read-only queries.
80pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
81/// Worker-registration capability for canonical typed search attributes.
82pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
83/// Worker-registration capability for synchronous workflow updates.
84pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
85/// Worker-registration capability for durable named input streams.
86pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
87/// Worker-registration capability for persisted first-completion selection.
88pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
89pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
90pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
91pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
92pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
93pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
94/// First additive worker protocol that defines query-task transport.
95pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
96/// First additive worker protocol that defines typed search-attribute upserts.
97pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
98/// First additive worker protocol that defines portable memo upserts.
99pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
100/// First additive worker protocol that preserves declared search-attribute types.
101pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
102/// First additive worker protocol that defines external durable condition waits.
103pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
104/// First additive worker protocol that preserves authored condition-wait occurrences.
105pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
106/// First additive worker protocol that defines durable selection groups.
107pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
108
109pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
110    let Some((major, minor)) = version.split_once('.') else {
111        return false;
112    };
113    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
114}
115
116fn validate_user_signal_name(signal_name: &str) -> Result<()> {
117    if signal_name == MESSAGE_STREAM_SIGNAL {
118        return Err(Error::Codec(format!(
119            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
120        )));
121    }
122    Ok(())
123}
124
125const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
126const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
127    "Workflow task waiting for scheduled history.";
128const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
129const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
130const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
131const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
132const MAX_MEMO_ENTRIES: usize = 100;
133const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
134const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
135
136const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
137    "lease_expired",
138    "query_task_not_found",
139    "query_task_not_leased",
140    "query_task_timed_out",
141];
142
143/// Manifest for the default service-worker profile.
144///
145/// Inline local execution is enabled separately by [`Worker::local_activities`].
146/// Local execution, sessions and caching require explicit Worker configuration.
147pub fn portable_worker_affinity_capability_manifest() -> Value {
148    json!({
149        "local_activities": {
150            "supported": false,
151            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
152            "reason": "rust_worker_does_not_execute_record_local_activity",
153        },
154        "worker_sessions": {
155            "supported": false,
156            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
157            "reason": "rust_worker_has_no_typed_session_lifecycle",
158        },
159        "sticky_execution": {
160            "supported": false,
161            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
162            "reason": "rust_worker_uses_complete_durable_history_replay",
163        },
164    })
165}
166
167/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
168pub const AVRO_VALUE_SCHEMA_JSON: &str =
169    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
170pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
171pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
172const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
173
174static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
175static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
176    OnceLock::new();
177
178#[derive(Clone, Copy)]
179enum RequestProtocol {
180    ControlPlane,
181    Worker(&'static str),
182}
183
184pub type Result<T> = std::result::Result<T, Error>;
185
186#[derive(Debug, Error)]
187pub enum Error {
188    #[error("transport error: {0}")]
189    Transport(#[from] reqwest::Error),
190    #[error(
191        "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"
192    )]
193    InvalidBaseUrl,
194    #[error("json error: {0}")]
195    Json(#[from] serde_json::Error),
196    #[error("http {status}: {body}")]
197    Http {
198        status: reqwest::StatusCode,
199        body: String,
200    },
201    #[error("codec error: {0}")]
202    Codec(String),
203    #[error(transparent)]
204    QueryFailed(QueryFailure),
205    #[error(transparent)]
206    Protocol(ProtocolFailure),
207    #[error(transparent)]
208    NonDeterministicReplay(ReplayFailure),
209    #[error(transparent)]
210    ChildWorkflowFailed(ChildWorkflowFailure),
211    #[error(transparent)]
212    ActivityFailed(ActivityFailure),
213    #[error(transparent)]
214    ParallelFailed(ParallelFailure),
215    #[error(transparent)]
216    SagaCompensationFailed(SagaCompensationFailure),
217    #[error(transparent)]
218    InvalidParallelGroup(ParallelGroupError),
219    #[error(transparent)]
220    DurableOperationCancelled(DurableOperationCancelled),
221    #[error(transparent)]
222    WorkflowCancellationRequested(WorkflowCancellationRequested),
223    #[error(transparent)]
224    CooperativeCancellationRequested(CooperativeCancellationRequested),
225    #[error(transparent)]
226    CancellationScopeRequested(CancellationScopeRequested),
227    #[error(transparent)]
228    WorkflowCommandRejected(WorkflowCommandRejection),
229    #[error(transparent)]
230    WorkflowFailed(WorkflowTerminalOutcome),
231    #[error(transparent)]
232    WorkflowCancelled(WorkflowTerminalOutcome),
233    #[error(transparent)]
234    WorkflowTerminated(WorkflowTerminalOutcome),
235    #[error(transparent)]
236    WorkflowTimedOut(WorkflowTerminalOutcome),
237    #[error(transparent)]
238    ActivityTaskRejected(ActivityTaskRejection),
239    #[error("workflow handler {0:?} is not registered")]
240    WorkflowNotRegistered(String),
241    #[error("activity handler {0:?} is not registered")]
242    ActivityNotRegistered(String),
243    #[error(
244        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
245    )]
246    HandlerType {
247        handler_kind: HandlerKind,
248        handler_name: String,
249        value_kind: HandlerValueKind,
250        rust_type: &'static str,
251        message: String,
252    },
253    #[error("workflow future yielded without emitting a durable command")]
254    WorkflowYieldedWithoutCommand,
255    #[error(
256        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
257    )]
258    MissingWorkflowCommandIdentity,
259    #[error("workflow state lock is poisoned")]
260    WorkflowStatePoisoned,
261    #[error("timer duration is too large for the worker protocol")]
262    TimerDurationOverflow,
263    #[error(transparent)]
264    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
265    #[error(transparent)]
266    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
267    #[error("operation timed out")]
268    Timeout,
269    #[error(
270        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
271    )]
272    MissingRoleCredentials {
273        role: &'static str,
274        opposite_role: &'static str,
275    },
276    #[error("worker loop error: {0}")]
277    WorkerLoop(String),
278    #[error(
279        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
280    )]
281    UnsupportedUpdateValidators { workflow_type: String },
282    #[error("{primary}; worker deregistration also failed: {deregistration}")]
283    WorkerShutdown {
284        primary: Box<Error>,
285        deregistration: Box<Error>,
286    },
287    #[error("invalid child workflow options: {0}")]
288    InvalidChildWorkflowOptions(String),
289    #[error("invalid workflow memo update: {0}")]
290    InvalidMemoUpdate(String),
291    #[error(
292        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
293    )]
294    WorkflowMemoUpdatesUnavailable,
295    #[error("cooperative cancellation is unavailable: {0}")]
296    CooperativeCancellationUnavailable(String),
297    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
298    CancellationScopeExecutionUnavailable,
299    #[error("invalid cooperative cancellation: {0}")]
300    InvalidCooperativeCancellation(String),
301    #[error("activity execution no longer owns its claim: {0}")]
302    ActivityExecutionAbandoned(String),
303    #[error(transparent)]
304    InvalidActivityOptions(ActivityOptionsError),
305    #[error(transparent)]
306    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
307    #[doc(hidden)]
308    #[error("workflow requested continue as new")]
309    ContinueAsNew(ContinueAsNewRequest),
310}
311
312/// Validation failure for a durable condition-wait definition.
313#[derive(Clone, Debug, Error, PartialEq, Eq)]
314pub enum ConditionWaitOptionsError {
315    #[error("condition_key must be non-empty")]
316    EmptyKey,
317    #[error("condition_definition_fingerprint must be non-empty")]
318    EmptyPredicateIdentity,
319    #[error("condition timeout is too large for the worker protocol")]
320    TimeoutOverflow,
321}
322
323/// Stable identity and optional durable timeout for a condition wait.
324///
325/// `predicate_identity` is recorded as the worker protocol's
326/// `condition_definition_fingerprint` and must change whenever predicate
327/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
328/// is written inline; it derives this identity from the predicate tokens.
329#[derive(Clone, Debug, PartialEq, Eq)]
330pub struct ConditionWaitOptions {
331    condition_key: String,
332    predicate_identity: String,
333    timeout: Option<Duration>,
334}
335
336impl ConditionWaitOptions {
337    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
338        Self {
339            condition_key: condition_key.into(),
340            predicate_identity: predicate_identity.into(),
341            timeout: None,
342        }
343    }
344
345    pub fn timeout(mut self, timeout: Duration) -> Self {
346        self.timeout = Some(timeout);
347        self
348    }
349
350    fn validate(
351        &self,
352    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
353        let condition_key = self.condition_key.trim();
354        if condition_key.is_empty() {
355            return Err(ConditionWaitOptionsError::EmptyKey);
356        }
357        let predicate_identity = self.predicate_identity.trim();
358        if predicate_identity.is_empty() {
359            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
360        }
361        let timeout_seconds = self
362            .timeout
363            .map(|timeout| {
364                timeout
365                    .as_secs()
366                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
367                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
368            })
369            .transpose()?;
370
371        Ok(ValidatedConditionWaitOptions {
372            condition_key: condition_key.to_string(),
373            predicate_identity: predicate_identity.to_string(),
374            timeout_seconds,
375        })
376    }
377}
378
379#[derive(Clone, Debug, PartialEq, Eq)]
380struct ValidatedConditionWaitOptions {
381    condition_key: String,
382    predicate_identity: String,
383    timeout_seconds: Option<u64>,
384}
385
386const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
387
388/// Unambiguous terminal result of a durable condition wait.
389#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
390#[serde(rename_all = "snake_case")]
391pub enum ConditionWaitResult {
392    Satisfied,
393    TimedOut,
394}
395
396impl ConditionWaitResult {
397    pub fn is_satisfied(self) -> bool {
398        self == Self::Satisfied
399    }
400
401    pub fn is_timed_out(self) -> bool {
402        self == Self::TimedOut
403    }
404}
405
406/// Build the stable condition definition identity used by [`wait_condition!`].
407#[doc(hidden)]
408pub fn __condition_definition_fingerprint(source: &str) -> String {
409    let mut digest = Sha256::new();
410    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
411    digest.update(source.as_bytes());
412    format!("sha256:{:x}", digest.finalize())
413}
414
415/// Create a durable condition wait whose predicate definition is fingerprinted
416/// from its inline Rust tokens.
417///
418/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
419/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
420#[macro_export]
421macro_rules! wait_condition {
422    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
423        $ctx.wait_condition(
424            $crate::ConditionWaitOptions::new(
425                $key,
426                $crate::__condition_definition_fingerprint(concat!(
427                    module_path!(),
428                    "\0",
429                    stringify!($predicate)
430                )),
431            )
432            .timeout($timeout),
433            $predicate,
434        )
435    }};
436    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
437        $ctx.wait_condition(
438            $crate::ConditionWaitOptions::new(
439                $key,
440                $crate::__condition_definition_fingerprint(concat!(
441                    module_path!(),
442                    "\0",
443                    stringify!($predicate)
444                )),
445            ),
446            $predicate,
447        )
448    }};
449}
450
451const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
452const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
453const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
454const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
455const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
456
457/// Validation failure for a typed workflow search-attribute update.
458#[derive(Clone, Debug, Error, PartialEq, Eq)]
459pub enum SearchAttributeUpdateError {
460    #[error("search-attribute update requires at least one attribute")]
461    Empty,
462    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
463    InvalidKey(String),
464    #[error("search-attribute update exceeds the limit of 100 attributes")]
465    TooManyAttributes,
466    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
467    ValueTooLong {
468        key: String,
469        kind: &'static str,
470        limit: usize,
471    },
472    #[error(
473        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
474    )]
475    EmptyString(String),
476    #[error("search attribute {0:?} has a non-finite float value")]
477    NonFiniteFloat(String),
478    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
479    InvalidDateTime(String),
480    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
481    PayloadTooLarge,
482}
483
484/// One public typed search-attribute value.
485#[derive(Clone, Debug, PartialEq)]
486pub enum SearchAttributeValue {
487    String(String),
488    Keyword(String),
489    KeywordList(Vec<String>),
490    Int(i64),
491    Float(f64),
492    Bool(bool),
493    DateTime(String),
494    Delete,
495}
496
497impl SearchAttributeValue {
498    fn type_name(&self) -> Option<&'static str> {
499        match self {
500            Self::String(_) => Some("string"),
501            Self::Keyword(_) => Some("keyword"),
502            Self::KeywordList(_) => Some("keyword_list"),
503            Self::Int(_) => Some("int"),
504            Self::Float(_) => Some("float"),
505            Self::Bool(_) => Some("bool"),
506            Self::DateTime(_) => Some("datetime"),
507            Self::Delete => None,
508        }
509    }
510
511    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
512        let normalize_string = |value: String, kind: &'static str, limit: usize| {
513            let value = value.trim().to_string();
514            if value.is_empty() {
515                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
516            }
517            if value.len() > limit {
518                return Err(SearchAttributeUpdateError::ValueTooLong {
519                    key: key.to_string(),
520                    kind,
521                    limit,
522                });
523            }
524            Ok(value)
525        };
526
527        match self {
528            Self::String(value) => Ok(Self::String(normalize_string(
529                value,
530                "string",
531                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
532            )?)),
533            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
534                value,
535                "keyword",
536                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
537            )?)),
538            Self::KeywordList(values) => {
539                let values = values
540                    .into_iter()
541                    .map(|value| {
542                        let value = value.trim().to_string();
543                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
544                            return Err(SearchAttributeUpdateError::ValueTooLong {
545                                key: key.to_string(),
546                                kind: "keyword-list entry",
547                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
548                            });
549                        }
550                        Ok(value)
551                    })
552                    .collect::<std::result::Result<Vec<_>, _>>()?;
553                Ok(Self::KeywordList(values))
554            }
555            Self::Float(value) if !value.is_finite() => {
556                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
557            }
558            Self::DateTime(value) => {
559                let value =
560                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
561                if DateTime::parse_from_rfc3339(&value).is_err() {
562                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
563                }
564                Ok(Self::DateTime(value))
565            }
566            value => Ok(value),
567        }
568    }
569
570    fn into_json(self) -> Value {
571        match self {
572            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
573                Value::String(value)
574            }
575            Self::KeywordList(values) => {
576                Value::Array(values.into_iter().map(Value::String).collect())
577            }
578            Self::Int(value) => json!(value),
579            Self::Float(value) => json!(value),
580            Self::Bool(value) => json!(value),
581            Self::Delete => Value::Null,
582        }
583    }
584}
585
586/// Validated typed workflow-side search-attribute mutation.
587#[derive(Clone, Debug, Default, PartialEq)]
588pub struct SearchAttributeUpdate {
589    attributes: BTreeMap<String, SearchAttributeValue>,
590}
591
592impl SearchAttributeUpdate {
593    pub fn new() -> Self {
594        Self::default()
595    }
596
597    pub fn set(
598        mut self,
599        key: impl Into<String>,
600        value: SearchAttributeValue,
601    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
602        let key = key.into();
603        validate_search_attribute_key(&key)?;
604        if !self.attributes.contains_key(&key)
605            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
606        {
607            return Err(SearchAttributeUpdateError::TooManyAttributes);
608        }
609        self.attributes.insert(key.clone(), value.normalized(&key)?);
610        self.validate_size()?;
611        Ok(self)
612    }
613
614    pub fn string(
615        self,
616        key: impl Into<String>,
617        value: impl Into<String>,
618    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
619        self.set(key, SearchAttributeValue::String(value.into()))
620    }
621
622    pub fn keyword(
623        self,
624        key: impl Into<String>,
625        value: impl Into<String>,
626    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
627        self.set(key, SearchAttributeValue::Keyword(value.into()))
628    }
629
630    pub fn keyword_list<I, V>(
631        self,
632        key: impl Into<String>,
633        values: I,
634    ) -> std::result::Result<Self, SearchAttributeUpdateError>
635    where
636        I: IntoIterator<Item = V>,
637        V: Into<String>,
638    {
639        self.set(
640            key,
641            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
642        )
643    }
644
645    pub fn int(
646        self,
647        key: impl Into<String>,
648        value: i64,
649    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
650        self.set(key, SearchAttributeValue::Int(value))
651    }
652
653    pub fn float(
654        self,
655        key: impl Into<String>,
656        value: f64,
657    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
658        self.set(key, SearchAttributeValue::Float(value))
659    }
660
661    pub fn bool(
662        self,
663        key: impl Into<String>,
664        value: bool,
665    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
666        self.set(key, SearchAttributeValue::Bool(value))
667    }
668
669    pub fn datetime(
670        self,
671        key: impl Into<String>,
672        value: impl Into<String>,
673    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
674        self.set(key, SearchAttributeValue::DateTime(value.into()))
675    }
676
677    pub fn delete(
678        self,
679        key: impl Into<String>,
680    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
681        self.set(key, SearchAttributeValue::Delete)
682    }
683
684    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
685        let (attributes, _) = self.clone().into_wire_parts();
686        if serde_json::to_vec(&attributes)
687            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
688            .unwrap_or(true)
689        {
690            return Err(SearchAttributeUpdateError::PayloadTooLarge);
691        }
692        Ok(())
693    }
694
695    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
696        let mut attributes = serde_json::Map::new();
697        let mut attribute_types = BTreeMap::new();
698        for (key, value) in self.attributes {
699            if let Some(type_name) = value.type_name() {
700                attribute_types.insert(key.clone(), type_name.to_string());
701            }
702            attributes.insert(key, value.into_json());
703        }
704        (Value::Object(attributes), attribute_types)
705    }
706
707    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
708        if self.attributes.is_empty() {
709            return Err(SearchAttributeUpdateError::Empty);
710        }
711        self.validate_size()
712    }
713}
714
715fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
716    let valid = !key.is_empty()
717        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
718        && key
719            .bytes()
720            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
721    if valid {
722        Ok(())
723    } else {
724        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
725    }
726}
727
728/// The registered handler family reported by [`Error::HandlerType`].
729#[derive(Clone, Copy, Debug, PartialEq, Eq)]
730pub enum HandlerKind {
731    Workflow,
732    Activity,
733}
734
735impl std::fmt::Display for HandlerKind {
736    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
737        formatter.write_str(match self {
738            Self::Workflow => "workflow",
739            Self::Activity => "activity",
740        })
741    }
742}
743
744/// Whether a typed handler failed to adapt its input or result.
745#[derive(Clone, Copy, Debug, PartialEq, Eq)]
746pub enum HandlerValueKind {
747    Input,
748    Result,
749}
750
751impl std::fmt::Display for HandlerValueKind {
752    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
753        formatter.write_str(match self {
754            Self::Input => "input",
755            Self::Result => "result",
756        })
757    }
758}
759
760/// The lifecycle command sent to a workflow execution.
761#[derive(Clone, Copy, Debug, PartialEq, Eq)]
762pub enum WorkflowCommandKind {
763    Cancel,
764    Terminate,
765}
766
767impl WorkflowCommandKind {
768    fn as_str(self) -> &'static str {
769        match self {
770            Self::Cancel => "cancel",
771            Self::Terminate => "terminate",
772        }
773    }
774}
775
776/// Optional structured fields for a cancellation or termination request.
777#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
778pub struct WorkflowCommandOptions {
779    #[serde(skip_serializing_if = "Option::is_none")]
780    pub reason: Option<String>,
781    #[serde(skip_serializing_if = "Option::is_none")]
782    pub request_id: Option<String>,
783}
784
785/// Server-enforced timeout policy for a workflow start.
786///
787/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
788/// only bounds how long the caller waits. A server deadline produces a terminal
789/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
790/// `run_timeout`.
791#[derive(Clone, Debug, PartialEq, Eq)]
792pub struct WorkflowStartOptions {
793    pub execution_timeout_seconds: u64,
794    pub run_timeout_seconds: u64,
795}
796
797impl Default for WorkflowStartOptions {
798    fn default() -> Self {
799        Self {
800            execution_timeout_seconds: 3600,
801            run_timeout_seconds: 600,
802        }
803    }
804}
805
806impl WorkflowStartOptions {
807    pub fn new() -> Self {
808        Self::default()
809    }
810
811    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
812        self.execution_timeout_seconds = seconds;
813        self
814    }
815
816    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
817        self.run_timeout_seconds = seconds;
818        self
819    }
820
821    fn validate(&self) -> Result<()> {
822        if self.execution_timeout_seconds == 0 {
823            return Err(Error::Codec(
824                "execution_timeout_seconds must be at least 1".to_string(),
825            ));
826        }
827        if self.run_timeout_seconds == 0 {
828            return Err(Error::Codec(
829                "run_timeout_seconds must be at least 1".to_string(),
830            ));
831        }
832        if self.run_timeout_seconds > self.execution_timeout_seconds {
833            return Err(Error::Codec(
834                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
835            ));
836        }
837
838        Ok(())
839    }
840}
841
842/// Optional routing overrides for a continue-as-new transition.
843///
844/// Omitted values retain the current workflow type and task queue. Server-owned
845/// instance metadata is not accepted here and is carried by the server.
846#[derive(Clone, Debug, Default, PartialEq, Eq)]
847pub struct ContinueAsNewOptions {
848    pub workflow_type: Option<String>,
849    pub task_queue: Option<String>,
850}
851
852impl ContinueAsNewOptions {
853    pub fn new() -> Self {
854        Self::default()
855    }
856
857    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
858        self.workflow_type = Some(workflow_type.into());
859        self
860    }
861
862    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
863        self.task_queue = Some(task_queue.into());
864        self
865    }
866
867    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
868        for (field, value) in [
869            ("workflow_type", self.workflow_type.as_deref()),
870            ("task_queue", self.task_queue.as_deref()),
871        ] {
872            if value.is_some_and(|value| value.trim().is_empty()) {
873                return Err(ContinueAsNewOptionsError {
874                    field,
875                    message: format!("{field} must not be empty"),
876                });
877            }
878        }
879        Ok(())
880    }
881}
882
883/// A stable validation error raised before a continue-as-new command is emitted.
884#[derive(Clone, Debug, Error, PartialEq, Eq)]
885#[error("invalid continue-as-new option {field}: {message}")]
886pub struct ContinueAsNewOptionsError {
887    pub field: &'static str,
888    pub message: String,
889}
890
891/// Public history-budget information attached to the current workflow task.
892#[derive(Clone, Debug, Default, PartialEq, Eq)]
893pub struct WorkflowHistoryBudget {
894    pub event_count: u64,
895    pub size_bytes: Option<u64>,
896    pub continue_as_new_recommended: bool,
897    pub pressure: Option<String>,
898}
899
900#[doc(hidden)]
901#[derive(Clone, Debug)]
902pub struct ContinueAsNewRequest {
903    arguments: AvroValue,
904    options: ContinueAsNewOptions,
905}
906
907impl WorkflowCommandOptions {
908    pub fn new() -> Self {
909        Self::default()
910    }
911
912    pub fn reason(mut self, reason: impl Into<String>) -> Self {
913        self.reason = Some(reason.into());
914        self
915    }
916
917    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
918        self.request_id = Some(request_id.into());
919        self
920    }
921}
922
923/// The accepted, machine-readable result of a lifecycle command.
924#[derive(Clone, Debug, PartialEq)]
925pub struct WorkflowCommandResult {
926    pub command: WorkflowCommandKind,
927    pub workflow_id: String,
928    pub run_id: Option<String>,
929    pub outcome: Option<String>,
930    pub reason: Option<String>,
931    pub command_status: Option<String>,
932    pub raw: Value,
933}
934
935/// A new run continuing a failed run from its recorded activity boundary.
936#[derive(Clone, Debug, PartialEq)]
937pub struct WorkflowRedriveResult {
938    pub workflow_id: String,
939    pub source_run_id: String,
940    pub run_id: String,
941    pub resume_step_sequence: u64,
942    pub raw: Value,
943}
944
945/// A stable rejection returned by instance- or selected-run lifecycle commands.
946#[derive(Clone, Debug, Error)]
947#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
948pub struct WorkflowCommandRejection {
949    pub command: WorkflowCommandKind,
950    pub status: u16,
951    pub reason: String,
952    pub message: String,
953    pub workflow_id: String,
954    pub run_id: Option<String>,
955    pub target_scope: Option<String>,
956    pub body: Value,
957}
958
959/// Stable terminal categories returned by [`WorkflowHandle::result`].
960#[derive(Clone, Copy, Debug, PartialEq, Eq)]
961pub enum WorkflowTerminalKind {
962    Failed,
963    Cancelled,
964    Terminated,
965    TimedOut,
966}
967
968/// A typed terminal workflow outcome with durable identity and failure metadata.
969///
970/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
971/// of parsing its display representation. Fields remain `None` when an older
972/// server did not publish that metadata.
973#[derive(Clone, Debug, Error)]
974#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
975pub struct WorkflowTerminalOutcome {
976    pub kind: WorkflowTerminalKind,
977    pub workflow_id: String,
978    pub run_id: Option<String>,
979    pub reason: String,
980    pub failure_category: Option<String>,
981    pub failure_id: Option<String>,
982    pub exception_type: Option<String>,
983    pub exception_class: Option<String>,
984    pub non_retryable: Option<bool>,
985    pub message: Option<String>,
986    pub exception: Option<Value>,
987    pub raw: Value,
988}
989
990/// A worker-side activity settlement or heartbeat rejected by durable state.
991#[derive(Clone, Debug, Error)]
992#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
993pub struct ActivityTaskRejection {
994    pub operation: String,
995    pub status: u16,
996    pub reason: String,
997    pub task_id: String,
998    pub activity_attempt_id: String,
999    pub cancel_requested: bool,
1000    pub can_continue: Option<bool>,
1001    pub run_closed_reason: Option<String>,
1002    pub body: Value,
1003}
1004
1005/// Stable validation categories for [`ActivityOptions`].
1006#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1007pub enum ActivityOptionsErrorKind {
1008    EmptyTaskQueue,
1009    EmptyRetryPolicy,
1010    InvalidMaxAttempts,
1011    BackoffWithoutRetryBudget,
1012    TooManyBackoffIntervals,
1013    InvalidBackoffCoefficient,
1014    BackoffGenerationTooLarge,
1015    BackoffOverflow,
1016    EmptyNonRetryableErrorType,
1017    TimeoutNotPositive,
1018    MissingTotalTimeout,
1019    TimeoutOverflow,
1020    TimeoutOrder,
1021}
1022
1023/// A machine-readable activity-options validation failure.
1024#[derive(Clone, Debug, Error, PartialEq, Eq)]
1025#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1026pub struct ActivityOptionsError {
1027    pub kind: ActivityOptionsErrorKind,
1028    pub field: Option<&'static str>,
1029    pub message: String,
1030}
1031
1032impl ActivityOptionsError {
1033    fn new(
1034        kind: ActivityOptionsErrorKind,
1035        field: Option<&'static str>,
1036        message: impl Into<String>,
1037    ) -> Self {
1038        Self {
1039            kind,
1040            field,
1041            message: message.into(),
1042        }
1043    }
1044}
1045
1046/// Stable terminal categories returned when an awaited activity does not succeed.
1047#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1048pub enum ActivityFailureKind {
1049    Failed,
1050    Cancelled,
1051    TimedOut,
1052}
1053
1054/// A stable, machine-readable terminal activity failure.
1055///
1056/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1057/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1058#[derive(Clone, Debug, Error, PartialEq)]
1059#[error("activity failed ({reason}): {message}")]
1060pub struct ActivityFailure {
1061    pub kind: ActivityFailureKind,
1062    pub reason: String,
1063    pub message: String,
1064    pub activity_execution_id: Option<String>,
1065    pub activity_attempt_id: Option<String>,
1066    pub activity_type: Option<String>,
1067    pub activity_class: Option<String>,
1068    pub attempt_number: Option<u64>,
1069    pub failure_id: Option<String>,
1070    pub failure_category: Option<String>,
1071    pub timeout_kind: Option<String>,
1072    pub non_retryable: bool,
1073    pub exception_type: Option<String>,
1074    pub exception_class: Option<String>,
1075    pub code: Option<Value>,
1076    pub exception: Option<Value>,
1077}
1078
1079/// Stable terminal categories returned when an awaited child does not succeed.
1080#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1081pub enum ChildWorkflowFailureKind {
1082    Failed,
1083    Cancelled,
1084    Terminated,
1085}
1086
1087/// A stable, machine-readable child workflow failure delivered to its parent.
1088///
1089/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1090/// of parsing the display message. Child and parent identifiers retain the
1091/// relationship recorded in durable history across worker restarts.
1092#[derive(Clone, Debug, Error)]
1093#[error("child workflow failed ({reason}): {message}")]
1094pub struct ChildWorkflowFailure {
1095    pub kind: ChildWorkflowFailureKind,
1096    pub reason: String,
1097    pub message: String,
1098    pub parent_workflow_id: Option<String>,
1099    pub parent_workflow_run_id: Option<String>,
1100    pub child_workflow_id: Option<String>,
1101    pub child_workflow_run_id: Option<String>,
1102    pub child_workflow_type: Option<String>,
1103    pub failure_id: Option<String>,
1104    pub failure_category: Option<String>,
1105    pub exception_type: Option<String>,
1106    pub exception_class: Option<String>,
1107    pub non_retryable: bool,
1108    pub code: Option<Value>,
1109    pub exception: Option<Value>,
1110}
1111
1112/// The identity of one durable workflow execution.
1113#[derive(Clone, Debug, PartialEq, Eq)]
1114pub struct WorkflowIdentity {
1115    pub workflow_id: Option<String>,
1116    pub run_id: Option<String>,
1117}
1118
1119/// A successful child result together with its durable parent-child identity.
1120#[derive(Clone, Debug, PartialEq)]
1121pub struct ChildWorkflowResult {
1122    pub parent: WorkflowIdentity,
1123    pub child: WorkflowIdentity,
1124    pub child_workflow_type: Option<String>,
1125    pub result: Value,
1126}
1127
1128/// Lossless successful child result for fixed Avro Value workflows.
1129#[derive(Clone, Debug, PartialEq)]
1130pub struct ChildWorkflowAvroResult {
1131    pub parent: WorkflowIdentity,
1132    pub child: WorkflowIdentity,
1133    pub child_workflow_type: Option<String>,
1134    pub result: AvroValue,
1135}
1136
1137/// Stable user-facing identity for one member of a durable selection group.
1138#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1139#[serde(untagged)]
1140pub enum SelectionKey {
1141    Index(usize),
1142    Name(String),
1143}
1144
1145impl From<usize> for SelectionKey {
1146    fn from(value: usize) -> Self {
1147        Self::Index(value)
1148    }
1149}
1150
1151impl From<String> for SelectionKey {
1152    fn from(value: String) -> Self {
1153        Self::Name(value)
1154    }
1155}
1156
1157impl From<&str> for SelectionKey {
1158    fn from(value: &str) -> Self {
1159        Self::Name(value.to_string())
1160    }
1161}
1162
1163/// Typed result of explicitly awaiting a cancelled non-winning operation.
1164#[derive(Clone, Debug, Error, PartialEq, Eq)]
1165#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1166pub struct DurableOperationCancelled {
1167    pub selection_group_id: String,
1168    pub member_key: SelectionKey,
1169    pub member_index: usize,
1170    pub operation_kind: String,
1171    pub operation_identity: String,
1172}
1173
1174/// Stable identity for one enclosing deterministic parallel group.
1175///
1176/// The same fields are attached to every ordinary activity, timer, or child
1177/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1178/// no Rust-specific wire command is introduced.
1179#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1180pub struct ParallelGroupMetadata {
1181    pub parallel_group_id: String,
1182    pub parallel_group_kind: String,
1183    pub parallel_group_base_sequence: u64,
1184    pub parallel_group_size: usize,
1185    pub parallel_group_index: usize,
1186    #[serde(default, skip_serializing_if = "Option::is_none")]
1187    pub parallel_group_mode: Option<String>,
1188    #[serde(default, skip_serializing_if = "Option::is_none")]
1189    pub selection_member_key: Option<SelectionKey>,
1190    #[serde(default, skip_serializing_if = "Option::is_none")]
1191    pub selection_member_index: Option<usize>,
1192    #[serde(default, skip_serializing_if = "Option::is_none")]
1193    pub selection_member_base_sequence: Option<u64>,
1194    #[serde(default, skip_serializing_if = "Option::is_none")]
1195    pub selection_member_size: Option<usize>,
1196    #[serde(default, skip_serializing_if = "Option::is_none")]
1197    pub selection_member_kind: Option<String>,
1198}
1199
1200/// One input-ordered result returned by [`WorkflowContext::parallel`].
1201#[derive(Clone, Debug, PartialEq)]
1202pub enum ParallelResult {
1203    Activity(Value),
1204    ChildWorkflow(ChildWorkflowResult),
1205    Timer,
1206    Signal(Vec<Value>),
1207    Condition(ConditionWaitResult),
1208    Group(Vec<ParallelResult>),
1209}
1210
1211/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1212#[derive(Clone, Debug, PartialEq)]
1213pub enum ParallelAvroResult {
1214    Activity(AvroValue),
1215    ChildWorkflow(ChildWorkflowAvroResult),
1216    Timer,
1217    Signal(Vec<AvroValue>),
1218    Condition(ConditionWaitResult),
1219    Group(Vec<ParallelAvroResult>),
1220}
1221
1222impl ParallelAvroResult {
1223    fn into_json_result(self) -> Result<ParallelResult> {
1224        match self {
1225            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1226            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1227                parent: result.parent,
1228                child: result.child,
1229                child_workflow_type: result.child_workflow_type,
1230                result: result.result.into_json()?,
1231            })),
1232            Self::Timer => Ok(ParallelResult::Timer),
1233            Self::Signal(values) => Ok(ParallelResult::Signal(
1234                values
1235                    .into_iter()
1236                    .map(AvroValue::into_json)
1237                    .collect::<Result<Vec<_>>>()?,
1238            )),
1239            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1240            Self::Group(results) => Ok(ParallelResult::Group(
1241                results
1242                    .into_iter()
1243                    .map(Self::into_json_result)
1244                    .collect::<Result<Vec<_>>>()?,
1245            )),
1246        }
1247    }
1248}
1249
1250/// One successful leaf retained when another parallel member failed.
1251#[derive(Clone, Debug, PartialEq)]
1252pub struct ParallelCompletion {
1253    pub member_path: Vec<usize>,
1254    pub result: ParallelResult,
1255}
1256
1257/// A deterministic join failed after some siblings had already completed.
1258///
1259/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1260/// error. `completed` is declaration ordered and contains only durable
1261/// successes observed in the same replay. Late sibling completions can add
1262/// entries on a later replay without changing `member_path` or the selected
1263/// positional failure.
1264#[derive(Debug, Error)]
1265#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1266pub struct ParallelFailure {
1267    pub group_id: String,
1268    pub member_path: Vec<usize>,
1269    pub group_path: Vec<ParallelGroupMetadata>,
1270    pub completed: Vec<ParallelCompletion>,
1271    #[source]
1272    pub cause: Box<Error>,
1273}
1274
1275/// Stable validation error returned before an invalid group emits commands.
1276#[derive(Clone, Debug, Error, PartialEq, Eq)]
1277#[error("invalid deterministic parallel group ({reason}): {message}")]
1278pub struct ParallelGroupError {
1279    pub reason: &'static str,
1280    pub member_path: Vec<usize>,
1281    pub message: String,
1282}
1283
1284/// Cooperative workflow cancellation observed at an author-controlled point.
1285#[derive(Clone, Debug, Error, PartialEq, Eq)]
1286#[error("workflow cancellation was requested")]
1287pub struct WorkflowCancellationRequested;
1288
1289/// A forward saga failure followed by a terminal compensation failure.
1290#[derive(Debug, Error)]
1291#[error(
1292    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1293)]
1294pub struct SagaCompensationFailure {
1295    pub initiating_failure: Box<Error>,
1296    pub compensation_failure: Box<Error>,
1297    pub compensation_activity_type: String,
1298    pub compensation_registration_order: usize,
1299}
1300
1301/// Server behavior when a parent closes while its child is still open.
1302#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1303pub enum ParentClosePolicy {
1304    #[default]
1305    Abandon,
1306    /// Legacy terminal cancellation without cooperative cleanup.
1307    RequestCancel,
1308    /// Request cooperative cleanup with the original lineage and deadline.
1309    RequestCancellation,
1310    Terminate,
1311}
1312
1313impl ParentClosePolicy {
1314    fn as_str(self) -> &'static str {
1315        match self {
1316            Self::Abandon => "abandon",
1317            Self::RequestCancel => "request_cancel",
1318            Self::RequestCancellation => "request_cancellation",
1319            Self::Terminate => "terminate",
1320        }
1321    }
1322}
1323
1324/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1325#[non_exhaustive]
1326#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1327pub enum CancellationPolicy {
1328    /// Request cancellation and continue without waiting. Historical Activity default.
1329    TryCancel,
1330    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1331    WaitCancellationCompleted,
1332    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1333    #[default]
1334    Abandon,
1335}
1336
1337impl CancellationPolicy {
1338    fn as_str(self) -> &'static str {
1339        match self {
1340            Self::TryCancel => "try_cancel",
1341            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1342            Self::Abandon => "abandon",
1343        }
1344    }
1345}
1346
1347/// Durable retry policy for one child workflow invocation.
1348#[derive(Clone, Debug, Default, PartialEq, Eq)]
1349pub struct ChildWorkflowRetryPolicy {
1350    pub max_attempts: Option<u32>,
1351    pub backoff_seconds: Vec<u64>,
1352    pub non_retryable_error_types: Vec<String>,
1353}
1354
1355/// Options recorded with a child-workflow command.
1356///
1357/// The task queue is mandatory so routing is explicit and replay-stable.
1358#[derive(Clone, Debug, PartialEq, Eq)]
1359pub struct ChildWorkflowOptions {
1360    pub task_queue: String,
1361    pub parent_close_policy: ParentClosePolicy,
1362    pub cancellation_policy: CancellationPolicy,
1363    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1364    pub execution_timeout_seconds: Option<u64>,
1365    pub run_timeout_seconds: Option<u64>,
1366}
1367
1368impl ChildWorkflowOptions {
1369    pub fn new(task_queue: impl Into<String>) -> Self {
1370        Self {
1371            task_queue: task_queue.into(),
1372            parent_close_policy: ParentClosePolicy::Abandon,
1373            cancellation_policy: CancellationPolicy::Abandon,
1374            retry_policy: None,
1375            execution_timeout_seconds: None,
1376            run_timeout_seconds: None,
1377        }
1378    }
1379
1380    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1381        self.parent_close_policy = policy;
1382        self
1383    }
1384
1385    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1386        self.cancellation_policy = policy;
1387        self
1388    }
1389
1390    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1391        self.retry_policy = Some(policy);
1392        self
1393    }
1394
1395    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1396        self.execution_timeout_seconds = Some(seconds);
1397        self
1398    }
1399
1400    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1401        self.run_timeout_seconds = Some(seconds);
1402        self
1403    }
1404}
1405
1406/// Backoff intervals for one durable activity retry policy.
1407#[derive(Clone, Debug, PartialEq, Eq)]
1408pub enum ActivityBackoff {
1409    /// Use these intervals between attempts. The server repeats the final
1410    /// interval if the retry budget contains more attempts than entries.
1411    Explicit(Vec<Duration>),
1412    /// Generate one interval for every retry using integer exponential growth.
1413    Exponential {
1414        initial_interval: Duration,
1415        coefficient: u32,
1416        maximum_interval: Option<Duration>,
1417    },
1418}
1419
1420/// Durable server-side retry policy for one activity execution.
1421#[derive(Clone, Debug, Default, PartialEq, Eq)]
1422pub struct ActivityRetryPolicy {
1423    pub max_attempts: Option<u32>,
1424    pub backoff: Option<ActivityBackoff>,
1425    pub non_retryable_error_types: Vec<String>,
1426}
1427
1428impl ActivityRetryPolicy {
1429    /// Start a policy with a finite attempt budget, including the first attempt.
1430    pub fn new(max_attempts: u32) -> Self {
1431        Self {
1432            max_attempts: Some(max_attempts),
1433            ..Self::default()
1434        }
1435    }
1436
1437    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1438        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1439        self
1440    }
1441
1442    pub fn exponential_backoff(
1443        mut self,
1444        initial_interval: Duration,
1445        coefficient: u32,
1446        maximum_interval: Option<Duration>,
1447    ) -> Self {
1448        self.backoff = Some(ActivityBackoff::Exponential {
1449            initial_interval,
1450            coefficient,
1451            maximum_interval,
1452        });
1453        self
1454    }
1455
1456    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1457        self.non_retryable_error_types.push(error_type.into());
1458        self
1459    }
1460
1461    pub fn non_retryable_error_types(
1462        mut self,
1463        error_types: impl IntoIterator<Item = impl Into<String>>,
1464    ) -> Self {
1465        self.non_retryable_error_types
1466            .extend(error_types.into_iter().map(Into::into));
1467        self
1468    }
1469}
1470
1471/// Options recorded atomically on one deterministic `schedule_activity` command.
1472///
1473/// Durations are rounded up to whole seconds when encoded, so the server never
1474/// receives a shorter timeout or backoff than the caller requested.
1475#[derive(Clone, Debug, Default, PartialEq, Eq)]
1476pub struct ActivityOptions {
1477    pub task_queue: Option<String>,
1478    pub retry_policy: Option<ActivityRetryPolicy>,
1479    pub start_to_close_timeout: Option<Duration>,
1480    pub schedule_to_start_timeout: Option<Duration>,
1481    pub schedule_to_close_timeout: Option<Duration>,
1482    pub heartbeat_timeout: Option<Duration>,
1483    pub cancellation_policy: Option<CancellationPolicy>,
1484}
1485
1486impl ActivityOptions {
1487    pub fn new() -> Self {
1488        Self::default()
1489    }
1490
1491    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1492        self.task_queue = Some(task_queue.into());
1493        self
1494    }
1495
1496    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1497        self.retry_policy = Some(policy);
1498        self
1499    }
1500
1501    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1502        self.start_to_close_timeout = Some(timeout);
1503        self
1504    }
1505
1506    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1507        self.schedule_to_start_timeout = Some(timeout);
1508        self
1509    }
1510
1511    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1512        self.schedule_to_close_timeout = Some(timeout);
1513        self
1514    }
1515
1516    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1517        self.heartbeat_timeout = Some(timeout);
1518        self
1519    }
1520
1521    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1522        self.cancellation_policy = Some(policy);
1523        self
1524    }
1525
1526    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1527        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1528            && self.schedule_to_close_timeout.is_none()
1529        {
1530            return Err(ActivityOptionsError::new(
1531                ActivityOptionsErrorKind::MissingTotalTimeout,
1532                Some("schedule_to_close_timeout"),
1533                "remote Activity Abandon requires a finite positive total timeout",
1534            ));
1535        }
1536        if self
1537            .task_queue
1538            .as_deref()
1539            .is_some_and(|queue| queue.trim().is_empty())
1540        {
1541            return Err(ActivityOptionsError::new(
1542                ActivityOptionsErrorKind::EmptyTaskQueue,
1543                Some("task_queue"),
1544                "task_queue must not be empty",
1545            ));
1546        }
1547
1548        for (field, value) in [
1549            ("start_to_close_timeout", self.start_to_close_timeout),
1550            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1551            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1552            ("heartbeat_timeout", self.heartbeat_timeout),
1553        ] {
1554            if value.is_some_and(|value| value.is_zero()) {
1555                return Err(ActivityOptionsError::new(
1556                    ActivityOptionsErrorKind::TimeoutNotPositive,
1557                    Some(field),
1558                    format!("{field} must be positive"),
1559                ));
1560            }
1561        }
1562
1563        validate_timeout_order(
1564            "heartbeat_timeout",
1565            self.heartbeat_timeout,
1566            "start_to_close_timeout",
1567            self.start_to_close_timeout,
1568        )?;
1569        validate_timeout_order(
1570            "start_to_close_timeout",
1571            self.start_to_close_timeout,
1572            "schedule_to_close_timeout",
1573            self.schedule_to_close_timeout,
1574        )?;
1575        validate_timeout_order(
1576            "schedule_to_start_timeout",
1577            self.schedule_to_start_timeout,
1578            "schedule_to_close_timeout",
1579            self.schedule_to_close_timeout,
1580        )?;
1581
1582        Ok(ValidatedActivityOptions {
1583            task_queue: self.task_queue.clone(),
1584            retry_policy: self
1585                .retry_policy
1586                .as_ref()
1587                .map(validate_activity_retry_policy)
1588                .transpose()?,
1589            start_to_close_timeout: timeout_seconds(
1590                "start_to_close_timeout",
1591                self.start_to_close_timeout,
1592            )?,
1593            schedule_to_start_timeout: timeout_seconds(
1594                "schedule_to_start_timeout",
1595                self.schedule_to_start_timeout,
1596            )?,
1597            schedule_to_close_timeout: timeout_seconds(
1598                "schedule_to_close_timeout",
1599                self.schedule_to_close_timeout,
1600            )?,
1601            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1602            cancellation_policy: self.cancellation_policy,
1603        })
1604    }
1605}
1606
1607/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1608///
1609/// Constructors capture arguments but perform no I/O. The join validates the
1610/// complete tree, attaches the existing parallel-group metadata to every
1611/// ordinary command, schedules all leaves, and then suspends.
1612pub enum ParallelOperation {
1613    Activity {
1614        activity_type: String,
1615        options: ActivityOptions,
1616        arguments: Result<AvroValue>,
1617    },
1618    ChildWorkflow {
1619        workflow_type: String,
1620        options: ChildWorkflowOptions,
1621        arguments: Result<AvroValue>,
1622    },
1623    Timer(Duration),
1624    Signal(String),
1625    Condition {
1626        options: ConditionWaitOptions,
1627        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1628    },
1629    Group(Vec<ParallelOperation>),
1630}
1631
1632impl ParallelOperation {
1633    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1634        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1635    }
1636
1637    pub fn activity_with_options<T: Serialize>(
1638        activity_type: impl Into<String>,
1639        options: ActivityOptions,
1640        args: T,
1641    ) -> Self {
1642        Self::Activity {
1643            activity_type: activity_type.into(),
1644            options,
1645            arguments: AvroValue::from_serialize(&args),
1646        }
1647    }
1648
1649    pub fn child_workflow<T: Serialize>(
1650        workflow_type: impl Into<String>,
1651        options: ChildWorkflowOptions,
1652        args: T,
1653    ) -> Self {
1654        Self::ChildWorkflow {
1655            workflow_type: workflow_type.into(),
1656            options,
1657            arguments: AvroValue::from_serialize(&args),
1658        }
1659    }
1660
1661    pub fn timer(duration: Duration) -> Self {
1662        Self::Timer(duration)
1663    }
1664
1665    pub fn signal(signal_name: impl Into<String>) -> Self {
1666        Self::Signal(signal_name.into())
1667    }
1668
1669    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1670    where
1671        F: Fn() -> Result<bool> + Send + 'static,
1672    {
1673        Self::Condition {
1674            options,
1675            predicate: Box::new(predicate),
1676        }
1677    }
1678
1679    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1680        Self::Group(operations)
1681    }
1682}
1683
1684#[derive(Clone, Debug)]
1685struct ValidatedActivityOptions {
1686    task_queue: Option<String>,
1687    retry_policy: Option<Value>,
1688    start_to_close_timeout: Option<u64>,
1689    schedule_to_start_timeout: Option<u64>,
1690    schedule_to_close_timeout: Option<u64>,
1691    heartbeat_timeout: Option<u64>,
1692    cancellation_policy: Option<CancellationPolicy>,
1693}
1694
1695fn validate_timeout_order(
1696    smaller_name: &'static str,
1697    smaller: Option<Duration>,
1698    larger_name: &'static str,
1699    larger: Option<Duration>,
1700) -> std::result::Result<(), ActivityOptionsError> {
1701    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1702        return Err(ActivityOptionsError::new(
1703            ActivityOptionsErrorKind::TimeoutOrder,
1704            Some(smaller_name),
1705            format!("{smaller_name} must be <= {larger_name}"),
1706        ));
1707    }
1708    Ok(())
1709}
1710
1711fn timeout_seconds(
1712    field: &'static str,
1713    value: Option<Duration>,
1714) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1715    value
1716        .map(|value| {
1717            activity_protocol_seconds(value).ok_or_else(|| {
1718                ActivityOptionsError::new(
1719                    ActivityOptionsErrorKind::TimeoutOverflow,
1720                    Some(field),
1721                    format!("{field} is too large for the worker protocol"),
1722                )
1723            })
1724        })
1725        .transpose()
1726}
1727
1728fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1729    value
1730        .as_secs()
1731        .checked_add(u64::from(value.subsec_nanos() > 0))
1732}
1733
1734fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1735    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1736}
1737
1738fn validate_activity_retry_policy(
1739    policy: &ActivityRetryPolicy,
1740) -> std::result::Result<Value, ActivityOptionsError> {
1741    if policy.max_attempts.is_none()
1742        && policy.backoff.is_none()
1743        && policy.non_retryable_error_types.is_empty()
1744    {
1745        return Err(ActivityOptionsError::new(
1746            ActivityOptionsErrorKind::EmptyRetryPolicy,
1747            Some("retry_policy"),
1748            "retry_policy must configure at least one field",
1749        ));
1750    }
1751    if policy.max_attempts == Some(0) {
1752        return Err(ActivityOptionsError::new(
1753            ActivityOptionsErrorKind::InvalidMaxAttempts,
1754            Some("retry_policy.max_attempts"),
1755            "max_attempts must be >= 1",
1756        ));
1757    }
1758    if policy
1759        .non_retryable_error_types
1760        .iter()
1761        .any(|error_type| error_type.trim().is_empty())
1762    {
1763        return Err(ActivityOptionsError::new(
1764            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1765            Some("retry_policy.non_retryable_error_types"),
1766            "non_retryable_error_types must not contain empty values",
1767        ));
1768    }
1769
1770    let backoff_seconds = match &policy.backoff {
1771        None => None,
1772        Some(backoff) => {
1773            let max_attempts = policy.max_attempts.ok_or_else(|| {
1774                ActivityOptionsError::new(
1775                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1776                    Some("retry_policy.backoff"),
1777                    "backoff requires max_attempts",
1778                )
1779            })?;
1780            let retry_count = max_attempts.saturating_sub(1) as usize;
1781            let intervals = match backoff {
1782                ActivityBackoff::Explicit(intervals) => {
1783                    if intervals.len() > retry_count {
1784                        return Err(ActivityOptionsError::new(
1785                            ActivityOptionsErrorKind::TooManyBackoffIntervals,
1786                            Some("retry_policy.backoff"),
1787                            "backoff interval count must not exceed max_attempts - 1",
1788                        ));
1789                    }
1790                    intervals.clone()
1791                }
1792                ActivityBackoff::Exponential {
1793                    initial_interval,
1794                    coefficient,
1795                    maximum_interval,
1796                } => {
1797                    if *coefficient < 1 {
1798                        return Err(ActivityOptionsError::new(
1799                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1800                            Some("retry_policy.backoff.coefficient"),
1801                            "backoff coefficient must be >= 1",
1802                        ));
1803                    }
1804                    if retry_count > 10_000 {
1805                        return Err(ActivityOptionsError::new(
1806                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1807                            Some("retry_policy.max_attempts"),
1808                            "generated backoff supports at most 10000 retry intervals",
1809                        ));
1810                    }
1811                    let mut current = *initial_interval;
1812                    let mut intervals = Vec::with_capacity(retry_count);
1813                    for _ in 0..retry_count {
1814                        let interval = maximum_interval
1815                            .map(|maximum| current.min(maximum))
1816                            .unwrap_or(current);
1817                        intervals.push(interval);
1818                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1819                            break;
1820                        }
1821                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1822                            ActivityOptionsError::new(
1823                                ActivityOptionsErrorKind::BackoffOverflow,
1824                                Some("retry_policy.backoff"),
1825                                "generated backoff interval overflowed",
1826                            )
1827                        })?;
1828                    }
1829                    intervals
1830                }
1831            };
1832            Some(
1833                intervals
1834                    .into_iter()
1835                    .map(|interval| {
1836                        activity_protocol_seconds(interval).ok_or_else(|| {
1837                            ActivityOptionsError::new(
1838                                ActivityOptionsErrorKind::BackoffOverflow,
1839                                Some("retry_policy.backoff"),
1840                                "backoff interval is too large for the worker protocol",
1841                            )
1842                        })
1843                    })
1844                    .collect::<std::result::Result<Vec<_>, _>>()?,
1845            )
1846        }
1847    };
1848
1849    let mut encoded = serde_json::Map::new();
1850    if let Some(max_attempts) = policy.max_attempts {
1851        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1852    }
1853    if let Some(backoff_seconds) = backoff_seconds {
1854        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1855    }
1856    if !policy.non_retryable_error_types.is_empty() {
1857        let mut canonical_error_types = Vec::new();
1858        for error_type in policy
1859            .non_retryable_error_types
1860            .iter()
1861            .map(|error_type| error_type.trim())
1862        {
1863            if !canonical_error_types.contains(&error_type) {
1864                canonical_error_types.push(error_type);
1865            }
1866        }
1867        encoded.insert(
1868            "non_retryable_error_types".to_string(),
1869            json!(canonical_error_types),
1870        );
1871    }
1872    Ok(Value::Object(encoded))
1873}
1874
1875/// A stable, machine-readable failure raised when workflow code no longer
1876/// reconstructs the durable command stream recorded in history.
1877#[derive(Clone, Debug, Error)]
1878#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1879pub struct ReplayFailure {
1880    pub reason: String,
1881    pub sequence: Option<u64>,
1882    pub expected: Option<String>,
1883    pub actual: Option<String>,
1884    pub message: String,
1885}
1886
1887impl ReplayFailure {
1888    fn new(
1889        reason: impl Into<String>,
1890        sequence: Option<u64>,
1891        expected: Option<String>,
1892        actual: Option<String>,
1893        message: impl Into<String>,
1894    ) -> Self {
1895        Self {
1896            reason: reason.into(),
1897            sequence,
1898            expected,
1899            actual,
1900            message: message.into(),
1901        }
1902    }
1903}
1904
1905/// A stable, machine-readable workflow query or query-task settlement failure.
1906#[derive(Clone, Debug, Error)]
1907#[error("query failed ({reason}, HTTP {status}): {message}")]
1908pub struct QueryFailure {
1909    pub status: u16,
1910    pub reason: String,
1911    pub message: String,
1912    pub body: Value,
1913}
1914
1915/// A stable failure returned when a server rejects an SDK protocol version.
1916#[derive(Clone, Debug, Error)]
1917#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
1918pub struct ProtocolFailure {
1919    pub status: u16,
1920    pub reason: String,
1921    pub message: String,
1922    pub supported_version: Option<String>,
1923    pub requested_version: Option<String>,
1924    pub body: Value,
1925}
1926
1927#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1928pub struct PayloadEnvelope {
1929    pub codec: String,
1930    pub blob: String,
1931}
1932
1933impl PayloadEnvelope {
1934    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
1935        encode_payload(value, DEFAULT_CODEC)
1936    }
1937
1938    /// Encode an explicit typed value, including the bytes branch that JSON
1939    /// serialization cannot represent.
1940    pub fn avro_value(value: &AvroValue) -> Result<Self> {
1941        encode_avro_value(value)
1942    }
1943}
1944
1945/// Native adapter for the fixed language-neutral Avro Value schema.
1946#[derive(Clone, Debug)]
1947pub enum AvroValue {
1948    Null,
1949    Boolean(bool),
1950    Long(i64),
1951    Double(f64),
1952    Bytes(Vec<u8>),
1953    String(String),
1954    Array(Vec<AvroValue>),
1955    Map(BTreeMap<String, AvroValue>),
1956}
1957
1958impl PartialEq for AvroValue {
1959    fn eq(&self, other: &Self) -> bool {
1960        match (self, other) {
1961            (Self::Null, Self::Null) => true,
1962            (Self::Boolean(left), Self::Boolean(right)) => left == right,
1963            (Self::Long(left), Self::Long(right)) => left == right,
1964            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
1965            (Self::Bytes(left), Self::Bytes(right)) => left == right,
1966            (Self::String(left), Self::String(right)) => left == right,
1967            (Self::Array(left), Self::Array(right)) => left == right,
1968            (Self::Map(left), Self::Map(right)) => left == right,
1969            _ => false,
1970        }
1971    }
1972}
1973
1974impl AvroValue {
1975    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
1976        Self::from_serde_value(
1977            serde_value::to_value(value).map_err(|error| {
1978                Error::Codec(format!("could not adapt value for Avro: {error}"))
1979            })?,
1980        )
1981    }
1982
1983    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
1984        use serde_value::Value as SerdeValue;
1985
1986        match value {
1987            SerdeValue::Unit => Ok(Self::Null),
1988            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
1989            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
1990            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
1991            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
1992            SerdeValue::I64(value) => Ok(Self::Long(value)),
1993            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
1994            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
1995            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
1996            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
1997                Error::Codec(
1998                    "integer_overflow: Avro Value long must be within signed 64-bit range"
1999                        .to_string(),
2000                )
2001            }),
2002            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2003            SerdeValue::F64(value) => Self::finite_double(value),
2004            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2005            SerdeValue::String(value) => Ok(Self::String(value)),
2006            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2007            SerdeValue::Option(None) => Ok(Self::Null),
2008            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2009                Self::from_serde_value(*value)
2010            }
2011            SerdeValue::Seq(values) => values
2012                .into_iter()
2013                .map(Self::from_serde_value)
2014                .collect::<Result<Vec<_>>>()
2015                .map(Self::Array),
2016            SerdeValue::Map(values) => values
2017                .into_iter()
2018                .map(|(key, value)| {
2019                    let SerdeValue::String(key) = key else {
2020                        return Err(Error::Codec(
2021                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2022                        ));
2023                    };
2024
2025                    Ok((key, Self::from_serde_value(value)?))
2026                })
2027                .collect::<Result<BTreeMap<_, _>>>()
2028                .map(Self::Map),
2029        }
2030    }
2031
2032    fn finite_double(value: f64) -> Result<Self> {
2033        if !value.is_finite() {
2034            return Err(Error::Codec(
2035                "non_finite_float: Avro Value doubles must be finite".to_string(),
2036            ));
2037        }
2038
2039        Ok(Self::Double(value))
2040    }
2041
2042    fn into_json(self) -> Result<Value> {
2043        match self {
2044            Self::Null => Ok(Value::Null),
2045            Self::Boolean(value) => Ok(Value::Bool(value)),
2046            Self::Long(value) => Ok(Value::Number(value.into())),
2047            Self::Double(value) => serde_json::Number::from_f64(value)
2048                .map(Value::Number)
2049                .ok_or_else(|| {
2050                    Error::Codec(
2051                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2052                    )
2053                }),
2054            Self::Bytes(value) => Ok(json!({
2055                "$type": "bytes",
2056                "base64": BASE64.encode(value),
2057            })),
2058            Self::String(value) => Ok(Value::String(value)),
2059            Self::Array(values) => values
2060                .into_iter()
2061                .map(Self::into_json)
2062                .collect::<Result<Vec<_>>>()
2063                .map(Value::Array),
2064            Self::Map(values) => values
2065                .into_iter()
2066                .map(|(key, value)| Ok((key, value.into_json()?)))
2067                .collect::<Result<serde_json::Map<_, _>>>()
2068                .map(Value::Object),
2069        }
2070    }
2071
2072    fn into_serde_value(self) -> serde_value::Value {
2073        use serde_value::Value as SerdeValue;
2074
2075        match self {
2076            Self::Null => SerdeValue::Unit,
2077            Self::Boolean(value) => SerdeValue::Bool(value),
2078            Self::Long(value) => SerdeValue::I64(value),
2079            Self::Double(value) => SerdeValue::F64(value),
2080            Self::Bytes(value) => SerdeValue::Bytes(value),
2081            Self::String(value) => SerdeValue::String(value),
2082            Self::Array(values) => {
2083                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2084            }
2085            Self::Map(values) => SerdeValue::Map(
2086                values
2087                    .into_iter()
2088                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2089                    .collect(),
2090            ),
2091        }
2092    }
2093
2094    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2095        self.into_serde_value().deserialize_into().map_err(|error| {
2096            Error::Codec(format!(
2097                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2098            ))
2099        })
2100    }
2101}
2102
2103impl Serialize for AvroValue {
2104    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2105    where
2106        S: Serializer,
2107    {
2108        match self {
2109            Self::Null => serializer.serialize_unit(),
2110            Self::Boolean(value) => serializer.serialize_bool(*value),
2111            Self::Long(value) => serializer.serialize_i64(*value),
2112            Self::Double(value) => serializer.serialize_f64(*value),
2113            Self::Bytes(value) => serializer.serialize_bytes(value),
2114            Self::String(value) => serializer.serialize_str(value),
2115            Self::Array(values) => {
2116                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2117                for value in values {
2118                    sequence.serialize_element(value)?;
2119                }
2120                sequence.end()
2121            }
2122            Self::Map(values) => {
2123                let mut map = serializer.serialize_map(Some(values.len()))?;
2124                for (key, value) in values {
2125                    map.serialize_entry(key, value)?;
2126                }
2127                map.end()
2128            }
2129        }
2130    }
2131}
2132
2133pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2134    let datum = avro_value_to_datum(value)?;
2135    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2136        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2137    let mut bytes = Vec::with_capacity(datum.len() + 10);
2138    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2139    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2140    bytes.extend_from_slice(&datum);
2141    Ok(PayloadEnvelope {
2142        codec: DEFAULT_CODEC.to_string(),
2143        blob: BASE64.encode(bytes),
2144    })
2145}
2146
2147pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2148    if envelope.codec != DEFAULT_CODEC {
2149        return Err(unsupported_payload_codec(&envelope.codec));
2150    }
2151    decode_avro_value_blob(&envelope.blob)
2152}
2153
2154pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2155    let blob = match codec {
2156        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2157        other => return Err(unsupported_payload_codec(other)),
2158    };
2159
2160    Ok(PayloadEnvelope {
2161        codec: codec.to_string(),
2162        blob,
2163    })
2164}
2165
2166pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2167    match envelope.codec.as_str() {
2168        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2169        other => Err(unsupported_payload_codec(other)),
2170    }
2171}
2172
2173fn handler_type_error<T>(
2174    handler_kind: HandlerKind,
2175    handler_name: &str,
2176    value_kind: HandlerValueKind,
2177    message: impl Into<String>,
2178) -> Error {
2179    Error::HandlerType {
2180        handler_kind,
2181        handler_name: handler_name.to_string(),
2182        value_kind,
2183        rust_type: type_name::<T>(),
2184        message: message.into(),
2185    }
2186}
2187
2188fn decode_handler_input<T: DeserializeOwned>(
2189    arguments: AvroValue,
2190    handler_kind: HandlerKind,
2191    handler_name: &str,
2192) -> Result<T> {
2193    let argument = match arguments {
2194        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2195            arguments.pop().expect("one typed handler argument")
2196        }
2197        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2198        AvroValue::Array(arguments) => {
2199            return Err(handler_type_error::<T>(
2200                handler_kind,
2201                handler_name,
2202                HandlerValueKind::Input,
2203                format!(
2204                    "typed handlers accept one request value, but the task carried {} arguments",
2205                    arguments.len()
2206                ),
2207            ));
2208        }
2209        argument => argument,
2210    };
2211
2212    argument.deserialize().map_err(|error| {
2213        handler_type_error::<T>(
2214            handler_kind,
2215            handler_name,
2216            HandlerValueKind::Input,
2217            error.to_string(),
2218        )
2219    })
2220}
2221
2222fn encode_handler_result<T: Serialize>(
2223    result: &T,
2224    handler_kind: HandlerKind,
2225    handler_name: &str,
2226) -> Result<AvroValue> {
2227    AvroValue::from_serialize(result).map_err(|error| {
2228        handler_type_error::<T>(
2229            handler_kind,
2230            handler_name,
2231            HandlerValueKind::Result,
2232            error.to_string(),
2233        )
2234    })
2235}
2236
2237fn decode_handler_result<T: DeserializeOwned>(
2238    result: AvroValue,
2239    handler_kind: HandlerKind,
2240    handler_name: &str,
2241) -> Result<T> {
2242    result.deserialize().map_err(|error| {
2243        handler_type_error::<T>(
2244            handler_kind,
2245            handler_name,
2246            HandlerValueKind::Result,
2247            error.to_string(),
2248        )
2249    })
2250}
2251
2252#[cfg(test)]
2253fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2254    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2255}
2256
2257fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2258    validate_payload_codec(fallback_codec)?;
2259
2260    if value.is_null() {
2261        return Ok(Value::Null);
2262    }
2263
2264    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2265        return decode_blob(blob, codec);
2266    }
2267
2268    if let Some(blob) = value.as_str() {
2269        return decode_blob(blob, fallback_codec);
2270    }
2271
2272    Err(untagged_payload_value())
2273}
2274
2275fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2276    let envelope = match codec {
2277        DEFAULT_CODEC => encode_avro_value(value)?,
2278        other => return Err(unsupported_payload_codec(other)),
2279    };
2280    Ok(serde_json::to_value(envelope)?)
2281}
2282
2283fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2284    validate_payload_codec(fallback_codec)?;
2285
2286    if value.is_null() {
2287        return Ok(AvroValue::Null);
2288    }
2289
2290    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2291        validate_payload_codec(codec)?;
2292        return decode_avro_value_blob(blob);
2293    }
2294
2295    if let Some(blob) = value.as_str() {
2296        return match fallback_codec {
2297            DEFAULT_CODEC => decode_avro_value_blob(blob),
2298            other => Err(unsupported_payload_codec(other)),
2299        };
2300    }
2301
2302    Err(untagged_payload_value())
2303}
2304
2305fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2306    match value {
2307        AvroValue::Null => AvroValue::Array(Vec::new()),
2308        AvroValue::Array(_) => value,
2309        other => AvroValue::Array(vec![other]),
2310    }
2311}
2312
2313fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2314    match codec {
2315        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2316        other => Err(unsupported_payload_codec(other)),
2317    }
2318}
2319
2320fn validate_payload_codec(codec: &str) -> Result<()> {
2321    match codec {
2322        DEFAULT_CODEC => Ok(()),
2323        MISSING_TASK_PAYLOAD_CODEC => {
2324            Err(invalid_task_payload_codec("task payload_codec is missing"))
2325        }
2326        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2327        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2328            "task payload_codec must be a string",
2329        )),
2330        other => Err(unsupported_payload_codec(other)),
2331    }
2332}
2333
2334fn invalid_task_payload_codec(reason: &str) -> Error {
2335    Error::Codec(format!(
2336        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2337    ))
2338}
2339
2340fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2341    let Some(object) = value.as_object() else {
2342        return Ok(None);
2343    };
2344    if !object.contains_key("codec") && !object.contains_key("blob") {
2345        return Ok(None);
2346    }
2347
2348    let codec = object
2349        .get("codec")
2350        .and_then(Value::as_str)
2351        .ok_or_else(invalid_payload_envelope)?;
2352    validate_payload_codec(codec)?;
2353    let blob = object
2354        .get("blob")
2355        .and_then(Value::as_str)
2356        .ok_or_else(invalid_payload_envelope)?;
2357    Ok(Some((codec, blob)))
2358}
2359
2360fn invalid_payload_envelope() -> Error {
2361    Error::Codec(
2362        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2363            .to_string(),
2364    )
2365}
2366
2367fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2368    for command in commands {
2369        let Some(command) = command.as_object() else {
2370            continue;
2371        };
2372        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2373            continue;
2374        };
2375        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2376            continue;
2377        };
2378
2379        if let Some(codec) = command.get("payload_codec") {
2380            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2381            validate_payload_codec(codec)?;
2382        }
2383
2384        let payload = command
2385            .get(payload_field)
2386            .ok_or_else(invalid_payload_envelope)?;
2387        if runtime_payloads::Reference::parse(payload)?.is_none() {
2388            validate_outbound_payload_envelope(payload)?;
2389        }
2390    }
2391    Ok(())
2392}
2393
2394fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2395    if commands.iter().any(|command| {
2396        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2397            && command
2398                .get("condition_wait_occurrence_id")
2399                .and_then(Value::as_str)
2400                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2401    }) {
2402        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2403    } else if commands.iter().any(|command| {
2404        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2405            && command.get("attribute_types").is_some()
2406    }) {
2407        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2408    } else if commands
2409        .iter()
2410        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2411    {
2412        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2413    } else if commands
2414        .iter()
2415        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2416    {
2417        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2418    } else if commands.iter().any(|command| {
2419        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2420    }) {
2421        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2422    } else {
2423        WORKER_PROTOCOL_VERSION
2424    }
2425}
2426
2427fn workflow_completion_protocol_version_with_message_streams(
2428    commands: &[Value],
2429    has_message_stream_metadata: bool,
2430) -> &'static str {
2431    let command_protocol = workflow_completion_protocol_version(commands);
2432    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2433        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2434    } else {
2435        command_protocol
2436    }
2437}
2438
2439fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2440    match command_type {
2441        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2442        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2443        "start_service_operation" => Some("request_payload"),
2444        "upsert_memo" => Some("entries"),
2445        _ => None,
2446    }
2447}
2448
2449fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2450    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2451        return Err(untagged_payload_value());
2452    };
2453    validate_payload_codec(codec)?;
2454    decode_avro_value_blob(blob)?;
2455    Ok(())
2456}
2457
2458fn unsupported_payload_codec(codec: &str) -> Error {
2459    Error::Codec(format!(
2460        "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"
2461    ))
2462}
2463
2464fn untagged_payload_value() -> Error {
2465    Error::Codec(
2466        "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"
2467            .to_string(),
2468    )
2469}
2470
2471fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2472    let bytes = BASE64.decode(blob).map_err(|err| {
2473        Error::Codec(format!(
2474            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2475        ))
2476    })?;
2477
2478    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2479        return Err(unsupported_payload_codec("json"));
2480    }
2481
2482    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2483        return Err(Error::Codec(
2484            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2485        ));
2486    }
2487
2488    let fingerprint: [u8; 8] = bytes[2..10]
2489        .try_into()
2490        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2491    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2492        return Err(Error::Codec(format!(
2493            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2494            fingerprint
2495                .iter()
2496                .map(|byte| format!("{byte:02x}"))
2497                .collect::<String>()
2498        )));
2499    }
2500
2501    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2502    // The current fingerprint selects the current immutable schema, so reader
2503    // resolution would only re-walk the same recursive union. Future retained
2504    // writer fingerprints supply a distinct reader schema in this branch.
2505    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2506    if datum_reader.truncated {
2507        return Err(Error::Codec(
2508            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2509        ));
2510    }
2511    let datum = datum.map_err(|err| {
2512        Error::Codec(format!(
2513            "invalid_payload_framing: malformed Avro Value datum: {err}"
2514        ))
2515    })?;
2516    if datum_reader.remaining() != 0 {
2517        return Err(Error::Codec(format!(
2518            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2519            datum_reader.remaining()
2520        )));
2521    }
2522    avro_value_from_datum(datum)
2523}
2524
2525struct StrictAvroDatumReader<'a> {
2526    bytes: &'a [u8],
2527    offset: usize,
2528    truncated: bool,
2529}
2530
2531impl<'a> StrictAvroDatumReader<'a> {
2532    fn new(bytes: &'a [u8]) -> Self {
2533        Self {
2534            bytes,
2535            offset: 0,
2536            truncated: false,
2537        }
2538    }
2539
2540    fn remaining(&self) -> usize {
2541        self.bytes.len() - self.offset
2542    }
2543}
2544
2545impl Read for StrictAvroDatumReader<'_> {
2546    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2547        let count = buffer.len().min(self.remaining());
2548        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2549        self.offset += count;
2550        if count < buffer.len() {
2551            self.truncated = true;
2552        }
2553
2554        Ok(count)
2555    }
2556}
2557
2558fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2559    let branch = match value {
2560        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2561        AvroValue::Boolean(value) => AvroDatum::Union(
2562            1,
2563            Box::new(AvroDatum::Record(vec![(
2564                "boolean".to_string(),
2565                AvroDatum::Boolean(*value),
2566            )])),
2567        ),
2568        AvroValue::Long(value) => AvroDatum::Union(
2569            2,
2570            Box::new(AvroDatum::Record(vec![(
2571                "long".to_string(),
2572                AvroDatum::Long(*value),
2573            )])),
2574        ),
2575        AvroValue::Double(value) => {
2576            if !value.is_finite() {
2577                return Err(Error::Codec(
2578                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2579                ));
2580            }
2581            AvroDatum::Union(
2582                3,
2583                Box::new(AvroDatum::Record(vec![(
2584                    "double".to_string(),
2585                    AvroDatum::Double(*value),
2586                )])),
2587            )
2588        }
2589        AvroValue::Bytes(value) => AvroDatum::Union(
2590            4,
2591            Box::new(AvroDatum::Record(vec![(
2592                "bytes".to_string(),
2593                AvroDatum::Bytes(value.clone()),
2594            )])),
2595        ),
2596        AvroValue::String(value) => AvroDatum::Union(
2597            5,
2598            Box::new(AvroDatum::Record(vec![(
2599                "string".to_string(),
2600                AvroDatum::String(value.clone()),
2601            )])),
2602        ),
2603        AvroValue::Array(values) => AvroDatum::Union(
2604            6,
2605            Box::new(AvroDatum::Record(vec![(
2606                "items".to_string(),
2607                AvroDatum::Array(
2608                    values
2609                        .iter()
2610                        .map(avro_value_to_datum)
2611                        .collect::<Result<Vec<_>>>()?,
2612                ),
2613            )])),
2614        ),
2615        AvroValue::Map(values) => AvroDatum::Union(
2616            7,
2617            Box::new(AvroDatum::Record(vec![(
2618                "entries".to_string(),
2619                AvroDatum::Array(
2620                    values
2621                        .iter()
2622                        .map(|(key, value)| {
2623                            Ok(AvroDatum::Record(vec![
2624                                ("key".to_string(), AvroDatum::String(key.clone())),
2625                                ("value".to_string(), avro_value_to_datum(value)?),
2626                            ]))
2627                        })
2628                        .collect::<Result<Vec<_>>>()?,
2629                ),
2630            )])),
2631        ),
2632    };
2633    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2634}
2635
2636fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2637    let AvroDatum::Record(mut outer) = datum else {
2638        return Err(Error::Codec(
2639            "invalid_payload_framing: datum is not a Value record".to_string(),
2640        ));
2641    };
2642    let (_, branch) = outer
2643        .pop()
2644        .filter(|(name, _)| name == "value")
2645        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2646    let AvroDatum::Union(_, branch) = branch else {
2647        return Err(Error::Codec(
2648            "invalid_payload_framing: invalid Value union".to_string(),
2649        ));
2650    };
2651    match *branch {
2652        AvroDatum::Null => Ok(AvroValue::Null),
2653        AvroDatum::Record(mut fields) => {
2654            let (name, value) = fields.pop().ok_or_else(|| {
2655                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2656            })?;
2657            match (name.as_str(), value) {
2658                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2659                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2660                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2661                    Ok(AvroValue::Double(value))
2662                }
2663                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2664                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2665                ("items", AvroDatum::Array(values)) => values
2666                    .into_iter()
2667                    .map(avro_value_from_datum)
2668                    .collect::<Result<Vec<_>>>()
2669                    .map(AvroValue::Array),
2670                ("entries", AvroDatum::Map(values)) => values
2671                    .into_iter()
2672                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2673                    .collect::<Result<BTreeMap<_, _>>>()
2674                    .map(AvroValue::Map),
2675                _ => Err(Error::Codec(
2676                    "invalid_payload_framing: unknown Value branch".to_string(),
2677                )),
2678            }
2679        }
2680        _ => Err(Error::Codec(
2681            "invalid_payload_framing: invalid Value branch".to_string(),
2682        )),
2683    }
2684}
2685
2686fn avro_value_schema() -> Result<&'static Schema> {
2687    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2688        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2689            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2690    }) {
2691        Ok(schema) => Ok(schema),
2692        Err(message) => Err(Error::Codec(message.clone())),
2693    }
2694}
2695
2696fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2697    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2698        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2699        // have the same block representation when each ordered array record
2700        // contains the map key followed by its value, so this encoding-only
2701        // adaptation lets the official encoder retain BTreeMap wire order.
2702        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2703            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2704        let entries_schema = schema
2705            .pointer_mut("/fields/0/type/7/fields/0/type")
2706            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2707        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2708            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2709        }
2710        *entries_schema = json!({
2711            "type": "array",
2712            "items": {
2713                "type": "record",
2714                "name": "MapEntry",
2715                "fields": [
2716                    {"name": "key", "type": "string"},
2717                    {"name": "value", "type": "Value"}
2718                ]
2719            }
2720        });
2721        Schema::parse_str(&schema.to_string())
2722            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2723    }) {
2724        Ok(schema) => Ok(schema),
2725        Err(message) => Err(Error::Codec(message.clone())),
2726    }
2727}
2728
2729#[derive(Clone, Debug)]
2730pub struct Client {
2731    http: reqwest::Client,
2732    base_url: String,
2733    token: Option<String>,
2734    control_token: Option<String>,
2735    worker_token: Option<String>,
2736    namespace: String,
2737    max_external_payload_bytes: usize,
2738    worker_storage_admission: Option<WorkerStorageAdmission>,
2739    cooperative_worker_protocol: bool,
2740    local_activities_enabled: bool,
2741    worker_sessions_enabled: bool,
2742    max_concurrent_worker_sessions: usize,
2743    worker_build_id: Option<String>,
2744    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2745    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2746}
2747
2748impl Client {
2749    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2750        Self::builder(base_url).build()
2751    }
2752
2753    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2754        ClientBuilder {
2755            base_url: base_url.into(),
2756            token: None,
2757            control_token: None,
2758            worker_token: None,
2759            namespace: "default".to_string(),
2760            timeout: Duration::from_secs(60),
2761            max_external_payload_bytes: 64 * 1024 * 1024,
2762        }
2763    }
2764
2765    pub async fn health(&self) -> Result<Value> {
2766        self.request_json(
2767            reqwest::Method::GET,
2768            "/health",
2769            RequestProtocol::ControlPlane,
2770            Option::<&Value>::None,
2771        )
2772        .await
2773    }
2774
2775    pub async fn cluster_info(&self) -> Result<Value> {
2776        self.request_json(
2777            reqwest::Method::GET,
2778            "/cluster/info",
2779            RequestProtocol::ControlPlane,
2780            Option::<&Value>::None,
2781        )
2782        .await
2783    }
2784
2785    pub async fn start_workflow<T: Serialize>(
2786        &self,
2787        workflow_type: &str,
2788        task_queue: &str,
2789        workflow_id: &str,
2790        input: T,
2791    ) -> Result<WorkflowHandle> {
2792        self.start_workflow_with_options(
2793            workflow_type,
2794            task_queue,
2795            workflow_id,
2796            WorkflowStartOptions::default(),
2797            input,
2798        )
2799        .await
2800    }
2801
2802    /// Start a workflow with explicit server-enforced execution and run
2803    /// deadlines.
2804    pub async fn start_workflow_with_options<T: Serialize>(
2805        &self,
2806        workflow_type: &str,
2807        task_queue: &str,
2808        workflow_id: &str,
2809        options: WorkflowStartOptions,
2810        input: T,
2811    ) -> Result<WorkflowHandle> {
2812        options.validate()?;
2813        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2814        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2815        let body = json!({
2816            "workflow_id": workflow_id,
2817            "workflow_type": workflow_type,
2818            "task_queue": task_queue,
2819            "input": input_envelope,
2820            "execution_timeout_seconds": options.execution_timeout_seconds,
2821            "run_timeout_seconds": options.run_timeout_seconds
2822        });
2823
2824        let data: Value = self
2825            .request_json(
2826                reqwest::Method::POST,
2827                "/workflows",
2828                RequestProtocol::ControlPlane,
2829                Some(&body),
2830            )
2831            .await?;
2832
2833        Ok(WorkflowHandle {
2834            client: self.clone(),
2835            workflow_id: data
2836                .get("workflow_id")
2837                .and_then(Value::as_str)
2838                .unwrap_or(workflow_id)
2839                .to_string(),
2840            run_id: data
2841                .get("run_id")
2842                .and_then(Value::as_str)
2843                .map(str::to_string),
2844            workflow_type: data
2845                .get("workflow_type")
2846                .and_then(Value::as_str)
2847                .unwrap_or(workflow_type)
2848                .to_string(),
2849        })
2850    }
2851
2852    pub async fn signal_workflow<T: Serialize>(
2853        &self,
2854        workflow_id: &str,
2855        signal_name: &str,
2856        input: T,
2857    ) -> Result<Value> {
2858        self.signal_workflow_target(workflow_id, None, signal_name, input)
2859            .await
2860    }
2861
2862    /// Append one idempotently identified item to an instance-scoped input stream.
2863    pub async fn append_message_stream<T: Serialize>(
2864        &self,
2865        workflow_id: &str,
2866        stream_name: &str,
2867        message_id: &str,
2868        input: T,
2869    ) -> Result<Value> {
2870        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2871        let body = json!({
2872            "message_id": message_id,
2873            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2874        });
2875        self.request_json(
2876            reqwest::Method::POST,
2877            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2878            RequestProtocol::ControlPlane,
2879            Some(&body),
2880        )
2881        .await
2882    }
2883
2884    /// Signal only if `run_id` is still the current run for this instance.
2885    pub async fn signal_workflow_run<T: Serialize>(
2886        &self,
2887        workflow_id: &str,
2888        run_id: &str,
2889        signal_name: &str,
2890        input: T,
2891    ) -> Result<Value> {
2892        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2893            .await
2894    }
2895
2896    async fn signal_workflow_target<T: Serialize>(
2897        &self,
2898        workflow_id: &str,
2899        run_id: Option<&str>,
2900        signal_name: &str,
2901        input: T,
2902    ) -> Result<Value> {
2903        validate_user_signal_name(signal_name)?;
2904        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2905        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2906        let body = json!({
2907            "input": input_envelope
2908        });
2909        let path = match run_id {
2910            Some(run_id) => {
2911                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
2912            }
2913            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
2914        };
2915        self.request_json(
2916            reqwest::Method::POST,
2917            &path,
2918            RequestProtocol::ControlPlane,
2919            Some(&body),
2920        )
2921        .await
2922    }
2923
2924    /// Close the current run as cancelled immediately.
2925    ///
2926    /// Server revokes open tasks and timers without resuming workflow code for
2927    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
2928    /// request on a supporting runtime and opted-in worker.
2929    pub async fn cancel_workflow(
2930        &self,
2931        workflow_id: &str,
2932        options: WorkflowCommandOptions,
2933    ) -> Result<WorkflowCommandResult> {
2934        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
2935            .await
2936    }
2937
2938    /// Close the selected run as cancelled, only if `run_id` is still current.
2939    pub async fn cancel_workflow_run(
2940        &self,
2941        workflow_id: &str,
2942        run_id: &str,
2943        options: WorkflowCommandOptions,
2944    ) -> Result<WorkflowCommandResult> {
2945        self.workflow_command(
2946            workflow_id,
2947            Some(run_id),
2948            WorkflowCommandKind::Cancel,
2949            options,
2950        )
2951        .await
2952    }
2953
2954    /// Forcefully terminate the current run for an instance.
2955    pub async fn terminate_workflow(
2956        &self,
2957        workflow_id: &str,
2958        options: WorkflowCommandOptions,
2959    ) -> Result<WorkflowCommandResult> {
2960        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
2961            .await
2962    }
2963
2964    /// Forcefully terminate only if `run_id` is still current.
2965    pub async fn terminate_workflow_run(
2966        &self,
2967        workflow_id: &str,
2968        run_id: &str,
2969        options: WorkflowCommandOptions,
2970    ) -> Result<WorkflowCommandResult> {
2971        self.workflow_command(
2972            workflow_id,
2973            Some(run_id),
2974            WorkflowCommandKind::Terminate,
2975            options,
2976        )
2977        .await
2978    }
2979
2980    /// Continue a failed run from its recorded activity failure boundary.
2981    pub async fn redrive_workflow_run(
2982        &self,
2983        workflow_id: &str,
2984        failed_run_id: &str,
2985        request_id: Option<&str>,
2986    ) -> Result<WorkflowRedriveResult> {
2987        let body = request_id
2988            .map(|id| json!({"request_id": id}))
2989            .unwrap_or_else(|| json!({}));
2990        let data: Value = self
2991            .request_json(
2992                reqwest::Method::POST,
2993                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
2994                RequestProtocol::ControlPlane,
2995                Some(&body),
2996            )
2997            .await?;
2998        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
2999            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3000        {
3001            return Err(Error::Codec(
3002                "redrive response was not accepted".to_string(),
3003            ));
3004        }
3005        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3006            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3007        {
3008            return Err(Error::Codec(
3009                "redrive response does not match the requested source run".to_string(),
3010            ));
3011        }
3012        let run_id = data
3013            .get("run_id")
3014            .and_then(Value::as_str)
3015            .filter(|id| !id.is_empty() && *id != failed_run_id)
3016            .ok_or_else(|| {
3017                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3018            })?;
3019        let resume_step_sequence = data
3020            .get("resume_step_sequence")
3021            .and_then(Value::as_u64)
3022            .filter(|sequence| *sequence > 0)
3023            .ok_or_else(|| {
3024                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3025            })?;
3026        Ok(WorkflowRedriveResult {
3027            workflow_id: workflow_id.to_string(),
3028            source_run_id: failed_run_id.to_string(),
3029            run_id: run_id.to_string(),
3030            resume_step_sequence,
3031            raw: data,
3032        })
3033    }
3034
3035    async fn workflow_command(
3036        &self,
3037        workflow_id: &str,
3038        run_id: Option<&str>,
3039        command: WorkflowCommandKind,
3040        options: WorkflowCommandOptions,
3041    ) -> Result<WorkflowCommandResult> {
3042        let path = match run_id {
3043            Some(run_id) => format!(
3044                "/workflows/{workflow_id}/runs/{run_id}/{}",
3045                command.as_str()
3046            ),
3047            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3048        };
3049        let data = match self
3050            .request_json(
3051                reqwest::Method::POST,
3052                &path,
3053                RequestProtocol::ControlPlane,
3054                Some(&options),
3055            )
3056            .await
3057        {
3058            Ok(data) => data,
3059            Err(Error::Http { status, body }) => {
3060                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3061                    command,
3062                    status,
3063                    body,
3064                    workflow_id,
3065                    run_id,
3066                )));
3067            }
3068            Err(error) => return Err(error),
3069        };
3070
3071        Ok(workflow_command_result(command, data, workflow_id, run_id))
3072    }
3073
3074    /// Execute a named, read-only query against a running or completed workflow.
3075    ///
3076    /// Arguments and results use the platform payload envelope. Server and
3077    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3078    /// reason, HTTP status, and original response body.
3079    pub async fn query_workflow<T: Serialize>(
3080        &self,
3081        workflow_id: &str,
3082        query_name: &str,
3083        input: T,
3084    ) -> Result<Value> {
3085        self.query_workflow_target(workflow_id, None, query_name, input)
3086            .await
3087    }
3088
3089    /// Query only if `run_id` is still current, preventing accidental retargeting.
3090    pub async fn query_workflow_run<T: Serialize>(
3091        &self,
3092        workflow_id: &str,
3093        run_id: &str,
3094        query_name: &str,
3095        input: T,
3096    ) -> Result<Value> {
3097        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3098            .await
3099    }
3100
3101    /// Query a workflow and return the lossless fixed Avro Value result.
3102    pub async fn query_workflow_avro_value<T: Serialize>(
3103        &self,
3104        workflow_id: &str,
3105        query_name: &str,
3106        input: T,
3107    ) -> Result<AvroValue> {
3108        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3109            .await
3110    }
3111
3112    /// Query a selected run and return the lossless fixed Avro Value result.
3113    pub async fn query_workflow_run_avro_value<T: Serialize>(
3114        &self,
3115        workflow_id: &str,
3116        run_id: &str,
3117        query_name: &str,
3118        input: T,
3119    ) -> Result<AvroValue> {
3120        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3121            .await
3122    }
3123
3124    async fn query_workflow_avro_value_target<T: Serialize>(
3125        &self,
3126        workflow_id: &str,
3127        run_id: Option<&str>,
3128        query_name: &str,
3129        input: T,
3130    ) -> Result<AvroValue> {
3131        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3132        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3133        let path = match run_id {
3134            Some(run_id) => {
3135                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3136            }
3137            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3138        };
3139        let response: Value = match self
3140            .request_json(
3141                reqwest::Method::POST,
3142                &path,
3143                RequestProtocol::ControlPlane,
3144                Some(&body),
3145            )
3146            .await
3147        {
3148            Ok(response) => response,
3149            Err(Error::Http { status, body }) => {
3150                return Err(Error::QueryFailed(query_failure(status, body)));
3151            }
3152            Err(error) => return Err(error),
3153        };
3154
3155        let envelope = response
3156            .get("result_envelope")
3157            .filter(|envelope| !envelope.is_null())
3158            .ok_or_else(|| {
3159                Error::Codec(
3160                    "missing_payload_envelope: typed query result requires result_envelope"
3161                        .to_string(),
3162                )
3163            })?;
3164        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3165    }
3166
3167    async fn query_workflow_target<T: Serialize>(
3168        &self,
3169        workflow_id: &str,
3170        run_id: Option<&str>,
3171        query_name: &str,
3172        input: T,
3173    ) -> Result<Value> {
3174        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3175        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3176        let body = json!({
3177            "input": input_envelope
3178        });
3179        let path = match run_id {
3180            Some(run_id) => {
3181                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3182            }
3183            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3184        };
3185        let response: Value = match self
3186            .request_json(
3187                reqwest::Method::POST,
3188                &path,
3189                RequestProtocol::ControlPlane,
3190                Some(&body),
3191            )
3192            .await
3193        {
3194            Ok(response) => response,
3195            Err(Error::Http { status, body }) => {
3196                return Err(Error::QueryFailed(query_failure(status, body)));
3197            }
3198            Err(error) => return Err(error),
3199        };
3200
3201        if let Some(envelope) = response
3202            .get("result_envelope")
3203            .filter(|envelope| !envelope.is_null())
3204        {
3205            return decode_wire_value(envelope, DEFAULT_CODEC);
3206        }
3207
3208        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3209    }
3210
3211    /// Send a synchronous update using fixed Avro Value arguments.
3212    pub async fn update_workflow<T: Serialize>(
3213        &self,
3214        workflow_id: &str,
3215        update_name: &str,
3216        input: T,
3217        request_id: Option<&str>,
3218    ) -> Result<Value> {
3219        let response = self
3220            .update_workflow_response(workflow_id, update_name, input, request_id)
3221            .await?;
3222        if let Some(envelope) = response
3223            .get("result_envelope")
3224            .filter(|envelope| !envelope.is_null())
3225        {
3226            return decode_wire_value(envelope, DEFAULT_CODEC);
3227        }
3228        Ok(response.get("result").cloned().unwrap_or(response))
3229    }
3230
3231    /// Send a synchronous update and retain a bytes-capable Avro result.
3232    pub async fn update_workflow_avro_value<T: Serialize>(
3233        &self,
3234        workflow_id: &str,
3235        update_name: &str,
3236        input: T,
3237        request_id: Option<&str>,
3238    ) -> Result<AvroValue> {
3239        let response = self
3240            .update_workflow_response(workflow_id, update_name, input, request_id)
3241            .await?;
3242        let envelope = response
3243            .get("result_envelope")
3244            .filter(|envelope| !envelope.is_null())
3245            .ok_or_else(|| {
3246                Error::Codec(
3247                    "missing_payload_envelope: typed update result requires result_envelope"
3248                        .to_string(),
3249                )
3250            })?;
3251        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3252    }
3253
3254    async fn update_workflow_response<T: Serialize>(
3255        &self,
3256        workflow_id: &str,
3257        update_name: &str,
3258        input: T,
3259        request_id: Option<&str>,
3260    ) -> Result<Value> {
3261        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3262        let mut body = json!({
3263            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3264            "wait_for": "completed",
3265        });
3266        if let Some(request_id) = request_id {
3267            body["request_id"] = json!(request_id);
3268        }
3269        self.request_json(
3270            reqwest::Method::POST,
3271            &format!("/workflows/{workflow_id}/update/{update_name}"),
3272            RequestProtocol::ControlPlane,
3273            Some(&body),
3274        )
3275        .await
3276    }
3277
3278    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3279        let path = format!("/workflows/{workflow_id}");
3280        let mut data: WorkflowDescription = self
3281            .request_json(
3282                reqwest::Method::GET,
3283                &path,
3284                RequestProtocol::ControlPlane,
3285                Option::<&Value>::None,
3286            )
3287            .await?;
3288        data.decode_payloads()?;
3289        Ok(data)
3290    }
3291
3292    /// Describe one selected run, including historical terminal runs.
3293    pub async fn describe_workflow_run(
3294        &self,
3295        workflow_id: &str,
3296        run_id: &str,
3297    ) -> Result<WorkflowDescription> {
3298        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3299        let mut data: WorkflowDescription = self
3300            .request_json(
3301                reqwest::Method::GET,
3302                &path,
3303                RequestProtocol::ControlPlane,
3304                Option::<&Value>::None,
3305            )
3306            .await?;
3307        data.decode_payloads()?;
3308        Ok(data)
3309    }
3310
3311    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3312        let mut path = format!(
3313            "/workflows/{}/runs/{}/streams",
3314            percent_encode_path_segment(workflow_id),
3315            percent_encode_path_segment(run_id),
3316        );
3317        if let Some(stream_name) = stream_name {
3318            path.push('/');
3319            path.push_str(&percent_encode_path_segment(stream_name));
3320        }
3321        path
3322    }
3323
3324    /// List the run-scoped output streams already opened by a workflow.
3325    pub async fn list_workflow_streams(
3326        &self,
3327        workflow_id: &str,
3328        run_id: &str,
3329    ) -> Result<Vec<WorkflowStreamDescription>> {
3330        let response: WorkflowStreamListResponse = self
3331            .request_json(
3332                reqwest::Method::GET,
3333                &Self::workflow_stream_path(workflow_id, run_id, None),
3334                RequestProtocol::ControlPlane,
3335                Option::<&Value>::None,
3336            )
3337            .await?;
3338        Ok(response.streams)
3339    }
3340
3341    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3342    pub async fn describe_workflow_stream(
3343        &self,
3344        workflow_id: &str,
3345        run_id: &str,
3346        stream_name: &str,
3347    ) -> Result<WorkflowStreamDescription> {
3348        let response: WorkflowStreamDescriptionResponse = self
3349            .request_json(
3350                reqwest::Method::GET,
3351                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3352                RequestProtocol::ControlPlane,
3353                Option::<&Value>::None,
3354            )
3355            .await?;
3356        Ok(response.stream)
3357    }
3358
3359    /// Read one bounded page beginning at a zero-based offset.
3360    ///
3361    /// Delivery is at least once: persist `next_offset` only after processing
3362    /// the page. The future is cancellation-safe; dropping it cancels the
3363    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3364    /// service contract.
3365    pub async fn subscribe_workflow_stream(
3366        &self,
3367        workflow_id: &str,
3368        run_id: &str,
3369        stream_name: &str,
3370        from_offset: u64,
3371        max_items: usize,
3372        wait: Duration,
3373    ) -> Result<WorkflowStreamPage> {
3374        let max_items = max_items.clamp(1, 500);
3375        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3376        let path = format!(
3377            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3378            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3379        );
3380        let response: WorkflowStreamPageResponse = self
3381            .request_json_with_timeout(
3382                reqwest::Method::GET,
3383                &path,
3384                RequestProtocol::ControlPlane,
3385                Option::<&Value>::None,
3386                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3387            )
3388            .await?;
3389
3390        let items = response
3391            .items
3392            .into_iter()
3393            .map(|raw| {
3394                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3395                let envelope = raw.get("payload").cloned();
3396                let payload = envelope
3397                    .as_ref()
3398                    .filter(|value| value.get("blob").is_some())
3399                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3400                    .transpose()?
3401                    .map(AvroValue::into_json)
3402                    .transpose()?;
3403                Ok(WorkflowStreamItem {
3404                    offset,
3405                    payload,
3406                    payload_envelope: envelope,
3407                    payload_reference: raw
3408                        .get("payload_reference")
3409                        .and_then(Value::as_str)
3410                        .map(str::to_string),
3411                    payload_codec: raw
3412                        .get("payload_codec")
3413                        .and_then(Value::as_str)
3414                        .map(str::to_string),
3415                    idempotency_key: raw
3416                        .get("idempotency_key")
3417                        .and_then(Value::as_str)
3418                        .map(str::to_string),
3419                    item_type: raw
3420                        .get("item_type")
3421                        .and_then(Value::as_str)
3422                        .map(str::to_string),
3423                    content_type: raw
3424                        .get("content_type")
3425                        .and_then(Value::as_str)
3426                        .map(str::to_string),
3427                    origin: raw
3428                        .get("origin")
3429                        .and_then(Value::as_str)
3430                        .map(str::to_string),
3431                    origin_reference: raw
3432                        .get("origin_reference")
3433                        .and_then(Value::as_str)
3434                        .map(str::to_string),
3435                    emitted_at: raw
3436                        .get("emitted_at")
3437                        .and_then(Value::as_str)
3438                        .map(str::to_string),
3439                    raw,
3440                })
3441            })
3442            .collect::<Result<Vec<_>>>()?;
3443        Ok(WorkflowStreamPage {
3444            stream: response.stream,
3445            items,
3446            next_offset: response.next_offset,
3447            terminal: response.terminal,
3448        })
3449    }
3450
3451    /// Append inline Avro envelopes or opaque external payload references.
3452    pub async fn append_workflow_stream(
3453        &self,
3454        workflow_id: &str,
3455        run_id: &str,
3456        stream_name: &str,
3457        items: &[WorkflowStreamAppendItem],
3458        max_pending_items: Option<u64>,
3459    ) -> Result<WorkflowStreamAppendResult> {
3460        if items.is_empty() {
3461            return Err(Error::Codec(
3462                "workflow_stream_items_empty: append requires at least one item".to_string(),
3463            ));
3464        }
3465        let mut body = json!({
3466            "items": items
3467                .iter()
3468                .map(|item| item.wire_value(None))
3469                .collect::<Vec<_>>(),
3470        });
3471        if let Some(max_pending_items) = max_pending_items {
3472            if max_pending_items == 0 {
3473                return Err(Error::Codec(
3474                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3475                        .to_string(),
3476                ));
3477            }
3478            body["max_pending_items"] = json!(max_pending_items);
3479        }
3480        let response: WorkflowStreamAppendResponse = self
3481            .request_json(
3482                reqwest::Method::POST,
3483                &format!(
3484                    "{}/items",
3485                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3486                ),
3487                RequestProtocol::ControlPlane,
3488                Some(&body),
3489            )
3490            .await?;
3491        Ok(WorkflowStreamAppendResult {
3492            stream: response.stream,
3493            accepted_offsets: response.accepted_offsets,
3494            accepted: response.accepted,
3495            deduped: response.deduped,
3496        })
3497    }
3498
3499    /// Close a stream, or mark it errored when `error_reason` is supplied.
3500    pub async fn close_workflow_stream(
3501        &self,
3502        workflow_id: &str,
3503        run_id: &str,
3504        stream_name: &str,
3505        error_reason: Option<&str>,
3506        retention_seconds: Option<u64>,
3507    ) -> Result<WorkflowStreamDescription> {
3508        let mut body = json!({});
3509        if let Some(error_reason) = error_reason {
3510            body["error_reason"] = json!(error_reason);
3511        }
3512        if let Some(retention_seconds) = retention_seconds {
3513            if retention_seconds == 0 {
3514                return Err(Error::Codec(
3515                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3516                        .to_string(),
3517                ));
3518            }
3519            body["retention_seconds"] = json!(retention_seconds);
3520        }
3521        let response: WorkflowStreamDescriptionResponse = self
3522            .request_json(
3523                reqwest::Method::POST,
3524                &format!(
3525                    "{}/close",
3526                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3527                ),
3528                RequestProtocol::ControlPlane,
3529                Some(&body),
3530            )
3531            .await?;
3532        Ok(response.stream)
3533    }
3534
3535    pub async fn register_worker(
3536        &self,
3537        worker_id: &str,
3538        task_queue: &str,
3539        supported_workflow_types: Vec<String>,
3540        supported_activity_types: Vec<String>,
3541        max_concurrent_workflow_tasks: usize,
3542        max_concurrent_activity_tasks: usize,
3543    ) -> Result<RegisterWorkerResponse> {
3544        self.register_worker_with_capabilities(
3545            worker_id,
3546            task_queue,
3547            supported_workflow_types,
3548            supported_activity_types,
3549            max_concurrent_workflow_tasks,
3550            max_concurrent_activity_tasks,
3551            Vec::new(),
3552        )
3553        .await
3554    }
3555
3556    /// Register a worker and explicitly advertise additive worker capabilities.
3557    pub async fn register_worker_with_capabilities(
3558        &self,
3559        worker_id: &str,
3560        task_queue: &str,
3561        supported_workflow_types: Vec<String>,
3562        supported_activity_types: Vec<String>,
3563        max_concurrent_workflow_tasks: usize,
3564        max_concurrent_activity_tasks: usize,
3565        capabilities: Vec<String>,
3566    ) -> Result<RegisterWorkerResponse> {
3567        self.register_worker_with_command_contracts(
3568            worker_id,
3569            task_queue,
3570            supported_workflow_types,
3571            supported_activity_types,
3572            max_concurrent_workflow_tasks,
3573            max_concurrent_activity_tasks,
3574            capabilities,
3575            Value::Object(serde_json::Map::new()),
3576        )
3577        .await
3578    }
3579
3580    /// Register a worker and advertise its named query and update handlers.
3581    ///
3582    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3583    /// so a workflow contract with a non-empty or malformed
3584    /// `update_validators` declaration returns
3585    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3586    #[allow(clippy::too_many_arguments)]
3587    pub async fn register_worker_with_command_contracts(
3588        &self,
3589        worker_id: &str,
3590        task_queue: &str,
3591        supported_workflow_types: Vec<String>,
3592        supported_activity_types: Vec<String>,
3593        max_concurrent_workflow_tasks: usize,
3594        max_concurrent_activity_tasks: usize,
3595        capabilities: Vec<String>,
3596        workflow_command_contracts: Value,
3597    ) -> Result<RegisterWorkerResponse> {
3598        self.register_worker_with_definition_fingerprints(
3599            worker_id,
3600            task_queue,
3601            supported_workflow_types,
3602            supported_activity_types,
3603            max_concurrent_workflow_tasks,
3604            max_concurrent_activity_tasks,
3605            capabilities,
3606            workflow_command_contracts,
3607            None,
3608        )
3609        .await
3610    }
3611
3612    #[allow(clippy::too_many_arguments)]
3613    async fn register_worker_with_definition_fingerprints(
3614        &self,
3615        worker_id: &str,
3616        task_queue: &str,
3617        supported_workflow_types: Vec<String>,
3618        supported_activity_types: Vec<String>,
3619        max_concurrent_workflow_tasks: usize,
3620        max_concurrent_activity_tasks: usize,
3621        capabilities: Vec<String>,
3622        workflow_command_contracts: Value,
3623        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3624    ) -> Result<RegisterWorkerResponse> {
3625        if let Some(contracts) = workflow_command_contracts.as_object() {
3626            for (workflow_type, contract) in contracts {
3627                let Some(update_validators) = contract.get("update_validators") else {
3628                    continue;
3629                };
3630                if !update_validators
3631                    .as_array()
3632                    .is_some_and(|validators| validators.is_empty())
3633                {
3634                    return Err(Error::UnsupportedUpdateValidators {
3635                        workflow_type: workflow_type.clone(),
3636                    });
3637                }
3638            }
3639        }
3640
3641        let mut body = json!({
3642            "worker_id": worker_id,
3643            "task_queue": task_queue,
3644            "runtime": "rust",
3645            "sdk_version": SDK_VERSION,
3646            "supported_workflow_types": supported_workflow_types,
3647            "supported_activity_types": supported_activity_types,
3648            "capabilities": capabilities,
3649            "capability_manifest": portable_worker_affinity_capability_manifest(),
3650            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3651            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3652        });
3653        if let Some(build_id) = &self.worker_build_id {
3654            if build_id.is_empty() || build_id.len() > 255 {
3655                return Err(Error::WorkerLoop(
3656                    "worker build ID must contain 1 to 255 bytes".into(),
3657                ));
3658            }
3659            body["build_id"] = json!(build_id);
3660        }
3661        if self.sticky_cache.is_some() {
3662            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
3663                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
3664                "implementation":"bounded_durable_history_cache"});
3665        }
3666        if self.local_activities_enabled {
3667            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3668                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3669        }
3670        if self.worker_sessions_enabled {
3671            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3672                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3673            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3674        }
3675        if workflow_command_contracts
3676            .as_object()
3677            .is_some_and(|contracts| !contracts.is_empty())
3678        {
3679            body["workflow_command_contracts"] = workflow_command_contracts;
3680        }
3681        if let Some(fingerprints) = workflow_definition_fingerprints {
3682            body["workflow_definition_fingerprints"] = json!(fingerprints);
3683        }
3684
3685        let response: Value = self
3686            .request_json(
3687                reqwest::Method::POST,
3688                "/worker/register",
3689                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3690                Some(&body),
3691            )
3692            .await?;
3693        if self.sticky_cache.is_some() {
3694            self.confirm_sticky_registration(&response, worker_id, task_queue)
3695                .await?;
3696        }
3697        if self.local_activities_enabled || self.worker_sessions_enabled {
3698            let compatible = response["registered"].as_bool() == Some(true)
3699                && response["worker_id"].as_str() == Some(worker_id)
3700                && response["namespace"].as_str() == Some(self.namespace.as_str())
3701                && response["task_queue"].as_str() == Some(task_queue)
3702                && response["protocol_version"]
3703                    .as_str()
3704                    .and_then(|version| version.strip_prefix("1."))
3705                    .and_then(|minor| minor.parse::<u64>().ok())
3706                    .is_some_and(|minor| minor >= 18)
3707                && (!self.local_activities_enabled
3708                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3709                        == Some(true))
3710                && (!self.worker_sessions_enabled
3711                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3712                        == Some(true)
3713                        && response["capabilities"].as_array().is_some_and(|accepted| {
3714                            capabilities.iter().all(|capability| {
3715                                accepted
3716                                    .iter()
3717                                    .any(|value| value.as_str() == Some(capability.as_str()))
3718                            })
3719                        })));
3720            if !compatible {
3721                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3722                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3723                } else {
3724                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3725                });
3726                if response["registered"] == true
3727                    && response["worker_id"].as_str() == Some(worker_id)
3728                {
3729                    if let Err(deregistration) =
3730                        self.deregister_worker_registration(worker_id).await
3731                    {
3732                        return Err(Error::WorkerShutdown {
3733                            primary: Box::new(error),
3734                            deregistration: Box::new(deregistration),
3735                        });
3736                    }
3737                }
3738                return Err(error);
3739            }
3740        }
3741        if self.cooperative_worker_protocol {
3742            let compatible = response["registered"].as_bool() == Some(true)
3743                && response["worker_id"].as_str() == Some(worker_id)
3744                && response["namespace"].as_str() == Some(self.namespace.as_str())
3745                && response["task_queue"].as_str() == Some(task_queue)
3746                && response["protocol_version"]
3747                    .as_str()
3748                    .is_some_and(cooperative_cancellation::supports_protocol)
3749                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3750                    == Some(true)
3751                && response["capabilities"].as_array().is_some_and(|accepted| {
3752                    capabilities.iter().all(|capability| {
3753                        accepted
3754                            .iter()
3755                            .any(|value| value.as_str() == Some(capability.as_str()))
3756                    })
3757                });
3758            if !compatible {
3759                let error = Error::CooperativeCancellationUnavailable(
3760                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3761                );
3762                if response["registered"].as_bool() == Some(true)
3763                    && response["worker_id"].as_str() == Some(worker_id)
3764                {
3765                    if let Err(deregistration) =
3766                        self.deregister_worker_registration(worker_id).await
3767                    {
3768                        return Err(Error::WorkerShutdown {
3769                            primary: Box::new(error),
3770                            deregistration: Box::new(deregistration),
3771                        });
3772                    }
3773                }
3774                return Err(error);
3775            }
3776        }
3777        Ok(serde_json::from_value(response)?)
3778    }
3779
3780    /// Gracefully remove one worker's registration through the worker plane.
3781    ///
3782    /// This operation is separate from operator-facing worker management. It
3783    /// uses worker-protocol authentication and returns the server's lease
3784    /// recovery result.
3785    pub async fn deregister_worker_registration(
3786        &self,
3787        worker_id: &str,
3788    ) -> Result<WorkerDeregistrationEnvelope> {
3789        let path = format!(
3790            "/worker/registrations/{}",
3791            percent_encode_path_segment(worker_id)
3792        );
3793        self.request_json(
3794            reqwest::Method::DELETE,
3795            &path,
3796            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3797            Option::<&Value>::None,
3798        )
3799        .await
3800    }
3801
3802    /// Long-poll for an ephemeral, read-only workflow query task.
3803    pub async fn poll_query_task(
3804        &self,
3805        worker_id: &str,
3806        task_queue: &str,
3807        timeout: Duration,
3808    ) -> Result<Option<QueryTask>> {
3809        Ok(self
3810            .poll_query_task_response(worker_id, task_queue, timeout)
3811            .await?
3812            .task)
3813    }
3814
3815    /// Poll a query task while preserving server stop and drain metadata.
3816    pub async fn poll_query_task_response(
3817        &self,
3818        worker_id: &str,
3819        task_queue: &str,
3820        timeout: Duration,
3821    ) -> Result<PollQueryTaskResponse> {
3822        let poll_request_id = unique_request_id("rust-query-poll");
3823        self.poll_query_task_response_with_request_id(
3824            worker_id,
3825            task_queue,
3826            timeout,
3827            &poll_request_id,
3828            1,
3829        )
3830        .await
3831    }
3832
3833    async fn poll_query_task_response_with_request_id(
3834        &self,
3835        worker_id: &str,
3836        task_queue: &str,
3837        timeout: Duration,
3838        poll_request_id: &str,
3839        transport_retries: usize,
3840    ) -> Result<PollQueryTaskResponse> {
3841        let timeout_seconds = long_poll_timeout_seconds(timeout);
3842        let body = json!({
3843            "worker_id": worker_id,
3844            "task_queue": task_queue,
3845            "poll_request_id": poll_request_id,
3846            "timeout_seconds": timeout_seconds,
3847        });
3848        self.poll_request_json(
3849            "/worker/query-tasks/poll",
3850            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3851            &body,
3852            timeout + Duration::from_secs(5),
3853            transport_retries,
3854        )
3855        .await
3856    }
3857
3858    /// Complete a query task without appending workflow history.
3859    pub async fn complete_query_task<T: Serialize>(
3860        &self,
3861        query_task_id: &str,
3862        lease_owner: &str,
3863        query_task_attempt: u64,
3864        result: T,
3865        codec: &str,
3866    ) -> Result<Value> {
3867        let typed_result = AvroValue::from_serialize(&result)?;
3868        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3869        self.complete_query_task_with_envelope(
3870            query_task_id,
3871            lease_owner,
3872            query_task_attempt,
3873            typed_result.into_json()?,
3874            result_envelope,
3875        )
3876        .await
3877    }
3878
3879    async fn complete_query_task_with_envelope(
3880        &self,
3881        query_task_id: &str,
3882        lease_owner: &str,
3883        query_task_attempt: u64,
3884        result: Value,
3885        result_envelope: Value,
3886    ) -> Result<Value> {
3887        let body = json!({
3888            "lease_owner": lease_owner,
3889            "query_task_attempt": query_task_attempt,
3890            "result": result,
3891            "result_envelope": result_envelope,
3892        });
3893        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3894        let response = self
3895            .request_json(
3896                reqwest::Method::POST,
3897                &path,
3898                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3899                Some(&body),
3900            )
3901            .await;
3902        query_task_response(response)
3903    }
3904
3905    /// Report a stable machine-readable query-task failure.
3906    pub async fn fail_query_task(
3907        &self,
3908        query_task_id: &str,
3909        lease_owner: &str,
3910        query_task_attempt: u64,
3911        message: impl Into<String>,
3912        reason: impl Into<String>,
3913        failure_type: impl Into<String>,
3914    ) -> Result<Value> {
3915        let body = json!({
3916            "lease_owner": lease_owner,
3917            "query_task_attempt": query_task_attempt,
3918            "failure": {
3919                "message": message.into(),
3920                "reason": reason.into(),
3921                "type": failure_type.into(),
3922            }
3923        });
3924        let path = format!("/worker/query-tasks/{query_task_id}/fail");
3925        let response = self
3926            .request_json(
3927                reqwest::Method::POST,
3928                &path,
3929                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3930                Some(&body),
3931            )
3932            .await;
3933        query_task_response(response)
3934    }
3935
3936    pub async fn heartbeat_worker(
3937        &self,
3938        worker_id: &str,
3939        workflow_available: usize,
3940        activity_available: usize,
3941    ) -> Result<Value> {
3942        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
3943            .await
3944    }
3945
3946    async fn heartbeat_worker_with_sessions(
3947        &self,
3948        worker_id: &str,
3949        workflow_available: usize,
3950        activity_available: usize,
3951        session_available: Option<usize>,
3952    ) -> Result<Value> {
3953        let mut body = json!({
3954            "worker_id": worker_id,
3955            "task_slots": {
3956                "workflow_available": workflow_available,
3957                "activity_available": activity_available
3958            },
3959            "process_metrics": {
3960                "process_id": std::process::id(),
3961                "process_uptime_seconds": 0
3962            }
3963        });
3964
3965        if let Some(available) = session_available {
3966            body["task_slots"]["session_available"] = json!(available);
3967        }
3968
3969        self.request_json(
3970            reqwest::Method::POST,
3971            "/worker/heartbeat",
3972            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
3973            Some(&body),
3974        )
3975        .await
3976    }
3977
3978    pub async fn poll_workflow_task(
3979        &self,
3980        worker_id: &str,
3981        task_queue: &str,
3982        timeout: Duration,
3983    ) -> Result<Option<WorkflowTask>> {
3984        Ok(self
3985            .poll_workflow_task_response(worker_id, task_queue, timeout)
3986            .await?
3987            .task)
3988    }
3989
3990    pub async fn poll_workflow_task_response(
3991        &self,
3992        worker_id: &str,
3993        task_queue: &str,
3994        timeout: Duration,
3995    ) -> Result<PollWorkflowTaskResponse> {
3996        let poll_request_id = unique_request_id("rust-workflow-poll");
3997        self.poll_workflow_task_response_with_request_id(
3998            worker_id,
3999            task_queue,
4000            timeout,
4001            &poll_request_id,
4002            1,
4003        )
4004        .await
4005    }
4006
4007    async fn poll_workflow_task_response_with_request_id(
4008        &self,
4009        worker_id: &str,
4010        task_queue: &str,
4011        timeout: Duration,
4012        poll_request_id: &str,
4013        transport_retries: usize,
4014    ) -> Result<PollWorkflowTaskResponse> {
4015        let body = json!({
4016            "worker_id": worker_id,
4017            "task_queue": task_queue,
4018            "poll_request_id": poll_request_id,
4019            "timeout_seconds": long_poll_timeout_seconds(timeout),
4020            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4021        });
4022        let mut data: PollWorkflowTaskResponse = self
4023            .poll_request_json(
4024                "/worker/workflow-tasks/poll",
4025                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4026                &body,
4027                timeout + Duration::from_secs(5),
4028                transport_retries,
4029            )
4030            .await?;
4031
4032        if let Some(task) = data.task.as_mut() {
4033            self.fetch_remaining_workflow_history(worker_id, task)
4034                .await?;
4035        }
4036
4037        Ok(data)
4038    }
4039
4040    async fn fetch_remaining_workflow_history(
4041        &self,
4042        worker_id: &str,
4043        task: &mut WorkflowTask,
4044    ) -> Result<()> {
4045        let mut next_token = task.next_history_page_token.clone();
4046
4047        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4048            let lease_owner = task
4049                .lease_owner
4050                .clone()
4051                .unwrap_or_else(|| worker_id.to_string());
4052            let page = self
4053                .workflow_task_history_page(
4054                    &task.task_id,
4055                    &lease_owner,
4056                    task.workflow_task_attempt,
4057                    &token,
4058                )
4059                .await?;
4060
4061            task.append_history_page(page);
4062
4063            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4064                return Err(Error::Codec(
4065                    "workflow history pagination returned the same page token".to_string(),
4066                ));
4067            }
4068
4069            next_token = task.next_history_page_token.clone();
4070        }
4071
4072        Ok(())
4073    }
4074
4075    async fn workflow_task_history_page(
4076        &self,
4077        task_id: &str,
4078        lease_owner: &str,
4079        workflow_task_attempt: u64,
4080        next_history_page_token: &str,
4081    ) -> Result<WorkflowTaskHistoryPage> {
4082        let body = json!({
4083            "lease_owner": lease_owner,
4084            "workflow_task_attempt": workflow_task_attempt,
4085            "next_history_page_token": next_history_page_token
4086        });
4087        let path = format!("/worker/workflow-tasks/{task_id}/history");
4088
4089        self.request_json(
4090            reqwest::Method::POST,
4091            &path,
4092            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4093            Some(&body),
4094        )
4095        .await
4096    }
4097
4098    pub async fn complete_workflow_task(
4099        &self,
4100        task_id: &str,
4101        lease_owner: &str,
4102        workflow_task_attempt: u64,
4103        commands: Vec<Value>,
4104    ) -> Result<Value> {
4105        self.complete_workflow_task_with_message_streams(
4106            task_id,
4107            lease_owner,
4108            workflow_task_attempt,
4109            commands,
4110            Vec::new(),
4111            Vec::new(),
4112            None,
4113        )
4114        .await
4115    }
4116
4117    #[allow(clippy::too_many_arguments)]
4118    async fn complete_workflow_task_with_message_streams(
4119        &self,
4120        task_id: &str,
4121        lease_owner: &str,
4122        workflow_task_attempt: u64,
4123        commands: Vec<Value>,
4124        message_stream_cursors: Vec<Value>,
4125        message_stream_waits: Vec<Value>,
4126        sticky_cache: Option<Value>,
4127    ) -> Result<Value> {
4128        validate_workflow_task_commands(&commands)?;
4129        let has_message_stream_metadata =
4130            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4131        if has_message_stream_metadata
4132            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4133        {
4134            return Err(Error::Codec(
4135                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4136                    .to_string(),
4137            ));
4138        }
4139        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4140            &commands,
4141            has_message_stream_metadata,
4142        );
4143        let protocol_version = if sticky_cache.is_some()
4144            && protocol_version
4145                .strip_prefix("1.")
4146                .and_then(|minor| minor.parse::<u64>().ok())
4147                .is_some_and(|minor| minor < 18)
4148        {
4149            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4150        } else {
4151            protocol_version
4152        };
4153        let mut body = json!({
4154            "lease_owner": lease_owner,
4155            "workflow_task_attempt": workflow_task_attempt,
4156            "commands": commands
4157        });
4158        if !message_stream_cursors.is_empty() {
4159            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4160        }
4161        if !message_stream_waits.is_empty() {
4162            body["message_stream_waits"] = Value::Array(message_stream_waits);
4163        }
4164        if let Some(claim) = sticky_cache {
4165            body["sticky_cache"] = claim;
4166        }
4167        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4168        self.request_json(
4169            reqwest::Method::POST,
4170            &path,
4171            RequestProtocol::Worker(protocol_version),
4172            Some(&body),
4173        )
4174        .await
4175    }
4176
4177    pub async fn fail_workflow_task(
4178        &self,
4179        task_id: &str,
4180        lease_owner: &str,
4181        workflow_task_attempt: u64,
4182        message: impl Into<String>,
4183    ) -> Result<Value> {
4184        self.fail_workflow_task_with_type(
4185            task_id,
4186            lease_owner,
4187            workflow_task_attempt,
4188            message,
4189            "RustWorkflowTaskFailure",
4190        )
4191        .await
4192    }
4193
4194    async fn fail_workflow_task_with_type(
4195        &self,
4196        task_id: &str,
4197        lease_owner: &str,
4198        workflow_task_attempt: u64,
4199        message: impl Into<String>,
4200        failure_type: &str,
4201    ) -> Result<Value> {
4202        let body = json!({
4203            "lease_owner": lease_owner,
4204            "workflow_task_attempt": workflow_task_attempt,
4205            "failure": {
4206                "message": message.into(),
4207                "type": failure_type
4208            }
4209        });
4210        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4211        self.request_json(
4212            reqwest::Method::POST,
4213            &path,
4214            RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4215            Some(&body),
4216        )
4217        .await
4218    }
4219
4220    pub async fn poll_activity_task(
4221        &self,
4222        worker_id: &str,
4223        task_queue: &str,
4224        timeout: Duration,
4225    ) -> Result<Option<ActivityTask>> {
4226        Ok(self
4227            .poll_activity_task_response(worker_id, task_queue, timeout)
4228            .await?
4229            .task)
4230    }
4231
4232    /// Poll an activity task while preserving server stop and drain metadata.
4233    pub async fn poll_activity_task_response(
4234        &self,
4235        worker_id: &str,
4236        task_queue: &str,
4237        timeout: Duration,
4238    ) -> Result<PollActivityTaskResponse> {
4239        let poll_request_id = unique_request_id("rust-activity-poll");
4240        self.poll_activity_task_response_with_request_id(
4241            worker_id,
4242            task_queue,
4243            timeout,
4244            &poll_request_id,
4245            1,
4246        )
4247        .await
4248        .map(worker_session::SessionPollResponse::ordinary)
4249    }
4250
4251    async fn poll_activity_task_response_with_request_id(
4252        &self,
4253        worker_id: &str,
4254        task_queue: &str,
4255        timeout: Duration,
4256        poll_request_id: &str,
4257        transport_retries: usize,
4258    ) -> Result<worker_session::SessionPollResponse> {
4259        let body = json!({
4260            "worker_id": worker_id,
4261            "task_queue": task_queue,
4262            "poll_request_id": poll_request_id,
4263            "timeout_seconds": long_poll_timeout_seconds(timeout),
4264        });
4265        let data: worker_session::SessionPollResponse = self
4266            .poll_request_json(
4267                "/worker/activity-tasks/poll",
4268                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4269                &body,
4270                timeout + Duration::from_secs(5),
4271                transport_retries,
4272            )
4273            .await?;
4274        Ok(data)
4275    }
4276
4277    pub async fn complete_activity_task<T: Serialize>(
4278        &self,
4279        task_id: &str,
4280        activity_attempt_id: &str,
4281        lease_owner: &str,
4282        result: T,
4283        codec: &str,
4284    ) -> Result<Value> {
4285        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4286        let body = json!({
4287            "activity_attempt_id": activity_attempt_id,
4288            "lease_owner": lease_owner,
4289            "result": result
4290        });
4291        let path = format!("/worker/activity-tasks/{task_id}/complete");
4292        activity_task_response(
4293            self.request_json(
4294                reqwest::Method::POST,
4295                &path,
4296                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4297                Some(&body),
4298            )
4299            .await,
4300            "complete",
4301            task_id,
4302            activity_attempt_id,
4303        )
4304    }
4305
4306    pub async fn fail_activity_task(
4307        &self,
4308        task_id: &str,
4309        activity_attempt_id: &str,
4310        lease_owner: &str,
4311        message: impl Into<String>,
4312        non_retryable: bool,
4313    ) -> Result<Value> {
4314        let body = json!({
4315            "activity_attempt_id": activity_attempt_id,
4316            "lease_owner": lease_owner,
4317            "failure": {
4318                "message": message.into(),
4319                "type": "RustActivityFailure",
4320                "non_retryable": non_retryable
4321            }
4322        });
4323        let path = format!("/worker/activity-tasks/{task_id}/fail");
4324        activity_task_response(
4325            self.request_json(
4326                reqwest::Method::POST,
4327                &path,
4328                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4329                Some(&body),
4330            )
4331            .await,
4332            "fail",
4333            task_id,
4334            activity_attempt_id,
4335        )
4336    }
4337
4338    /// Record a flat map of scalar/null activity progress metadata.
4339    ///
4340    /// Heartbeat details use the Server's bounded JSON progress contract.
4341    /// They are not workflow payload envelopes.
4342    pub async fn heartbeat_activity_task<T: Serialize>(
4343        &self,
4344        task_id: &str,
4345        activity_attempt_id: &str,
4346        lease_owner: &str,
4347        details: T,
4348    ) -> Result<ActivityHeartbeatResponse> {
4349        serde_json::from_value(
4350            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4351                .await?,
4352        )
4353        .map_err(Error::from)
4354    }
4355
4356    async fn heartbeat_activity_task_value<T: Serialize>(
4357        &self,
4358        task_id: &str,
4359        activity_attempt_id: &str,
4360        lease_owner: &str,
4361        details: T,
4362    ) -> Result<Value> {
4363        let details = AvroValue::from_serialize(&details)?.into_json()?;
4364        let body = json!({
4365            "activity_attempt_id": activity_attempt_id,
4366            "lease_owner": lease_owner,
4367            "details": details
4368        });
4369        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4370        activity_task_response(
4371            self.request_json(
4372                reqwest::Method::POST,
4373                &path,
4374                RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
4375                Some(&body),
4376            )
4377            .await,
4378            "heartbeat",
4379            task_id,
4380            activity_attempt_id,
4381        )
4382    }
4383
4384    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4385        &self,
4386        method: reqwest::Method,
4387        path: &str,
4388        protocol: RequestProtocol,
4389        body: Option<&B>,
4390    ) -> Result<T> {
4391        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4392            .await
4393    }
4394
4395    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4396        &self,
4397        method: reqwest::Method,
4398        path: &str,
4399        protocol: RequestProtocol,
4400        body: Option<&B>,
4401        timeout: Duration,
4402    ) -> Result<T> {
4403        let protocol = match protocol {
4404            RequestProtocol::Worker(version)
4405                if self.cooperative_worker_protocol
4406                    && version
4407                        .strip_prefix("1.")
4408                        .and_then(|minor| minor.parse::<u64>().ok())
4409                        .is_some_and(|minor| minor < 20) =>
4410            {
4411                RequestProtocol::Worker("1.20")
4412            }
4413            protocol => protocol,
4414        };
4415        let auth_token = self.auth_token(protocol)?;
4416        let mut request = self
4417            .http
4418            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4419            .timeout(timeout)
4420            .header(reqwest::header::ACCEPT, "application/json")
4421            .header(reqwest::header::CONTENT_TYPE, "application/json")
4422            .header("X-Namespace", &self.namespace);
4423
4424        match protocol {
4425            RequestProtocol::Worker(version) => {
4426                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4427            }
4428            RequestProtocol::ControlPlane => {
4429                request = request.header(
4430                    "X-Durable-Workflow-Control-Plane-Version",
4431                    CONTROL_PLANE_VERSION,
4432                );
4433            }
4434        }
4435
4436        if let Some(token) = auth_token {
4437            request = request.bearer_auth(token);
4438        }
4439
4440        if let Some(body) = body {
4441            let mut body = serde_json::to_value(body)?;
4442            if matches!(
4443                method,
4444                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4445            ) {
4446                self.externalize_runtime_payloads(&mut body, path, protocol)
4447                    .await?;
4448            }
4449            request = request.json(&body);
4450        }
4451
4452        let request = request.build()?;
4453        let request_body = request
4454            .body()
4455            .and_then(reqwest::Body::as_bytes)
4456            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4457        let poll_request_id = path.ends_with("/poll").then(|| {
4458            request_body
4459                .as_ref()
4460                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4461                .unwrap_or_default()
4462        });
4463        let mut storage_retries = 0_usize;
4464
4465        loop {
4466            // Keep the serialized body and lease/poll identity across admission pauses.
4467            let response = self
4468                .http
4469                .execute(request.try_clone().ok_or_else(|| {
4470                    Error::WorkerLoop("worker request body cannot be retried".to_string())
4471                })?)
4472                .await?;
4473            let status = response.status();
4474            let bytes = response.bytes().await?;
4475
4476            if !status.is_success() {
4477                let body = String::from_utf8_lossy(&bytes).to_string();
4478                if let Some(protocol) = protocol_failure(status, &body) {
4479                    return Err(Error::Protocol(protocol));
4480                }
4481                let error = Error::Http { status, body };
4482                if self
4483                    .wait_for_storage_admission(
4484                        &error,
4485                        protocol,
4486                        Some(path),
4487                        poll_request_id.as_deref(),
4488                        request_body.as_ref(),
4489                        &mut storage_retries,
4490                    )
4491                    .await
4492                {
4493                    continue;
4494                }
4495                return Err(error);
4496            }
4497
4498            if bytes.is_empty() {
4499                return Ok(serde_json::from_value(Value::Null)?);
4500            }
4501
4502            let mut value: Value = serde_json::from_slice(&bytes)?;
4503            self.resolve_runtime_payloads(&mut value, path, protocol)
4504                .await?;
4505            return Ok(serde_json::from_value(value)?);
4506        }
4507    }
4508
4509    async fn wait_for_storage_admission(
4510        &self,
4511        error: &Error,
4512        protocol: RequestProtocol,
4513        path: Option<&str>,
4514        poll_request_id: Option<&str>,
4515        request_body: Option<&Value>,
4516        retries: &mut usize,
4517    ) -> bool {
4518        let Some(admission) = self
4519            .worker_storage_admission
4520            .as_ref()
4521            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4522        else {
4523            return false;
4524        };
4525        let Some(advertised_delay) = worker_storage_admission_retry_after(error, poll_request_id)
4526            .or_else(|| {
4527                path.and_then(|path| {
4528                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4529                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4530                })
4531            })
4532        else {
4533            return false;
4534        };
4535        *retries = retries.saturating_add(1);
4536        let delay = worker_retry_delay(admission.policy, *retries)
4537            .max(advertised_delay)
4538            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4539        let deadline = tokio::time::Instant::now() + delay;
4540        loop {
4541            if admission.stop.load(Ordering::SeqCst) {
4542                return false;
4543            }
4544            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
4545            if remaining.is_zero() {
4546                return true;
4547            }
4548            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4549        }
4550    }
4551
4552    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4553        &self,
4554        path: &str,
4555        protocol: RequestProtocol,
4556        body: &B,
4557        timeout: Duration,
4558        max_retries: usize,
4559    ) -> Result<T> {
4560        let mut retries = 0;
4561
4562        loop {
4563            let response = self
4564                .request_json_with_timeout(
4565                    reqwest::Method::POST,
4566                    path,
4567                    protocol,
4568                    Some(body),
4569                    timeout,
4570                )
4571                .await;
4572
4573            match response {
4574                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4575                response => return worker_poll_response(response),
4576            }
4577        }
4578    }
4579
4580    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4581        match protocol {
4582            RequestProtocol::Worker(_) => {
4583                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4584                    return Ok(Some(token));
4585                }
4586                if self.control_token.is_some() {
4587                    return Err(Error::MissingRoleCredentials {
4588                        role: "worker",
4589                        opposite_role: "control",
4590                    });
4591                }
4592                Ok(None)
4593            }
4594            RequestProtocol::ControlPlane => {
4595                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4596                    return Ok(Some(token));
4597                }
4598                if self.worker_token.is_some() {
4599                    return Err(Error::MissingRoleCredentials {
4600                        role: "control",
4601                        opposite_role: "worker",
4602                    });
4603                }
4604                Ok(None)
4605            }
4606        }
4607    }
4608}
4609
4610fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4611    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4612    let reason = body
4613        .get("reason")
4614        .and_then(Value::as_str)
4615        .unwrap_or("query_rejected")
4616        .to_string();
4617    let message = body
4618        .get("message")
4619        .or_else(|| body.get("error"))
4620        .and_then(Value::as_str)
4621        .unwrap_or("workflow query was rejected")
4622        .to_string();
4623
4624    QueryFailure {
4625        status: status.as_u16(),
4626        reason,
4627        message,
4628        body,
4629    }
4630}
4631
4632fn workflow_command_result(
4633    command: WorkflowCommandKind,
4634    data: Value,
4635    workflow_id: &str,
4636    run_id: Option<&str>,
4637) -> WorkflowCommandResult {
4638    WorkflowCommandResult {
4639        command,
4640        workflow_id: data
4641            .get("workflow_id")
4642            .and_then(Value::as_str)
4643            .unwrap_or(workflow_id)
4644            .to_string(),
4645        run_id: data
4646            .get("run_id")
4647            .and_then(Value::as_str)
4648            .or(run_id)
4649            .map(str::to_string),
4650        outcome: data
4651            .get("outcome")
4652            .and_then(Value::as_str)
4653            .map(str::to_string),
4654        reason: data
4655            .get("reason")
4656            .and_then(Value::as_str)
4657            .map(str::to_string),
4658        command_status: data
4659            .get("command_status")
4660            .and_then(Value::as_str)
4661            .map(str::to_string),
4662        raw: data,
4663    }
4664}
4665
4666fn workflow_command_rejection(
4667    command: WorkflowCommandKind,
4668    status: reqwest::StatusCode,
4669    raw_body: String,
4670    workflow_id: &str,
4671    run_id: Option<&str>,
4672) -> WorkflowCommandRejection {
4673    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4674    WorkflowCommandRejection {
4675        command,
4676        status: status.as_u16(),
4677        reason: body
4678            .get("reason")
4679            .and_then(Value::as_str)
4680            .unwrap_or("workflow_command_rejected")
4681            .to_string(),
4682        message: body
4683            .get("message")
4684            .or_else(|| body.get("error"))
4685            .and_then(Value::as_str)
4686            .unwrap_or("workflow lifecycle command was rejected")
4687            .to_string(),
4688        workflow_id: body
4689            .get("workflow_id")
4690            .and_then(Value::as_str)
4691            .unwrap_or(workflow_id)
4692            .to_string(),
4693        run_id: body
4694            .get("run_id")
4695            .and_then(Value::as_str)
4696            .or(run_id)
4697            .map(str::to_string),
4698        target_scope: body
4699            .get("target_scope")
4700            .and_then(Value::as_str)
4701            .map(str::to_string),
4702        body,
4703    }
4704}
4705
4706fn query_task_response(response: Result<Value>) -> Result<Value> {
4707    match response {
4708        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4709        response => response,
4710    }
4711}
4712
4713fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4714    match response {
4715        Err(Error::Http { status, body })
4716            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4717        {
4718            Ok(serde_json::from_str(&body)?)
4719        }
4720        response => response,
4721    }
4722}
4723
4724fn worker_poll_body_is_stop(body: &str) -> bool {
4725    serde_json::from_str::<Value>(body)
4726        .ok()
4727        .is_some_and(|body| {
4728            worker_poll_is_stop(
4729                body.get("poll_status").and_then(Value::as_str),
4730                body.get("reason").and_then(Value::as_str),
4731            )
4732        })
4733}
4734
4735fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4736    matches!(poll_status, Some("draining" | "stopped"))
4737        || matches!(reason, Some("worker_draining" | "worker_stopped"))
4738}
4739
4740fn query_task_rejection_is_final(error: &Error) -> bool {
4741    matches!(
4742        error,
4743        Error::QueryFailed(failure)
4744            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
4745    )
4746}
4747
4748fn activity_task_response<T>(
4749    response: Result<T>,
4750    operation: &str,
4751    task_id: &str,
4752    activity_attempt_id: &str,
4753) -> Result<T> {
4754    match response {
4755        Err(Error::Http { status, body }) => {
4756            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
4757            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
4758                operation: operation.to_string(),
4759                status: status.as_u16(),
4760                reason: body
4761                    .get("reason")
4762                    .and_then(Value::as_str)
4763                    .unwrap_or("activity_task_rejected")
4764                    .to_string(),
4765                task_id: body
4766                    .get("task_id")
4767                    .and_then(Value::as_str)
4768                    .unwrap_or(task_id)
4769                    .to_string(),
4770                activity_attempt_id: body
4771                    .get("activity_attempt_id")
4772                    .and_then(Value::as_str)
4773                    .unwrap_or(activity_attempt_id)
4774                    .to_string(),
4775                cancel_requested: body
4776                    .get("cancel_requested")
4777                    .and_then(Value::as_bool)
4778                    .unwrap_or(false),
4779                can_continue: body.get("can_continue").and_then(Value::as_bool),
4780                run_closed_reason: body
4781                    .get("run_closed_reason")
4782                    .and_then(Value::as_str)
4783                    .map(str::to_string),
4784                body,
4785            }))
4786        }
4787        response => response,
4788    }
4789}
4790
4791fn activity_task_rejection_is_final(error: &Error) -> bool {
4792    matches!(
4793        error,
4794        Error::ActivityTaskRejected(rejection)
4795            if matches!(
4796                rejection.reason.as_str(),
4797                "run_cancelled"
4798                    | "run_terminated"
4799                    | "attempt_closed"
4800                    | "stale_attempt"
4801                    | "activity_cancelled"
4802                    | "task_cancelled"
4803                    | "run_closed"
4804                    | "activity_not_running"
4805                    | "attempt_not_found"
4806            )
4807    )
4808}
4809
4810fn workflow_task_completion_is_terminal_timeout(
4811    error: &Error,
4812    task_id: &str,
4813    workflow_task_attempt: u64,
4814    run_id: Option<&str>,
4815) -> bool {
4816    let Error::Http { status, body } = error else {
4817        return false;
4818    };
4819    if *status != reqwest::StatusCode::CONFLICT {
4820        return false;
4821    }
4822
4823    let Some(run_id) = run_id else {
4824        return false;
4825    };
4826    let Ok(body) = serde_json::from_str::<Value>(body) else {
4827        return false;
4828    };
4829
4830    body.get("recorded").and_then(Value::as_bool) == Some(false)
4831        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
4832        && body.get("run_status").and_then(Value::as_str) == Some("failed")
4833        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
4834        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
4835        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
4836}
4837
4838fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
4839    let body: Value = serde_json::from_str(raw_body).ok()?;
4840    let reason = body.get("reason")?.as_str()?;
4841    if !matches!(
4842        reason,
4843        "missing_protocol_version"
4844            | "unsupported_protocol_version"
4845            | "missing_control_plane_version"
4846            | "unsupported_control_plane_version"
4847    ) {
4848        return None;
4849    }
4850
4851    Some(ProtocolFailure {
4852        status: status.as_u16(),
4853        reason: reason.to_string(),
4854        message: body
4855            .get("message")
4856            .or_else(|| body.get("error"))
4857            .and_then(Value::as_str)
4858            .unwrap_or("protocol version rejected")
4859            .to_string(),
4860        supported_version: body
4861            .get("supported_version")
4862            .and_then(Value::as_str)
4863            .map(str::to_string),
4864        requested_version: body
4865            .get("requested_version")
4866            .and_then(Value::as_str)
4867            .map(str::to_string),
4868        body,
4869    })
4870}
4871
4872fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
4873    timeout
4874        .as_secs()
4875        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
4876        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
4877}
4878
4879fn worker_operation_is_retryable(error: &Error) -> bool {
4880    if worker_poll_capacity_retry_after(error).is_some()
4881        || worker_storage_admission_body(error).is_some()
4882        || worker_backend_unavailable_body(error).is_some()
4883        || worker_operation_is_explicitly_non_retryable(error)
4884    {
4885        return false;
4886    }
4887
4888    match error {
4889        Error::Transport(error) => {
4890            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
4891        }
4892        Error::Http { status, .. } => {
4893            matches!(
4894                *status,
4895                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
4896            ) || status.is_server_error()
4897        }
4898        _ => false,
4899    }
4900}
4901
4902fn worker_storage_admission_body(error: &Error) -> Option<Value> {
4903    let body: Value = match error {
4904        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
4905        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
4906        _ => return None,
4907    };
4908    matches!(
4909        body.get("reason").and_then(Value::as_str),
4910        Some("storage_pressure" | "storage_admission_unavailable")
4911    )
4912    .then_some(body)
4913}
4914
4915fn worker_storage_admission_retry_after(
4916    error: &Error,
4917    poll_request_id: Option<&str>,
4918) -> Option<Duration> {
4919    let Error::Http { status, .. } = error else {
4920        return None;
4921    };
4922    let body = worker_storage_admission_body(error)?;
4923    let delay = body.get("retry_after_seconds")?.as_u64()?;
4924    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
4925        || delay == 0
4926        || body.get("retryable") != Some(&Value::Bool(true))
4927        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
4928        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
4929        || body
4930            .get("request_admitted")
4931            .is_some_and(|admitted| admitted != &Value::Bool(false))
4932    {
4933        return None;
4934    }
4935    match poll_request_id {
4936        Some(id) => {
4937            if id.is_empty()
4938                || body.get("task") != Some(&Value::Null)
4939                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
4940                || body.get("poll_status") != body.get("reason")
4941                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
4942                || body.get("claim_admitted") != Some(&Value::Bool(false))
4943            {
4944                return None;
4945            }
4946        }
4947        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
4948        None => {}
4949    }
4950    Some(Duration::from_secs(delay))
4951}
4952
4953fn worker_backend_unavailable_retry_after(
4954    error: &Error,
4955    path: &str,
4956    poll_request_id: Option<&str>,
4957) -> Option<Duration> {
4958    let operation = match path {
4959        "/worker/register" => "register_worker",
4960        "/worker/heartbeat" => "heartbeat_worker",
4961        "/worker/workflow-tasks/poll" => "poll_workflow_task",
4962        "/worker/activity-tasks/poll" => "poll_activity_task",
4963        "/worker/query-tasks/poll" => "poll_query_task",
4964        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
4965        _ => return None,
4966    };
4967    let body = worker_backend_unavailable_body(error)?;
4968    let delay = body.get("retry_after_seconds")?.as_u64()?;
4969    if delay == 0
4970        || body.get("operation")?.as_str()? != operation
4971        || body.get("outcome")?.as_str()? != "unknown"
4972        || body.get("retryable") != Some(&Value::Bool(true))
4973        || body.get("worker_id")?.as_str()?.is_empty()
4974    {
4975        return None;
4976    }
4977    if let Some(id) = poll_request_id {
4978        if id.is_empty()
4979            || body.get("task") != Some(&Value::Null)
4980            || body.get("poll_status")?.as_str()? != "backend_unavailable"
4981            || body.get("poll_request_id")?.as_str()? != id
4982            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
4983        {
4984            return None;
4985        }
4986    } else if path.ends_with("/poll") {
4987        return None;
4988    }
4989    Some(Duration::from_secs(delay))
4990}
4991
4992fn worker_fenced_completion_retry_after(
4993    error: &Error,
4994    path: &str,
4995    request_body: Option<&Value>,
4996) -> Option<Duration> {
4997    let (operation, task_id, attempt_field) = if let Some(task_id) = path
4998        .strip_prefix("/worker/workflow-tasks/")
4999        .and_then(|tail| tail.strip_suffix("/complete"))
5000    {
5001        ("complete_workflow_task", task_id, "workflow_task_attempt")
5002    } else if let Some(task_id) = path
5003        .strip_prefix("/worker/activity-tasks/")
5004        .and_then(|tail| tail.strip_suffix("/complete"))
5005    {
5006        ("complete_activity_task", task_id, "activity_attempt_id")
5007    } else {
5008        return None;
5009    };
5010    if task_id.is_empty() || task_id.contains('/') {
5011        return None;
5012    }
5013
5014    let request = request_body?.as_object()?;
5015    let lease_owner = request.get("lease_owner")?.as_str()?;
5016    if lease_owner.is_empty() {
5017        return None;
5018    }
5019    let attempt = request.get(attempt_field)?;
5020    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5021        || (attempt_field == "activity_attempt_id"
5022            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5023    {
5024        return None;
5025    }
5026
5027    let body = worker_backend_unavailable_body(error)?;
5028    let delay = body.get("retry_after_seconds")?.as_u64()?;
5029    if delay == 0
5030        || body.get("operation")?.as_str()? != operation
5031        || body.get("outcome")?.as_str()? != "unknown"
5032        || body.get("retryable") != Some(&Value::Bool(true))
5033        || body.get("worker_id")?.as_str()? != lease_owner
5034        || body.get("task_queue") != Some(&Value::Null)
5035        || body.get("task_id")?.as_str()? != task_id
5036        || body.get("lease_owner")?.as_str()? != lease_owner
5037        || body.get(attempt_field) != Some(attempt)
5038    {
5039        return None;
5040    }
5041
5042    Some(Duration::from_secs(delay))
5043}
5044
5045fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5046    let Error::Http { status, body } = error else {
5047        return None;
5048    };
5049    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5050        return None;
5051    }
5052    let body: Value = serde_json::from_str(body).ok()?;
5053    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5054}
5055
5056fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5057    let Error::Http { body, .. } = error else {
5058        return false;
5059    };
5060
5061    serde_json::from_str::<Value>(body)
5062        .ok()
5063        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5064        == Some(false)
5065}
5066
5067fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5068    let Error::Http { status, body } = error else {
5069        return None;
5070    };
5071    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5072        return None;
5073    }
5074
5075    let body = serde_json::from_str::<Value>(body).ok()?;
5076    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5077        == Some("long_poll_capacity_exhausted")
5078        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5079    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5080        return None;
5081    }
5082
5083    Some(Duration::from_secs(
5084        body.get("retry_after_seconds")
5085            .and_then(Value::as_u64)
5086            .unwrap_or_default(),
5087    ))
5088}
5089
5090fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5091    let exponent = retry.saturating_sub(1).min(31) as u32;
5092    policy
5093        .initial_backoff
5094        .saturating_mul(1_u32 << exponent)
5095        .min(policy.max_backoff)
5096}
5097
5098#[derive(Debug)]
5099pub struct ClientBuilder {
5100    base_url: String,
5101    token: Option<String>,
5102    control_token: Option<String>,
5103    worker_token: Option<String>,
5104    namespace: String,
5105    timeout: Duration,
5106    max_external_payload_bytes: usize,
5107}
5108
5109impl ClientBuilder {
5110    pub fn token(mut self, token: Option<String>) -> Self {
5111        self.token = token;
5112        self
5113    }
5114
5115    pub fn control_token(mut self, token: Option<String>) -> Self {
5116        self.control_token = token;
5117        self
5118    }
5119
5120    pub fn worker_token(mut self, token: Option<String>) -> Self {
5121        self.worker_token = token;
5122        self
5123    }
5124
5125    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5126        self.namespace = namespace.into();
5127        self
5128    }
5129
5130    pub fn timeout(mut self, timeout: Duration) -> Self {
5131        self.timeout = timeout;
5132        self
5133    }
5134
5135    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5136    /// References are fetched only from this client's authenticated runtime.
5137    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5138        self.max_external_payload_bytes = bytes;
5139        self
5140    }
5141
5142    pub fn build(self) -> Result<Client> {
5143        let base_url = self.base_url.trim_end_matches('/').to_string();
5144        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5145            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5146            .unwrap_or_else(|_| base_url.ends_with("/api"));
5147
5148        if has_sdk_api_suffix {
5149            return Err(Error::InvalidBaseUrl);
5150        }
5151
5152        Ok(Client {
5153            http: reqwest::Client::builder()
5154                .timeout(self.timeout)
5155                .redirect(reqwest::redirect::Policy::none())
5156                .build()?,
5157            base_url,
5158            token: self.token,
5159            control_token: self.control_token,
5160            worker_token: self.worker_token,
5161            namespace: self.namespace,
5162            max_external_payload_bytes: self.max_external_payload_bytes,
5163            worker_storage_admission: None,
5164            cooperative_worker_protocol: false,
5165            local_activities_enabled: false,
5166            worker_sessions_enabled: false,
5167            max_concurrent_worker_sessions: 10,
5168            worker_build_id: None,
5169            sticky_cache: None,
5170            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5171        })
5172    }
5173}
5174
5175#[derive(Clone, Debug)]
5176pub struct WorkflowHandle {
5177    client: Client,
5178    pub workflow_id: String,
5179    pub run_id: Option<String>,
5180    pub workflow_type: String,
5181}
5182
5183impl WorkflowHandle {
5184    /// Describe whichever run is current for this stable workflow instance.
5185    pub async fn describe(&self) -> Result<WorkflowDescription> {
5186        self.client.describe_workflow(&self.workflow_id).await
5187    }
5188
5189    /// Describe the run identity originally selected by this handle.
5190    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5191        let run_id = self.run_id.as_deref().ok_or_else(|| {
5192            Error::Codec("run_id is required for selected-run description".to_string())
5193        })?;
5194        self.client
5195            .describe_workflow_run(&self.workflow_id, run_id)
5196            .await
5197    }
5198
5199    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5200        self.client
5201            .signal_workflow(&self.workflow_id, signal_name, input)
5202            .await
5203    }
5204
5205    pub async fn append_message<T: Serialize>(
5206        &self,
5207        stream_name: &str,
5208        message_id: &str,
5209        input: T,
5210    ) -> Result<Value> {
5211        self.client
5212            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5213            .await
5214    }
5215
5216    /// Signal only if this handle's selected run is still current.
5217    pub async fn signal_selected_run<T: Serialize>(
5218        &self,
5219        signal_name: &str,
5220        input: T,
5221    ) -> Result<Value> {
5222        let run_id = self.run_id.as_deref().ok_or_else(|| {
5223            Error::Codec("run_id is required for selected-run signaling".to_string())
5224        })?;
5225        self.client
5226            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5227            .await
5228    }
5229
5230    /// Close whichever run is current as cancelled, without workflow cleanup.
5231    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5232        self.client
5233            .cancel_workflow(&self.workflow_id, options)
5234            .await
5235    }
5236
5237    /// Request cancellation only if this handle's selected run is still current.
5238    pub async fn cancel_selected_run(
5239        &self,
5240        options: WorkflowCommandOptions,
5241    ) -> Result<WorkflowCommandResult> {
5242        let run_id = self.run_id.as_deref().ok_or_else(|| {
5243            Error::Codec("run_id is required for selected-run cancellation".to_string())
5244        })?;
5245        self.client
5246            .cancel_workflow_run(&self.workflow_id, run_id, options)
5247            .await
5248    }
5249
5250    /// Forcefully terminate whichever run is current.
5251    pub async fn terminate(
5252        &self,
5253        options: WorkflowCommandOptions,
5254    ) -> Result<WorkflowCommandResult> {
5255        self.client
5256            .terminate_workflow(&self.workflow_id, options)
5257            .await
5258    }
5259
5260    /// Terminate only if this handle's selected run is still current.
5261    pub async fn terminate_selected_run(
5262        &self,
5263        options: WorkflowCommandOptions,
5264    ) -> Result<WorkflowCommandResult> {
5265        let run_id = self.run_id.as_deref().ok_or_else(|| {
5266            Error::Codec("run_id is required for selected-run termination".to_string())
5267        })?;
5268        self.client
5269            .terminate_workflow_run(&self.workflow_id, run_id, options)
5270            .await
5271    }
5272
5273    /// Continue this handle's failed run without repeating completed activities.
5274    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5275        let run_id = self
5276            .run_id
5277            .as_deref()
5278            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5279        self.client
5280            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5281            .await
5282    }
5283
5284    /// Execute a named, read-only query against this workflow.
5285    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5286        self.client
5287            .query_workflow(&self.workflow_id, query_name, input)
5288            .await
5289    }
5290
5291    pub async fn query_avro_value<T: Serialize>(
5292        &self,
5293        query_name: &str,
5294        input: T,
5295    ) -> Result<AvroValue> {
5296        self.client
5297            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5298            .await
5299    }
5300
5301    pub async fn update<T: Serialize>(
5302        &self,
5303        update_name: &str,
5304        input: T,
5305        request_id: Option<&str>,
5306    ) -> Result<Value> {
5307        self.client
5308            .update_workflow(&self.workflow_id, update_name, input, request_id)
5309            .await
5310    }
5311
5312    pub async fn update_avro_value<T: Serialize>(
5313        &self,
5314        update_name: &str,
5315        input: T,
5316        request_id: Option<&str>,
5317    ) -> Result<AvroValue> {
5318        self.client
5319            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5320            .await
5321    }
5322
5323    /// Query only if this handle's selected run is still current.
5324    pub async fn query_selected_run<T: Serialize>(
5325        &self,
5326        query_name: &str,
5327        input: T,
5328    ) -> Result<Value> {
5329        let run_id = self
5330            .run_id
5331            .as_deref()
5332            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5333        self.client
5334            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5335            .await
5336    }
5337
5338    /// Await the final terminal outcome of the current continue-as-new chain.
5339    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5340        self.result_target(options, None).await
5341    }
5342
5343    /// Await the final result without projecting Avro bytes through JSON.
5344    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5345        self.result_avro_value_target(options, None).await
5346    }
5347
5348    /// Await the final result and decode it into a Serde application type.
5349    pub async fn result_typed<T: DeserializeOwned>(
5350        &self,
5351        options: WorkflowResultOptions,
5352    ) -> Result<T> {
5353        let result = self.result_avro_value(options).await?;
5354        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5355    }
5356
5357    /// Await only the run identity originally selected by this handle.
5358    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5359        let run_id = self.run_id.as_deref().ok_or_else(|| {
5360            Error::Codec("run_id is required for selected-run result".to_string())
5361        })?;
5362        self.result_target(options, Some(run_id)).await
5363    }
5364
5365    /// Await the selected run's result on the lossless Avro Value surface.
5366    pub async fn result_selected_run_avro_value(
5367        &self,
5368        options: WorkflowResultOptions,
5369    ) -> Result<AvroValue> {
5370        let run_id = self.run_id.as_deref().ok_or_else(|| {
5371            Error::Codec("run_id is required for selected-run result".to_string())
5372        })?;
5373        self.result_avro_value_target(options, Some(run_id)).await
5374    }
5375
5376    /// Await the selected run and decode its result into a Serde type.
5377    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5378        &self,
5379        options: WorkflowResultOptions,
5380    ) -> Result<T> {
5381        let result = self.result_selected_run_avro_value(options).await?;
5382        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5383    }
5384
5385    async fn result_avro_value_target(
5386        &self,
5387        options: WorkflowResultOptions,
5388        selected_run_id: Option<&str>,
5389    ) -> Result<AvroValue> {
5390        let started = Instant::now();
5391
5392        loop {
5393            let description = match selected_run_id {
5394                Some(run_id) => {
5395                    self.client
5396                        .describe_workflow_run(&self.workflow_id, run_id)
5397                        .await?
5398                }
5399                None => self.describe().await?,
5400            };
5401            if description.is_completed() {
5402                return description.output_avro_value.ok_or_else(|| {
5403                    Error::Codec(
5404                        "missing_payload_envelope: typed workflow result requires output_envelope"
5405                            .to_string(),
5406                    )
5407                });
5408            }
5409            if description.is_terminal() {
5410                let outcome =
5411                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5412                return Err(match outcome.kind {
5413                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5414                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5415                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5416                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5417                });
5418            }
5419            if started.elapsed() >= options.timeout {
5420                return Err(Error::Timeout);
5421            }
5422            tokio::time::sleep(options.poll_interval).await;
5423        }
5424    }
5425
5426    async fn result_target(
5427        &self,
5428        options: WorkflowResultOptions,
5429        selected_run_id: Option<&str>,
5430    ) -> Result<Value> {
5431        let started = Instant::now();
5432
5433        loop {
5434            let description = match selected_run_id {
5435                Some(run_id) => {
5436                    self.client
5437                        .describe_workflow_run(&self.workflow_id, run_id)
5438                        .await?
5439                }
5440                None => self.describe().await?,
5441            };
5442            if description.is_completed() {
5443                return Ok(description.output.unwrap_or(Value::Null));
5444            }
5445
5446            if description.is_terminal() {
5447                let outcome =
5448                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5449                return Err(match outcome.kind {
5450                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5451                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5452                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5453                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5454                });
5455            }
5456
5457            if started.elapsed() >= options.timeout {
5458                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5459                    kind: WorkflowTerminalKind::TimedOut,
5460                    workflow_id: description
5461                        .workflow_id
5462                        .clone()
5463                        .unwrap_or_else(|| self.workflow_id.clone()),
5464                    run_id: description
5465                        .run_id
5466                        .clone()
5467                        .or_else(|| selected_run_id.map(str::to_string)),
5468                    reason: "result_wait_timeout".to_string(),
5469                    failure_category: Some("client_timeout".to_string()),
5470                    failure_id: None,
5471                    exception_type: None,
5472                    exception_class: None,
5473                    non_retryable: None,
5474                    message: Some(format!(
5475                        "workflow result was not terminal within {:?}",
5476                        options.timeout
5477                    )),
5478                    exception: None,
5479                    raw: description.raw_value(),
5480                }));
5481            }
5482
5483            tokio::time::sleep(options.poll_interval).await;
5484        }
5485    }
5486}
5487
5488#[derive(Clone, Copy, Debug)]
5489pub struct WorkflowResultOptions {
5490    pub poll_interval: Duration,
5491    pub timeout: Duration,
5492}
5493
5494impl Default for WorkflowResultOptions {
5495    fn default() -> Self {
5496        Self {
5497            poll_interval: Duration::from_millis(500),
5498            timeout: Duration::from_secs(30),
5499        }
5500    }
5501}
5502
5503#[derive(Clone, Debug, Deserialize)]
5504pub struct WorkflowDescription {
5505    pub workflow_id: Option<String>,
5506    pub run_id: Option<String>,
5507    pub workflow_type: Option<String>,
5508    pub status: Option<String>,
5509    #[serde(default)]
5510    pub closed_reason: Option<String>,
5511    #[serde(default)]
5512    pub error: Option<String>,
5513    #[serde(default)]
5514    pub failure: Option<Value>,
5515    #[serde(default)]
5516    pub exception: Option<Value>,
5517    #[serde(default)]
5518    pub failures: Vec<Value>,
5519    #[serde(default)]
5520    pub output: Option<Value>,
5521    #[serde(default)]
5522    pub output_envelope: Option<Value>,
5523    #[serde(skip)]
5524    pub output_avro_value: Option<AvroValue>,
5525    #[serde(flatten)]
5526    pub raw: HashMap<String, Value>,
5527}
5528
5529/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5530#[derive(Clone, Debug, Deserialize)]
5531pub struct WorkflowStreamDescription {
5532    pub stream_name: String,
5533    pub status: String,
5534    pub last_offset: i64,
5535    pub total_items: u64,
5536    pub pending_items: u64,
5537    #[serde(default)]
5538    pub opened_at: Option<String>,
5539    #[serde(default)]
5540    pub last_appended_at: Option<String>,
5541    #[serde(default)]
5542    pub closed_at: Option<String>,
5543    #[serde(default)]
5544    pub error_reason: Option<String>,
5545    #[serde(default)]
5546    pub retention_seconds: Option<u64>,
5547    #[serde(flatten)]
5548    pub raw: HashMap<String, Value>,
5549}
5550
5551impl WorkflowStreamDescription {
5552    pub fn is_terminal(&self) -> bool {
5553        matches!(self.status.as_str(), "closed" | "errored")
5554    }
5555}
5556
5557/// One item for direct or replay-safe append.
5558#[derive(Clone, Debug, Default)]
5559pub struct WorkflowStreamAppendItem {
5560    pub payload_envelope: Option<Value>,
5561    pub payload_reference: Option<String>,
5562    pub item_type: Option<String>,
5563    pub content_type: Option<String>,
5564    pub idempotency_key: Option<String>,
5565}
5566
5567impl WorkflowStreamAppendItem {
5568    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5569    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5570        let value = AvroValue::from_serialize(&payload)?;
5571        Ok(Self {
5572            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5573            ..Self::default()
5574        })
5575    }
5576
5577    /// Preserve an external payload URI as an opaque service-contract reference.
5578    pub fn from_reference(reference: impl Into<String>) -> Self {
5579        Self {
5580            payload_reference: Some(reference.into()),
5581            ..Self::default()
5582        }
5583    }
5584
5585    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5586        self.item_type = Some(item_type.into());
5587        self
5588    }
5589
5590    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5591        self.content_type = Some(content_type.into());
5592        self
5593    }
5594
5595    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5596        self.idempotency_key = Some(idempotency_key.into());
5597        self
5598    }
5599
5600    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5601        let mut item = serde_json::Map::new();
5602        if let Some(payload) = &self.payload_envelope {
5603            item.insert("payload".to_string(), payload.clone());
5604            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5605        }
5606        if let Some(reference) = &self.payload_reference {
5607            item.insert("payload_reference".to_string(), json!(reference));
5608        }
5609        if let Some(item_type) = &self.item_type {
5610            item.insert("item_type".to_string(), json!(item_type));
5611        }
5612        if let Some(content_type) = &self.content_type {
5613            item.insert("content_type".to_string(), json!(content_type));
5614        }
5615        if let Some(key) = derived_idempotency_key
5616            .as_ref()
5617            .or(self.idempotency_key.as_ref())
5618        {
5619            item.insert("idempotency_key".to_string(), json!(key));
5620        }
5621        Value::Object(item)
5622    }
5623}
5624
5625/// One durable item at its stable zero-based offset.
5626#[derive(Clone, Debug)]
5627pub struct WorkflowStreamItem {
5628    pub offset: u64,
5629    pub payload: Option<Value>,
5630    pub payload_envelope: Option<Value>,
5631    pub payload_reference: Option<String>,
5632    pub payload_codec: Option<String>,
5633    pub idempotency_key: Option<String>,
5634    pub item_type: Option<String>,
5635    pub content_type: Option<String>,
5636    pub origin: Option<String>,
5637    pub origin_reference: Option<String>,
5638    pub emitted_at: Option<String>,
5639    pub raw: Value,
5640}
5641
5642/// One bounded at-least-once subscription page.
5643#[derive(Clone, Debug)]
5644pub struct WorkflowStreamPage {
5645    pub stream: WorkflowStreamDescription,
5646    pub items: Vec<WorkflowStreamItem>,
5647    pub next_offset: u64,
5648    pub terminal: bool,
5649}
5650
5651/// Durable acceptance and deduplication outcome for an append request.
5652#[derive(Clone, Debug)]
5653pub struct WorkflowStreamAppendResult {
5654    pub stream: WorkflowStreamDescription,
5655    pub accepted_offsets: Vec<u64>,
5656    pub accepted: u64,
5657    pub deduped: u64,
5658}
5659
5660#[derive(Deserialize)]
5661struct WorkflowStreamListResponse {
5662    #[serde(default)]
5663    streams: Vec<WorkflowStreamDescription>,
5664}
5665
5666#[derive(Deserialize)]
5667struct WorkflowStreamDescriptionResponse {
5668    stream: WorkflowStreamDescription,
5669}
5670
5671#[derive(Deserialize)]
5672struct WorkflowStreamPageResponse {
5673    stream: WorkflowStreamDescription,
5674    #[serde(default)]
5675    items: Vec<Value>,
5676    next_offset: u64,
5677    terminal: bool,
5678}
5679
5680#[derive(Deserialize)]
5681struct WorkflowStreamAppendResponse {
5682    stream: WorkflowStreamDescription,
5683    #[serde(default)]
5684    accepted_offsets: Vec<u64>,
5685    accepted: u64,
5686    deduped: u64,
5687}
5688
5689impl WorkflowDescription {
5690    pub fn is_completed(&self) -> bool {
5691        matches!(self.status.as_deref(), Some("completed" | "Completed"))
5692    }
5693
5694    pub fn is_terminal(&self) -> bool {
5695        matches!(
5696            self.status.as_deref(),
5697            Some(
5698                "completed"
5699                    | "Completed"
5700                    | "failed"
5701                    | "Failed"
5702                    | "cancelled"
5703                    | "Cancelled"
5704                    | "terminated"
5705                    | "Terminated"
5706                    | "timed_out"
5707                    | "TimedOut",
5708            )
5709        )
5710    }
5711
5712    fn decode_payloads(&mut self) -> Result<()> {
5713        if let Some(envelope) = &self.output_envelope {
5714            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
5715            self.output = Some(value.clone().into_json()?);
5716            self.output_avro_value = Some(value);
5717        }
5718
5719        Ok(())
5720    }
5721
5722    fn raw_value(&self) -> Value {
5723        let mut data = self.raw.clone();
5724        data.insert(
5725            "workflow_id".to_string(),
5726            self.workflow_id
5727                .clone()
5728                .map(Value::String)
5729                .unwrap_or(Value::Null),
5730        );
5731        data.insert(
5732            "run_id".to_string(),
5733            self.run_id
5734                .clone()
5735                .map(Value::String)
5736                .unwrap_or(Value::Null),
5737        );
5738        data.insert(
5739            "workflow_type".to_string(),
5740            self.workflow_type
5741                .clone()
5742                .map(Value::String)
5743                .unwrap_or(Value::Null),
5744        );
5745        data.insert(
5746            "status".to_string(),
5747            self.status
5748                .clone()
5749                .map(Value::String)
5750                .unwrap_or(Value::Null),
5751        );
5752        data.insert(
5753            "closed_reason".to_string(),
5754            self.closed_reason
5755                .clone()
5756                .map(Value::String)
5757                .unwrap_or(Value::Null),
5758        );
5759        if let Some(failure) = &self.failure {
5760            data.insert("failure".to_string(), failure.clone());
5761        }
5762        if let Some(exception) = &self.exception {
5763            data.insert("exception".to_string(), exception.clone());
5764        }
5765        Value::Object(data.into_iter().collect())
5766    }
5767}
5768
5769fn workflow_terminal_outcome(
5770    description: &WorkflowDescription,
5771    workflow_id: &str,
5772    run_id: Option<&str>,
5773) -> WorkflowTerminalOutcome {
5774    let terminal_kind = description
5775        .closed_reason
5776        .as_deref()
5777        .or(description.status.as_deref())
5778        .unwrap_or("failed")
5779        .to_ascii_lowercase();
5780    let kind = match terminal_kind.as_str() {
5781        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
5782        "terminated" => WorkflowTerminalKind::Terminated,
5783        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
5784        _ => WorkflowTerminalKind::Failed,
5785    };
5786    let default_reason = match kind {
5787        WorkflowTerminalKind::Failed => "workflow_failed",
5788        WorkflowTerminalKind::Cancelled => "cancelled",
5789        WorkflowTerminalKind::Terminated => "terminated",
5790        WorkflowTerminalKind::TimedOut => "timed_out",
5791    };
5792    let failure = description
5793        .failure
5794        .as_ref()
5795        .filter(|value| value.is_object());
5796    let nested_failure = failure
5797        .and_then(|value| value.get("failures"))
5798        .and_then(Value::as_array)
5799        .and_then(|failures| failures.last())
5800        .or_else(|| description.failures.last());
5801    let exception = description
5802        .exception
5803        .clone()
5804        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
5805        .or_else(|| {
5806            nested_failure
5807                .and_then(|value| value.get("exception_payload"))
5808                .cloned()
5809        });
5810    let string_field = |name: &str| {
5811        failure
5812            .and_then(|value| value.get(name))
5813            .and_then(Value::as_str)
5814            .or_else(|| {
5815                nested_failure
5816                    .and_then(|value| value.get(name))
5817                    .and_then(Value::as_str)
5818            })
5819            .map(str::to_string)
5820    };
5821    let exception_field = |name: &str| {
5822        exception
5823            .as_ref()
5824            .and_then(|value| value.get(name))
5825            .and_then(Value::as_str)
5826            .map(str::to_string)
5827    };
5828    let message = description
5829        .error
5830        .clone()
5831        .or_else(|| string_field("message"))
5832        .or_else(|| exception_field("message"));
5833    let reason = description
5834        .raw
5835        .get("reason")
5836        .and_then(Value::as_str)
5837        .map(str::to_string)
5838        .or_else(|| {
5839            failure
5840                .and_then(|value| value.get("reason"))
5841                .and_then(Value::as_str)
5842                .map(str::to_string)
5843        })
5844        .or_else(|| description.closed_reason.clone())
5845        .unwrap_or_else(|| default_reason.to_string());
5846    let failure_id = string_field("failure_id").or_else(|| {
5847        nested_failure
5848            .and_then(|value| value.get("id"))
5849            .and_then(Value::as_str)
5850            .map(str::to_string)
5851    });
5852
5853    WorkflowTerminalOutcome {
5854        kind,
5855        workflow_id: description
5856            .workflow_id
5857            .clone()
5858            .unwrap_or_else(|| workflow_id.to_string()),
5859        run_id: description
5860            .run_id
5861            .clone()
5862            .or_else(|| run_id.map(str::to_string)),
5863        reason,
5864        failure_category: string_field("failure_category")
5865            .or_else(|| Some(default_reason.to_string())),
5866        failure_id,
5867        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
5868        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
5869        non_retryable: failure
5870            .and_then(|value| value.get("non_retryable"))
5871            .and_then(Value::as_bool)
5872            .or_else(|| {
5873                nested_failure
5874                    .and_then(|value| value.get("non_retryable"))
5875                    .and_then(Value::as_bool)
5876            }),
5877        message,
5878        exception,
5879        raw: description.raw_value(),
5880    }
5881}
5882
5883#[derive(Clone, Debug, Deserialize)]
5884pub struct RegisterWorkerResponse {
5885    pub worker_id: String,
5886    pub registered: bool,
5887    #[serde(default)]
5888    pub heartbeat_interval_seconds: Option<u64>,
5889    #[serde(default)]
5890    pub protocol_version: Option<String>,
5891    #[serde(default)]
5892    pub server_capabilities: Option<Value>,
5893}
5894
5895/// Result of gracefully removing a worker-plane registration.
5896#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5897pub struct WorkerDeregistrationEnvelope {
5898    pub worker_id: String,
5899    pub outcome: String,
5900    pub recovered_workflow_task_count: u64,
5901}
5902
5903#[derive(Clone, Debug, Deserialize)]
5904pub struct PollWorkflowTaskResponse {
5905    #[serde(default)]
5906    pub task: Option<WorkflowTask>,
5907    #[serde(default)]
5908    pub poll_status: Option<String>,
5909    #[serde(default)]
5910    pub reason: Option<String>,
5911    #[serde(default)]
5912    pub protocol_version: Option<String>,
5913    #[serde(default)]
5914    pub server_capabilities: Option<Value>,
5915}
5916
5917impl PollWorkflowTaskResponse {
5918    /// Classify this response without parsing server display text.
5919    pub fn outcome(&self) -> WorkerPollOutcome {
5920        worker_poll_outcome(
5921            self.task.is_some(),
5922            self.poll_status.as_deref(),
5923            self.reason.as_deref(),
5924        )
5925    }
5926}
5927
5928fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
5929    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
5930        return false;
5931    };
5932    let supported = capabilities
5933        .get("workflow_memo_updates")
5934        .and_then(Value::as_object)
5935        .and_then(|memo| memo.get("supported"))
5936        .and_then(Value::as_bool)
5937        == Some(true);
5938    let command_advertised = capabilities
5939        .get("supported_workflow_task_commands")
5940        .and_then(Value::as_array)
5941        .is_some_and(|commands| {
5942            commands
5943                .iter()
5944                .any(|command| command.as_str() == Some("upsert_memo"))
5945        });
5946    supported && command_advertised
5947}
5948
5949fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
5950    commands
5951        .iter()
5952        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
5953}
5954
5955#[derive(Clone, Debug, Deserialize)]
5956pub struct PollActivityTaskResponse {
5957    #[serde(default)]
5958    pub task: Option<ActivityTask>,
5959    #[serde(default)]
5960    pub poll_status: Option<String>,
5961    #[serde(default)]
5962    pub reason: Option<String>,
5963}
5964
5965impl PollActivityTaskResponse {
5966    /// Classify this response without parsing server display text.
5967    pub fn outcome(&self) -> WorkerPollOutcome {
5968        worker_poll_outcome(
5969            self.task.is_some(),
5970            self.poll_status.as_deref(),
5971            self.reason.as_deref(),
5972        )
5973    }
5974}
5975
5976#[derive(Clone, Debug, Deserialize)]
5977pub struct PollQueryTaskResponse {
5978    #[serde(default)]
5979    pub task: Option<QueryTask>,
5980    #[serde(default)]
5981    pub poll_status: Option<String>,
5982    #[serde(default)]
5983    pub reason: Option<String>,
5984}
5985
5986impl PollQueryTaskResponse {
5987    /// Classify this response without parsing server display text.
5988    pub fn outcome(&self) -> WorkerPollOutcome {
5989        worker_poll_outcome(
5990            self.task.is_some(),
5991            self.poll_status.as_deref(),
5992            self.reason.as_deref(),
5993        )
5994    }
5995}
5996
5997/// Stable classification for worker poll responses.
5998#[derive(Clone, Debug, PartialEq, Eq)]
5999pub enum WorkerPollOutcome {
6000    /// A task was leased and is available on the response.
6001    Task,
6002    /// No task was leased, but the worker should continue polling.
6003    Idle {
6004        poll_status: Option<String>,
6005        reason: Option<String>,
6006    },
6007    /// The server asked this worker to stop claiming new work.
6008    Stop {
6009        poll_status: Option<String>,
6010        reason: Option<String>,
6011    },
6012}
6013
6014impl WorkerPollOutcome {
6015    pub fn should_stop(&self) -> bool {
6016        matches!(self, Self::Stop { .. })
6017    }
6018}
6019
6020fn worker_poll_outcome(
6021    has_task: bool,
6022    poll_status: Option<&str>,
6023    reason: Option<&str>,
6024) -> WorkerPollOutcome {
6025    if worker_poll_is_stop(poll_status, reason) {
6026        return WorkerPollOutcome::Stop {
6027            poll_status: poll_status.map(str::to_string),
6028            reason: reason.map(str::to_string),
6029        };
6030    }
6031
6032    if has_task {
6033        WorkerPollOutcome::Task
6034    } else {
6035        WorkerPollOutcome::Idle {
6036            poll_status: poll_status.map(str::to_string),
6037            reason: reason.map(str::to_string),
6038        }
6039    }
6040}
6041
6042/// An ephemeral server-routed query task.
6043#[derive(Clone, Debug, Deserialize)]
6044pub struct QueryTask {
6045    pub query_task_id: String,
6046    #[serde(default = "default_workflow_task_attempt")]
6047    pub query_task_attempt: u64,
6048    #[serde(default)]
6049    pub lease_owner: Option<String>,
6050    #[serde(default)]
6051    pub workflow_id: Option<String>,
6052    #[serde(default)]
6053    pub run_id: Option<String>,
6054    pub workflow_type: String,
6055    pub query_name: String,
6056    #[serde(
6057        default = "missing_task_payload_codec",
6058        deserialize_with = "deserialize_task_payload_codec"
6059    )]
6060    pub payload_codec: String,
6061    #[serde(default)]
6062    pub workflow_arguments: Option<Value>,
6063    #[serde(default)]
6064    pub query_arguments: Option<Value>,
6065    #[serde(default)]
6066    pub history_events: Vec<HistoryEvent>,
6067    #[serde(default)]
6068    pub history_export: Option<Value>,
6069    #[serde(default)]
6070    pub run_status: Option<String>,
6071}
6072
6073#[derive(Clone, Debug, Deserialize)]
6074pub struct WorkflowTask {
6075    pub task_id: String,
6076    #[serde(default)]
6077    pub workflow_command_id: Option<String>,
6078    #[serde(default)]
6079    pub workflow_id: Option<String>,
6080    #[serde(default)]
6081    pub run_id: Option<String>,
6082    pub workflow_type: String,
6083    #[serde(default)]
6084    pub cancel_requested: bool,
6085    #[serde(
6086        default = "missing_task_payload_codec",
6087        deserialize_with = "deserialize_task_payload_codec"
6088    )]
6089    pub payload_codec: String,
6090    #[serde(default)]
6091    pub arguments: Option<Value>,
6092    #[serde(default)]
6093    pub history_events: Vec<HistoryEvent>,
6094    #[serde(default)]
6095    pub total_history_events: Option<u64>,
6096    #[serde(default)]
6097    pub history_size_bytes: Option<u64>,
6098    #[serde(default)]
6099    pub continue_as_new_recommended: Option<bool>,
6100    #[serde(default)]
6101    pub history_budget_pressure: Option<String>,
6102    #[serde(default)]
6103    pub next_history_page_token: Option<String>,
6104    #[serde(default = "default_workflow_task_attempt")]
6105    pub workflow_task_attempt: u64,
6106    #[serde(default)]
6107    pub workflow_signal_id: Option<String>,
6108    #[serde(default)]
6109    pub signal_name: Option<String>,
6110    #[serde(default)]
6111    pub signal_arguments: Option<Value>,
6112    #[serde(default)]
6113    pub workflow_update_id: Option<String>,
6114    #[serde(default)]
6115    pub update_name: Option<String>,
6116    #[serde(default)]
6117    pub lease_owner: Option<String>,
6118}
6119
6120impl WorkflowTask {
6121    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6122        self.history_events.extend(page.history_events);
6123
6124        if page.total_history_events.is_some() {
6125            self.total_history_events = page.total_history_events;
6126        }
6127
6128        self.next_history_page_token = page
6129            .next_history_page_token
6130            .filter(|token| !token.is_empty());
6131    }
6132}
6133
6134#[derive(Clone, Debug, Deserialize)]
6135struct WorkflowTaskHistoryPage {
6136    #[serde(default)]
6137    history_events: Vec<HistoryEvent>,
6138    #[serde(default)]
6139    total_history_events: Option<u64>,
6140    #[serde(default)]
6141    next_history_page_token: Option<String>,
6142}
6143
6144#[derive(Clone, Debug, Deserialize)]
6145pub struct ActivityTask {
6146    pub task_id: String,
6147    #[serde(default)]
6148    pub activity_attempt_id: Option<String>,
6149    #[serde(default)]
6150    pub attempt_id: Option<String>,
6151    pub activity_type: String,
6152    #[serde(
6153        default = "missing_task_payload_codec",
6154        deserialize_with = "deserialize_task_payload_codec"
6155    )]
6156    pub payload_codec: String,
6157    #[serde(default)]
6158    pub arguments: Option<Value>,
6159    #[serde(default = "default_attempt_number")]
6160    pub attempt_number: u64,
6161    #[serde(default)]
6162    pub lease_owner: Option<String>,
6163}
6164
6165#[derive(Clone, Debug, Serialize, Deserialize)]
6166pub struct HistoryEvent {
6167    #[serde(alias = "type")]
6168    pub event_type: String,
6169    #[serde(default)]
6170    pub payload: Value,
6171    #[serde(flatten)]
6172    pub raw: HashMap<String, Value>,
6173}
6174
6175/// One decoded signal in the committed workflow-history snapshot.
6176#[derive(Clone, Debug, PartialEq)]
6177pub struct QuerySignal {
6178    pub id: Option<String>,
6179    pub name: String,
6180    pub arguments: Vec<Value>,
6181    avro_arguments: Vec<AvroValue>,
6182    pub workflow_sequence: Option<u64>,
6183}
6184
6185impl QuerySignal {
6186    /// Lossless fixed Avro Value arguments for this committed signal.
6187    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6188        &self.avro_arguments
6189    }
6190}
6191
6192/// Immutable state supplied to a registered query handler.
6193///
6194/// This context intentionally exposes no activity, signal-wait, or command
6195/// APIs. Query handlers inspect committed history and return a value; query
6196/// completion does not append an event or advance deterministic execution.
6197#[derive(Clone, Debug)]
6198pub struct QueryContext {
6199    pub workflow_id: Option<String>,
6200    pub run_id: Option<String>,
6201    pub workflow_type: String,
6202    pub run_status: Option<String>,
6203    workflow_input: Value,
6204    workflow_input_avro_value: AvroValue,
6205    history_events: Arc<Vec<HistoryEvent>>,
6206    signal_events: Arc<Vec<QuerySignal>>,
6207}
6208
6209impl QueryContext {
6210    /// The normalized argument list used to start the workflow.
6211    pub fn workflow_input(&self) -> &Value {
6212        &self.workflow_input
6213    }
6214
6215    /// The lossless fixed Avro Value argument list used to start the workflow.
6216    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6217        &self.workflow_input_avro_value
6218    }
6219
6220    /// The immutable committed history used for this query snapshot.
6221    pub fn history_events(&self) -> &[HistoryEvent] {
6222        self.history_events.as_slice()
6223    }
6224
6225    /// All decoded signals in committed workflow order.
6226    pub fn signal_events(&self) -> &[QuerySignal] {
6227        self.signal_events.as_slice()
6228    }
6229
6230    /// Decoded argument lists for each committed signal with `signal_name`.
6231    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6232        self.signal_events
6233            .iter()
6234            .filter(|signal| signal.name == signal_name)
6235            .map(|signal| signal.arguments.clone())
6236            .collect()
6237    }
6238
6239    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6240    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6241        self.signal_events
6242            .iter()
6243            .filter(|signal| signal.name == signal_name)
6244            .map(|signal| signal.avro_arguments.clone())
6245            .collect()
6246    }
6247}
6248
6249#[derive(Clone, Debug, Deserialize)]
6250pub struct ActivityHeartbeatResponse {
6251    #[serde(default)]
6252    pub cancel_requested: bool,
6253    #[serde(default)]
6254    pub heartbeat_recorded: bool,
6255    #[serde(default)]
6256    pub can_continue: Option<bool>,
6257    #[serde(default)]
6258    pub reason: Option<String>,
6259    #[serde(default)]
6260    pub run_closed_reason: Option<String>,
6261    #[serde(default)]
6262    pub run_closed_at: Option<String>,
6263    #[serde(default)]
6264    pub lease_expires_at: Option<String>,
6265    #[serde(default)]
6266    pub last_heartbeat_at: Option<String>,
6267}
6268
6269impl ActivityHeartbeatResponse {
6270    /// Whether the activity should stop instead of attempting completion.
6271    pub fn should_stop(&self) -> bool {
6272        self.cancel_requested || self.can_continue == Some(false)
6273    }
6274}
6275
6276fn missing_task_payload_codec() -> String {
6277    MISSING_TASK_PAYLOAD_CODEC.to_string()
6278}
6279
6280fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6281where
6282    D: Deserializer<'de>,
6283{
6284    Ok(match Value::deserialize(deserializer)? {
6285        Value::String(codec) => codec,
6286        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6287        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6288    })
6289}
6290
6291fn default_workflow_task_attempt() -> u64 {
6292    1
6293}
6294
6295fn default_attempt_number() -> u64 {
6296    1
6297}
6298
6299type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6300type WorkflowHandler = Arc<dyn Fn(WorkflowContext, AvroValue) -> WorkflowFuture + Send + Sync>;
6301type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6302type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6303type ReplayedWorkflowHandler =
6304    Arc<dyn Fn(WorkflowContext, AvroValue) -> ReplayedWorkflowInvocation + Send + Sync>;
6305type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6306type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6307type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6308type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6309type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6310type ReplayedQueryHandler = Arc<
6311    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6312        + Send
6313        + Sync,
6314>;
6315type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6316
6317struct ReplayedWorkflowInvocation {
6318    future: WorkflowFuture,
6319    snapshot: WorkflowStateSnapshot,
6320}
6321
6322#[derive(Clone)]
6323struct RegisteredWorkflow {
6324    execute: WorkflowHandler,
6325    replay: Option<ReplayedWorkflowHandler>,
6326    state_type: Option<TypeId>,
6327    definition_fingerprint: Option<String>,
6328}
6329
6330fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6331    names
6332        .iter()
6333        .map(|name| {
6334            json!({
6335                "name": name,
6336                "parameters": [{
6337                    "name": "args",
6338                    "position": 0,
6339                    "required": false,
6340                    "variadic": true,
6341                    "type": null,
6342                    "allows_null": true,
6343                    "default_available": false,
6344                    "default": null,
6345                }],
6346            })
6347        })
6348        .collect()
6349}
6350
6351#[derive(Debug)]
6352struct WorkflowTaskDecision {
6353    commands: Vec<Value>,
6354    message_stream_cursors: Vec<Value>,
6355    message_stream_waits: Vec<Value>,
6356    cancellation_delivery: Option<CancellationDelivery>,
6357    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6358    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6359}
6360
6361enum PreparedWorkflowTask {
6362    Decision(WorkflowTaskDecision),
6363    Execution {
6364        task: WorkflowTask,
6365        context: WorkflowContext,
6366        future: WorkflowFuture,
6367    },
6368}
6369
6370impl WorkflowTaskDecision {
6371    fn without_message_streams(commands: Vec<Value>) -> Self {
6372        Self {
6373            commands,
6374            message_stream_cursors: Vec::new(),
6375            message_stream_waits: Vec::new(),
6376            cancellation_delivery: None,
6377            cancellation_scope_opening: None,
6378            cancellation_scope_delivery: None,
6379        }
6380    }
6381}
6382
6383#[derive(Clone)]
6384enum RegisteredQuery {
6385    Snapshot(QueryHandler),
6386    Replayed {
6387        state_type: TypeId,
6388        handler: ReplayedQueryHandler,
6389    },
6390}
6391
6392#[derive(Clone, Debug)]
6393pub struct WorkerHeartbeatObservation {
6394    pub worker_id: String,
6395    pub task_queue: String,
6396    pub acknowledged_at_unix_millis: u64,
6397    pub acknowledgement: Value,
6398}
6399
6400/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6401///
6402/// Expected empty long polls and explicit Server capacity backpressure are
6403/// normal worker states. Capacity backpressure honors the advertised retry
6404/// delay without consuming this retry budget. Other transport failures,
6405/// retryable HTTP 408/429 responses, and server errors are retried with capped
6406/// exponential backoff. Authentication, protocol, codec, and handler failures
6407/// are never retried by the worker.
6408/// Explicit storage admission pauses also preserve the already-serialized worker
6409/// request without consuming this budget or rerunning its handler. The delay is
6410/// capped by `max_backoff`, and shutdown interrupts storage waits.
6411/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6412/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6413/// and `max_retries = 0` disables ordinary retries in either mode.
6414#[derive(Clone, Copy, Debug)]
6415pub struct WorkerRetryPolicy {
6416    /// Number of retries after the initial request fails.
6417    pub max_retries: usize,
6418    /// Delay before the first retry.
6419    pub initial_backoff: Duration,
6420    /// Maximum delay between retries.
6421    pub max_backoff: Duration,
6422}
6423
6424impl Default for WorkerRetryPolicy {
6425    fn default() -> Self {
6426        Self {
6427            max_retries: 5,
6428            initial_backoff: Duration::from_millis(100),
6429            max_backoff: Duration::from_secs(5),
6430        }
6431    }
6432}
6433
6434#[derive(Clone, Debug)]
6435struct WorkerStorageAdmission {
6436    policy: WorkerRetryPolicy,
6437    stop: Arc<AtomicBool>,
6438}
6439
6440struct StopWorkerOnDrop(Arc<AtomicBool>);
6441
6442impl Drop for StopWorkerOnDrop {
6443    fn drop(&mut self) {
6444        self.0.store(true, Ordering::SeqCst);
6445    }
6446}
6447
6448async fn wait_for_worker_stop(stop: &AtomicBool) {
6449    while !stop.load(Ordering::SeqCst) {
6450        tokio::time::sleep(Duration::from_millis(100)).await;
6451    }
6452}
6453
6454#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6455enum ManagedPollOutcome {
6456    Idle,
6457    Handled,
6458    Stop,
6459}
6460
6461#[derive(Clone)]
6462pub struct Worker {
6463    client: Client,
6464    worker_id: String,
6465    task_queue: String,
6466    workflows: HashMap<String, RegisteredWorkflow>,
6467    activities: HashMap<String, ActivityHandler>,
6468    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6469    signals: HashMap<String, Vec<String>>,
6470    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6471    max_concurrent_workflow_tasks: usize,
6472    max_concurrent_activity_tasks: usize,
6473    poll_timeout: Duration,
6474    heartbeat_interval: Duration,
6475    retry_policy: WorkerRetryPolicy,
6476    recover_transient_outages: bool,
6477    run_stop: Option<Arc<AtomicBool>>,
6478    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6479    cooperative_cancellation_enabled: bool,
6480    allow_cancellation_scope_authoring: bool,
6481    allow_cancellation_scope_delivery: bool,
6482    cooperative_registration_confirmed: Arc<AtomicBool>,
6483    local_registration_confirmed: Arc<AtomicBool>,
6484    session_registration_confirmed: Arc<AtomicBool>,
6485    sticky_registration_confirmed: Arc<AtomicBool>,
6486    resource_capabilities: Vec<String>,
6487    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6488}
6489
6490impl Worker {
6491    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6492        Self {
6493            client,
6494            worker_id: default_worker_id(),
6495            task_queue: task_queue.into(),
6496            workflows: HashMap::new(),
6497            activities: HashMap::new(),
6498            queries: HashMap::new(),
6499            signals: HashMap::new(),
6500            updates: HashMap::new(),
6501            max_concurrent_workflow_tasks: 10,
6502            max_concurrent_activity_tasks: 10,
6503            poll_timeout: Duration::from_secs(30),
6504            heartbeat_interval: Duration::from_secs(60),
6505            retry_policy: WorkerRetryPolicy::default(),
6506            recover_transient_outages: false,
6507            run_stop: None,
6508            heartbeat_observer: None,
6509            cooperative_cancellation_enabled: false,
6510            allow_cancellation_scope_authoring: false,
6511            allow_cancellation_scope_delivery: false,
6512            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6513            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6514            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6515            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
6516            resource_capabilities: Vec::new(),
6517            sessions: Arc::new(Mutex::new(HashMap::new())),
6518        }
6519    }
6520
6521    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6522        self.worker_id = worker_id.into();
6523        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6524        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6525        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6526        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
6527        self.client.reset_sticky_cache();
6528        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6529        self
6530    }
6531
6532    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6533        self.poll_timeout = timeout;
6534        self
6535    }
6536
6537    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6538        self.heartbeat_interval = interval;
6539        self
6540    }
6541
6542    /// Explicitly enable inline local activities in this workflow worker.
6543    ///
6544    /// The worker advertises the capability to Server only when enabled.
6545    /// These callbacks must yield to Tokio and have idempotent side effects.
6546    /// Cooperative prepared local supervision is a separate capability.
6547    pub fn local_activities(mut self, enabled: bool) -> Self {
6548        self.client.local_activities_enabled = enabled;
6549        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6550        self
6551    }
6552
6553    /// Opt in to separate cooperative workflow cancellation requests.
6554    ///
6555    /// Registration requires the Server to acknowledge this exact worker,
6556    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6557    /// processing uses canonical delivery and activity ownership fences.
6558    /// Existing terminal cancel and terminate operations remain terminal.
6559    /// The default is disabled, preserving ordinary protocol 1.19 workers.
6560    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6561    /// and [`Worker::run_until`] register automatically.
6562    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6563        self.cooperative_cancellation_enabled = enabled;
6564        self.client.cooperative_worker_protocol = enabled;
6565        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6566        self
6567    }
6568
6569    /// Enable candidate scope authoring without advertising scoped execution.
6570    #[doc(hidden)]
6571    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6572        self.allow_cancellation_scope_authoring = enabled;
6573        self
6574    }
6575
6576    /// Enable the candidate scoped call consumer with canonical authoring.
6577    #[doc(hidden)]
6578    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6579        self.allow_cancellation_scope_delivery = enabled;
6580        self
6581    }
6582
6583    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6584    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6585        self.retry_policy = policy;
6586        self
6587    }
6588
6589    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6590    ///
6591    /// Retries preserve the poll request identity and use capped exponential
6592    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6593    /// An in-flight poll is allowed to finish so leased work is not discarded.
6594    /// Authentication, protocol, codec, handler and task settlement failures
6595    /// remain errors. Registration and deregistration are not retried here.
6596    ///
6597    /// The default is disabled, preserving the bounded retry contract.
6598    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6599    /// even when this option is enabled.
6600    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6601        self.recover_transient_outages = enabled;
6602        self
6603    }
6604
6605    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6606    where
6607        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6608    {
6609        self.heartbeat_observer = Some(Arc::new(observer));
6610        self
6611    }
6612
6613    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6614        self.max_concurrent_workflow_tasks = count.max(1);
6615        self
6616    }
6617
6618    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6619        self.max_concurrent_activity_tasks = count.max(1);
6620        self
6621    }
6622
6623    /// Register a workflow handler.
6624    ///
6625    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6626    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6627    /// while acquiring or decoding a worker task remain worker-operation
6628    /// failures and do not get converted into workflow outcomes.
6629    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6630    where
6631        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6632        Fut: Future<Output = Result<Value>> + Send + 'static,
6633    {
6634        let handler = Arc::new(handler);
6635        self.workflows.insert(
6636            workflow_type.into(),
6637            RegisteredWorkflow {
6638                execute: Arc::new(move |ctx, input| {
6639                    let handler = Arc::clone(&handler);
6640                    Box::pin(async move {
6641                        let result = handler(ctx, input.into_json()?).await?;
6642                        AvroValue::from_serialize(&result)
6643                    })
6644                }),
6645                replay: None,
6646                state_type: None,
6647                definition_fingerprint: None,
6648            },
6649        );
6650    }
6651
6652    /// Register a workflow with one Serde request value and a Serde result.
6653    ///
6654    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
6655    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
6656    /// workflow-specific schema. A task must contain zero arguments for a unit
6657    /// request or exactly one argument for every other request type.
6658    ///
6659    /// See the runnable
6660    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
6661    /// for typed workflow and activity contracts with retry and timeout policy.
6662    pub fn register_typed_workflow<I, O, F, Fut>(
6663        &mut self,
6664        workflow_type: impl Into<String>,
6665        handler: F,
6666    ) where
6667        I: DeserializeOwned + Send + 'static,
6668        O: Serialize + Send + 'static,
6669        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
6670        Fut: Future<Output = Result<O>> + Send + 'static,
6671    {
6672        let workflow_type = workflow_type.into();
6673        let handler_name = workflow_type.clone();
6674        let handler = Arc::new(handler);
6675        self.workflows.insert(
6676            workflow_type,
6677            RegisteredWorkflow {
6678                execute: Arc::new(move |ctx, input| {
6679                    let handler = Arc::clone(&handler);
6680                    let handler_name = handler_name.clone();
6681                    Box::pin(async move {
6682                        let input =
6683                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6684                        let result = handler(ctx, input).await?;
6685                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6686                    })
6687                }),
6688                replay: None,
6689                state_type: None,
6690                definition_fingerprint: None,
6691            },
6692        );
6693    }
6694
6695    /// Register a workflow on the lossless fixed Avro Value surface.
6696    pub fn register_workflow_avro_value<F, Fut>(
6697        &mut self,
6698        workflow_type: impl Into<String>,
6699        handler: F,
6700    ) where
6701        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
6702        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6703    {
6704        self.workflows.insert(
6705            workflow_type.into(),
6706            RegisteredWorkflow {
6707                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
6708                replay: None,
6709                state_type: None,
6710                definition_fingerprint: None,
6711            },
6712        );
6713    }
6714
6715    /// Register a workflow whose typed instance state can be reconstructed for queries.
6716    ///
6717    /// `state_factory` creates a fresh instance for every normal workflow task and
6718    /// query replay. The workflow handler is the single source of truth for state
6719    /// transitions: it updates [`WorkflowInstance`] after activities and signals
6720    /// resolve. Query replay runs this same handler over committed history and
6721    /// discards any commands it would emit.
6722    pub fn register_replayed_workflow<S, Factory, F, Fut>(
6723        &mut self,
6724        workflow_type: impl Into<String>,
6725        state_factory: Factory,
6726        handler: F,
6727    ) where
6728        S: Clone + Send + Sync + 'static,
6729        Factory: Fn() -> S + Send + Sync + 'static,
6730        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6731        Fut: Future<Output = Result<Value>> + Send + 'static,
6732    {
6733        let state_factory = Arc::new(state_factory);
6734        let handler = Arc::new(handler);
6735
6736        let execute_factory = Arc::clone(&state_factory);
6737        let execute_handler = Arc::clone(&handler);
6738        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6739            let state = WorkflowInstance::new(execute_factory());
6740            let handler = Arc::clone(&execute_handler);
6741            Box::pin(async move {
6742                let result = handler(ctx, input.into_json()?, state).await?;
6743                AvroValue::from_serialize(&result)
6744            }) as WorkflowFuture
6745        });
6746
6747        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6748            let state = WorkflowInstance::new(state_factory());
6749            let snapshot_state = state.clone();
6750            let snapshot: WorkflowStateSnapshot =
6751                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6752            let replay_handler = Arc::clone(&handler);
6753            let future = async move {
6754                let result = replay_handler(ctx, input.into_json()?, state).await?;
6755                AvroValue::from_serialize(&result)
6756            };
6757            ReplayedWorkflowInvocation {
6758                future: Box::pin(future),
6759                snapshot,
6760            }
6761        });
6762
6763        self.workflows.insert(
6764            workflow_type.into(),
6765            RegisteredWorkflow {
6766                execute,
6767                replay: Some(replay),
6768                state_type: Some(TypeId::of::<S>()),
6769                definition_fingerprint: None,
6770            },
6771        );
6772    }
6773
6774    /// Register a replayable workflow with one Serde request value and result.
6775    ///
6776    /// Normal task execution and instance-state query replay both decode and
6777    /// encode through the fixed Avro Value codec. The state factory and handler
6778    /// otherwise follow [`Worker::register_replayed_workflow`].
6779    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
6780        &mut self,
6781        workflow_type: impl Into<String>,
6782        state_factory: Factory,
6783        handler: F,
6784    ) where
6785        I: DeserializeOwned + Send + 'static,
6786        O: Serialize + Send + 'static,
6787        S: Clone + Send + Sync + 'static,
6788        Factory: Fn() -> S + Send + Sync + 'static,
6789        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6790        Fut: Future<Output = Result<O>> + Send + 'static,
6791    {
6792        let workflow_type = workflow_type.into();
6793        let state_factory = Arc::new(state_factory);
6794        let handler = Arc::new(handler);
6795
6796        let execute_name = workflow_type.clone();
6797        let execute_factory = Arc::clone(&state_factory);
6798        let execute_handler = Arc::clone(&handler);
6799        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6800            let state = WorkflowInstance::new(execute_factory());
6801            let handler = Arc::clone(&execute_handler);
6802            let handler_name = execute_name.clone();
6803            Box::pin(async move {
6804                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6805                let result = handler(ctx, input, state).await?;
6806                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6807            }) as WorkflowFuture
6808        });
6809
6810        let replay_name = workflow_type.clone();
6811        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6812            let state = WorkflowInstance::new(state_factory());
6813            let snapshot_state = state.clone();
6814            let snapshot: WorkflowStateSnapshot =
6815                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6816            let handler = Arc::clone(&handler);
6817            let handler_name = replay_name.clone();
6818            let future = async move {
6819                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6820                let result = handler(ctx, input, state).await?;
6821                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6822            };
6823            ReplayedWorkflowInvocation {
6824                future: Box::pin(future),
6825                snapshot,
6826            }
6827        });
6828
6829        self.workflows.insert(
6830            workflow_type,
6831            RegisteredWorkflow {
6832                execute,
6833                replay: Some(replay),
6834                state_type: Some(TypeId::of::<S>()),
6835                definition_fingerprint: None,
6836            },
6837        );
6838    }
6839
6840    /// Declare the signal names consumed by a registered workflow.
6841    ///
6842    /// Call this after registering the workflow and before starting the worker.
6843    /// Names read through `wait_signal` or `signals` need a declaration for
6844    /// Server command admission. Arguments remain arbitrary positional values,
6845    /// including lossless Avro values. This replaces the previous declaration;
6846    /// an empty slice declares no signals. Names are sorted and deduplicated.
6847    /// Existing runs retain the declarations captured when they started.
6848    pub fn declare_workflow_signals(
6849        &mut self,
6850        workflow_type: &str,
6851        signal_names: &[&str],
6852    ) -> Result<()> {
6853        if !self.workflows.contains_key(workflow_type) {
6854            return Err(Error::Codec(format!(
6855                "workflow type {workflow_type:?} is not registered"
6856            )));
6857        }
6858        if signal_names
6859            .iter()
6860            .any(|name| name.is_empty() || *name != name.trim())
6861        {
6862            return Err(Error::Codec(
6863                "signal names must be non-empty and have no surrounding whitespace".into(),
6864            ));
6865        }
6866        let mut names = signal_names
6867            .iter()
6868            .map(|name| (*name).to_string())
6869            .collect::<Vec<_>>();
6870        names.sort();
6871        names.dedup();
6872        self.signals.insert(workflow_type.to_string(), names);
6873        Ok(())
6874    }
6875
6876    /// Bind a registered workflow to compile-time embedded source for safe redrive.
6877    ///
6878    /// Supply `include_str!` values for the workflow body and every helper whose
6879    /// behavior can affect replay. A handler re-registration clears the local
6880    /// identity; call this after registering the final handler. The server
6881    /// rejects reusing a worker ID when its prior fingerprint disappears.
6882    /// Workflows without source identity remain runnable but cannot be safely redriven.
6883    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
6884    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
6885    pub fn set_workflow_definition_sources(
6886        &mut self,
6887        workflow_type: &str,
6888        sources: &[&str],
6889    ) -> Result<()> {
6890        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
6891            return Err(Error::Codec(
6892                "workflow definition sources must be non-empty".to_string(),
6893            ));
6894        }
6895        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
6896            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
6897        })?;
6898        let mut hasher = Sha256::new();
6899        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
6900        hasher.update((workflow_type.len() as u64).to_be_bytes());
6901        hasher.update(workflow_type.as_bytes());
6902        for source in sources {
6903            hasher.update((source.len() as u64).to_be_bytes());
6904            hasher.update(source.as_bytes());
6905        }
6906        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
6907        Ok(())
6908    }
6909
6910    /// Register a replayable workflow on the lossless fixed Avro Value surface.
6911    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
6912        &mut self,
6913        workflow_type: impl Into<String>,
6914        state_factory: Factory,
6915        handler: F,
6916    ) where
6917        S: Clone + Send + Sync + 'static,
6918        Factory: Fn() -> S + Send + Sync + 'static,
6919        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
6920        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6921    {
6922        let state_factory = Arc::new(state_factory);
6923        let handler = Arc::new(handler);
6924
6925        let execute_factory = Arc::clone(&state_factory);
6926        let execute_handler = Arc::clone(&handler);
6927        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6928            let state = WorkflowInstance::new(execute_factory());
6929            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
6930        });
6931
6932        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
6933            let state = WorkflowInstance::new(state_factory());
6934            let snapshot_state = state.clone();
6935            let snapshot: WorkflowStateSnapshot =
6936                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
6937            ReplayedWorkflowInvocation {
6938                future: Box::pin(handler(ctx, input, state)),
6939                snapshot,
6940            }
6941        });
6942
6943        self.workflows.insert(
6944            workflow_type.into(),
6945            RegisteredWorkflow {
6946                execute,
6947                replay: Some(replay),
6948                state_type: Some(TypeId::of::<S>()),
6949                definition_fingerprint: None,
6950            },
6951        );
6952    }
6953
6954    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
6955    where
6956        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
6957        Fut: Future<Output = Result<Value>> + Send + 'static,
6958    {
6959        let handler = Arc::new(handler);
6960        self.activities.insert(
6961            activity_type.into(),
6962            Arc::new(move |ctx, args| {
6963                let handler = Arc::clone(&handler);
6964                Box::pin(async move {
6965                    let result = handler(ctx, args.into_json()?).await?;
6966                    AvroValue::from_serialize(&result)
6967                })
6968            }),
6969        );
6970    }
6971
6972    /// Register an activity with one Serde request value and a Serde result.
6973    ///
6974    /// Inputs and results use the platform's fixed Avro Value schema. Shape
6975    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
6976    /// with the activity name and Rust type.
6977    pub fn register_typed_activity<I, O, F, Fut>(
6978        &mut self,
6979        activity_type: impl Into<String>,
6980        handler: F,
6981    ) where
6982        I: DeserializeOwned + Send + 'static,
6983        O: Serialize + Send + 'static,
6984        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
6985        Fut: Future<Output = Result<O>> + Send + 'static,
6986    {
6987        let activity_type = activity_type.into();
6988        let handler_name = activity_type.clone();
6989        let handler = Arc::new(handler);
6990        self.activities.insert(
6991            activity_type,
6992            Arc::new(move |ctx, input| {
6993                let handler = Arc::clone(&handler);
6994                let handler_name = handler_name.clone();
6995                Box::pin(async move {
6996                    let input =
6997                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
6998                    let result = handler(ctx, input).await?;
6999                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
7000                })
7001            }),
7002        );
7003    }
7004
7005    /// Register an activity on the lossless fixed Avro Value surface.
7006    pub fn register_activity_avro_value<F, Fut>(
7007        &mut self,
7008        activity_type: impl Into<String>,
7009        handler: F,
7010    ) where
7011        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
7012        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7013    {
7014        self.activities.insert(
7015            activity_type.into(),
7016            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7017        );
7018    }
7019
7020    /// Register a named, read-only query handler for a workflow type.
7021    ///
7022    /// The workflow type must also be registered with [`Worker::register_workflow`]
7023    /// before the worker runs. The handler receives only an immutable committed
7024    /// state snapshot and normalized query arguments.
7025    pub fn register_query<F, Fut>(
7026        &mut self,
7027        workflow_type: impl Into<String>,
7028        query_name: impl Into<String>,
7029        handler: F,
7030    ) where
7031        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7032        Fut: Future<Output = Result<Value>> + Send + 'static,
7033    {
7034        let handler = Arc::new(handler);
7035        self.queries
7036            .entry(workflow_type.into())
7037            .or_default()
7038            .insert(
7039                query_name.into(),
7040                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
7041                    let handler = Arc::clone(&handler);
7042                    Box::pin(async move {
7043                        let result = handler(ctx, args.into_json()?).await?;
7044                        AvroValue::from_serialize(&result)
7045                    })
7046                })),
7047            );
7048    }
7049
7050    /// Register a query handler on the lossless fixed Avro Value surface.
7051    pub fn register_query_avro_value<F, Fut>(
7052        &mut self,
7053        workflow_type: impl Into<String>,
7054        query_name: impl Into<String>,
7055        handler: F,
7056    ) where
7057        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7058        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7059    {
7060        self.queries
7061            .entry(workflow_type.into())
7062            .or_default()
7063            .insert(
7064                query_name.into(),
7065                RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7066            );
7067    }
7068
7069    /// Register a named query against deterministically replayed instance state.
7070    ///
7071    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7072    /// same state type `S`. The handler receives an immutable, detached state
7073    /// clone, so successful and failed queries cannot affect workflow execution
7074    /// or the state reconstructed by a later query.
7075    pub fn register_replayed_query<S, F, Fut>(
7076        &mut self,
7077        workflow_type: impl Into<String>,
7078        query_name: impl Into<String>,
7079        handler: F,
7080    ) where
7081        S: Clone + Send + Sync + 'static,
7082        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7083        Fut: Future<Output = Result<Value>> + Send + 'static,
7084    {
7085        let handler = Arc::new(handler);
7086        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7087            let state = state.downcast::<S>().map_err(|_| {
7088                "registered query state type does not match the replayed workflow state".to_string()
7089            })?;
7090            let handler = Arc::clone(&handler);
7091            Ok(Box::pin(async move {
7092                let result = handler(ctx, state, args.into_json()?).await?;
7093                AvroValue::from_serialize(&result)
7094            }))
7095        });
7096
7097        self.queries
7098            .entry(workflow_type.into())
7099            .or_default()
7100            .insert(
7101                query_name.into(),
7102                RegisteredQuery::Replayed {
7103                    state_type: TypeId::of::<S>(),
7104                    handler: erased_handler,
7105                },
7106            );
7107    }
7108
7109    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7110    pub fn register_replayed_query_avro_value<S, F, Fut>(
7111        &mut self,
7112        workflow_type: impl Into<String>,
7113        query_name: impl Into<String>,
7114        handler: F,
7115    ) where
7116        S: Clone + Send + Sync + 'static,
7117        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7118        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7119    {
7120        let handler = Arc::new(handler);
7121        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7122            let state = state.downcast::<S>().map_err(|_| {
7123                "registered query state type does not match the replayed workflow state".to_string()
7124            })?;
7125            Ok(Box::pin(handler(ctx, state, args)))
7126        });
7127
7128        self.queries
7129            .entry(workflow_type.into())
7130            .or_default()
7131            .insert(
7132                query_name.into(),
7133                RegisteredQuery::Replayed {
7134                    state_type: TypeId::of::<S>(),
7135                    handler: erased_handler,
7136                },
7137            );
7138    }
7139
7140    /// Register a synchronous workflow update handler.
7141    pub fn register_update<F, Fut>(
7142        &mut self,
7143        workflow_type: impl Into<String>,
7144        update_name: impl Into<String>,
7145        handler: F,
7146    ) where
7147        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7148        Fut: Future<Output = Result<Value>> + Send + 'static,
7149    {
7150        let handler = Arc::new(handler);
7151        self.updates
7152            .entry(workflow_type.into())
7153            .or_default()
7154            .insert(
7155                update_name.into(),
7156                Arc::new(move |ctx, args| {
7157                    let handler = Arc::clone(&handler);
7158                    Box::pin(async move {
7159                        let result = handler(ctx, args.into_json()?).await?;
7160                        AvroValue::from_serialize(&result)
7161                    })
7162                }),
7163            );
7164    }
7165
7166    /// Register an update handler on the lossless fixed Avro Value surface.
7167    pub fn register_update_avro_value<F, Fut>(
7168        &mut self,
7169        workflow_type: impl Into<String>,
7170        update_name: impl Into<String>,
7171        handler: F,
7172    ) where
7173        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7174        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7175    {
7176        self.updates
7177            .entry(workflow_type.into())
7178            .or_default()
7179            .insert(
7180                update_name.into(),
7181                Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7182            );
7183    }
7184
7185    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7186        self.sticky_registration_confirmed
7187            .store(false, Ordering::SeqCst);
7188        self.session_registration_confirmed
7189            .store(false, Ordering::SeqCst);
7190        for capability in &self.resource_capabilities {
7191            worker_session::validate_resource_capability(capability)?;
7192        }
7193        self.local_registration_confirmed
7194            .store(false, Ordering::SeqCst);
7195        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7196            return Err(Error::CooperativeCancellationUnavailable(
7197                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7198            ));
7199        }
7200        let mut command_contracts = serde_json::Map::new();
7201        for workflow_type in self.workflows.keys() {
7202            let mut queries = self
7203                .queries
7204                .get(workflow_type)
7205                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7206                .unwrap_or_default();
7207            queries.sort();
7208            let mut updates = self
7209                .updates
7210                .get(workflow_type)
7211                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7212                .unwrap_or_default();
7213            updates.sort();
7214            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7215            command_contracts.insert(
7216                workflow_type.clone(),
7217                json!({
7218                    "queries": queries,
7219                    "query_contracts": argument_vector_contracts(&queries),
7220                    "signals": signals,
7221                    "signal_contracts": argument_vector_contracts(&signals),
7222                    "updates": updates,
7223                    "update_contracts": argument_vector_contracts(&updates),
7224                    "update_validators": [],
7225                }),
7226            );
7227        }
7228
7229        self.cooperative_registration_confirmed
7230            .store(false, Ordering::SeqCst);
7231        let response = self
7232            .client
7233            .register_worker_with_definition_fingerprints(
7234                &self.worker_id,
7235                &self.task_queue,
7236                self.workflows.keys().cloned().collect(),
7237                self.activities.keys().cloned().collect(),
7238                self.max_concurrent_workflow_tasks,
7239                self.max_concurrent_activity_tasks,
7240                [
7241                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7242                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7243                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7244                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7245                    self.client
7246                        .local_activities_enabled
7247                        .then(|| "local_activities".to_string()),
7248                    self.client
7249                        .worker_sessions_enabled
7250                        .then(|| "worker_sessions".to_string()),
7251                    self.client
7252                        .sticky_cache
7253                        .is_some()
7254                        .then(|| "sticky_execution".to_string()),
7255                    self.cooperative_cancellation_enabled
7256                        .then(|| "cooperative_cancellation".to_string()),
7257                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7258                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7259                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7260                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7261                ]
7262                .into_iter()
7263                .flatten()
7264                .chain(self.resource_capabilities.iter().cloned())
7265                .collect(),
7266                Value::Object(command_contracts),
7267                Some(
7268                    self.workflows
7269                        .iter()
7270                        .filter_map(|(workflow_type, workflow)| {
7271                            workflow
7272                                .definition_fingerprint
7273                                .as_ref()
7274                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7275                        })
7276                        .collect(),
7277                ),
7278            )
7279            .await?;
7280        if self.cooperative_cancellation_enabled && response.registered {
7281            self.cooperative_registration_confirmed
7282                .store(true, Ordering::SeqCst);
7283        }
7284        if self.client.local_activities_enabled && response.registered {
7285            self.local_registration_confirmed
7286                .store(true, Ordering::SeqCst);
7287        }
7288        if self.client.worker_sessions_enabled && response.registered {
7289            self.session_registration_confirmed
7290                .store(true, Ordering::SeqCst);
7291        }
7292        if self.client.sticky_cache.is_some() && response.registered {
7293            self.sticky_registration_confirmed
7294                .store(true, Ordering::SeqCst);
7295        }
7296        Ok(response)
7297    }
7298
7299    /// Run until shutdown or a terminal worker error occurs.
7300    ///
7301    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7302    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7303    /// authentication, protocol, and other non-retryable failures are returned.
7304    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7305    /// poll and heartbeat outages beyond the ordinary retry budget.
7306    pub async fn run(&self) -> Result<()> {
7307        self.run_until(std::future::pending::<()>()).await
7308    }
7309
7310    /// Run until `shutdown` resolves or a terminal worker error occurs.
7311    ///
7312    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7313    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7314    where
7315        F: Future<Output = ()>,
7316    {
7317        let _clear_cache_on_drop =
7318            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
7319        let stop = Arc::new(AtomicBool::new(false));
7320        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7321        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7322        worker.run_stop = Some(Arc::clone(&stop));
7323        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7324        tokio::pin!(run);
7325        tokio::pin!(shutdown);
7326        tokio::select! {
7327            result = &mut run => result,
7328            _ = &mut shutdown => {
7329                stop.store(true, Ordering::SeqCst);
7330                run.await
7331            }
7332        }
7333    }
7334
7335    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7336        let mut worker = self.clone();
7337        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7338            policy: self.retry_policy,
7339            stop,
7340        });
7341        worker
7342    }
7343
7344    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7345        let registration = self.register().await?;
7346        if !registration.registered {
7347            return Err(Error::WorkerLoop(format!(
7348                "worker registration for {:?} was not accepted",
7349                self.worker_id
7350            )));
7351        }
7352        let registered_worker_id = registration.worker_id.clone();
7353        let primary = self.run_registered_until(stop, registration).await;
7354        let primary = match (primary, self.close_worker_sessions().await) {
7355            (Ok(()), result) => result,
7356            (Err(error), Ok(())) => Err(error),
7357            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7358                primary: Box::new(primary),
7359                deregistration: Box::new(close),
7360            }),
7361        };
7362        self.session_registration_confirmed
7363            .store(false, Ordering::SeqCst);
7364        self.cooperative_registration_confirmed
7365            .store(false, Ordering::SeqCst);
7366        self.local_registration_confirmed
7367            .store(false, Ordering::SeqCst);
7368        let deregistration = self
7369            .client
7370            .deregister_worker_registration(&registered_worker_id)
7371            .await;
7372        self.sticky_registration_confirmed
7373            .store(false, Ordering::SeqCst);
7374        self.client.clear_sticky_cache()?;
7375
7376        match (primary, deregistration) {
7377            (Ok(()), Ok(_)) => Ok(()),
7378            (Ok(()), Err(deregistration)) => Err(deregistration),
7379            (Err(primary), Ok(_)) => Err(primary),
7380            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7381                primary: Box::new(primary),
7382                deregistration: Box::new(deregistration),
7383            }),
7384        }
7385    }
7386
7387    async fn run_registered_until(
7388        &self,
7389        stop: Arc<AtomicBool>,
7390        registration: RegisterWorkerResponse,
7391    ) -> Result<()> {
7392        let heartbeat_interval = Duration::from_secs(
7393            registration
7394                .heartbeat_interval_seconds
7395                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7396        );
7397        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7398        // from the completion of the preceding attempt, including its bounded
7399        // retries. A fixed-epoch interval can leave an already-due tick queued
7400        // while an acknowledgement is slow, producing a catch-up heartbeat as
7401        // soon as that request completes.
7402        let heartbeat = tokio::time::sleep(Duration::ZERO);
7403        tokio::pin!(heartbeat);
7404        // Poll responses may already have leased server-side work by the time
7405        // they become ready, so each poller owns its responses through
7406        // completion or failure instead of racing raw polls in this select.
7407        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7408            let worker = self.clone();
7409            let stop = Arc::clone(&stop);
7410            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7411        });
7412        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7413            let worker = self.clone();
7414            let stop = Arc::clone(&stop);
7415            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7416        });
7417        let mut query_poller = (!self.queries.is_empty()).then(|| {
7418            let worker = self.clone();
7419            let stop = Arc::clone(&stop);
7420            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7421        });
7422
7423        loop {
7424            tokio::select! {
7425                _ = wait_for_worker_stop(&stop) => {
7426                    stop.store(true, Ordering::SeqCst);
7427                    break;
7428                }
7429                _ = &mut heartbeat => {
7430                    let result = self.retry_worker_operation(|| {
7431                        self.client.heartbeat_worker_with_sessions(
7432                            &self.worker_id,
7433                            self.max_concurrent_workflow_tasks,
7434                            self.max_concurrent_activity_tasks,
7435                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7436                        )
7437                    }).await;
7438                    heartbeat
7439                        .as_mut()
7440                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7441                    match result {
7442                        Ok(Some(acknowledgement)) => {
7443                            if let Some(observer) = &self.heartbeat_observer {
7444                                observer(&WorkerHeartbeatObservation {
7445                                    worker_id: self.worker_id.clone(),
7446                                    task_queue: self.task_queue.clone(),
7447                                    acknowledged_at_unix_millis: SystemTime::now()
7448                                        .duration_since(UNIX_EPOCH)
7449                                        .unwrap_or_default()
7450                                        .as_millis()
7451                                        .min(u64::MAX as u128)
7452                                        as u64,
7453                                    acknowledgement,
7454                                });
7455                            }
7456                        }
7457                        Ok(None) => break,
7458                        Err(error) => {
7459                            stop.store(true, Ordering::SeqCst);
7460                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7461                            return Err(error);
7462                        }
7463                    }
7464                }
7465                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7466                    workflow_poller = None;
7467                    let stopped_by_server = stop.load(Ordering::SeqCst);
7468                    stop.store(true, Ordering::SeqCst);
7469                    let poller_result = optional_poller_result("workflow", result);
7470                    let join_result =
7471                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7472                    poller_result?;
7473                    join_result?;
7474                    if stopped_by_server {
7475                        return Ok(());
7476                    }
7477                    return Err(Error::WorkerLoop(
7478                        "workflow poller stopped unexpectedly".to_string(),
7479                    ));
7480                }
7481                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7482                    activity_poller = None;
7483                    let stopped_by_server = stop.load(Ordering::SeqCst);
7484                    stop.store(true, Ordering::SeqCst);
7485                    let poller_result = optional_poller_result("activity", result);
7486                    let join_result =
7487                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7488                    poller_result?;
7489                    join_result?;
7490                    if stopped_by_server {
7491                        return Ok(());
7492                    }
7493                    return Err(Error::WorkerLoop(
7494                        "activity poller stopped unexpectedly".to_string(),
7495                    ));
7496                }
7497                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7498                    query_poller = None;
7499                    let stopped_by_server = stop.load(Ordering::SeqCst);
7500                    stop.store(true, Ordering::SeqCst);
7501                    let poller_result = optional_poller_result("query", result);
7502                    let join_result =
7503                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7504                    poller_result?;
7505                    join_result?;
7506                    if stopped_by_server {
7507                        return Ok(());
7508                    }
7509                    return Err(Error::WorkerLoop(
7510                        "query poller stopped unexpectedly".to_string(),
7511                    ));
7512                }
7513            }
7514        }
7515
7516        join_pollers(
7517            workflow_poller.take(),
7518            activity_poller.take(),
7519            query_poller.take(),
7520        )
7521        .await
7522    }
7523
7524    /// Poll and settle at most one task from each enabled task family.
7525    ///
7526    /// A workflow may reach its server-enforced run deadline while this worker
7527    /// holds a task. When the completion endpoint authoritatively rejects that
7528    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
7529    /// terminal `run_status=failed`, the workflow tick is considered settled:
7530    /// the late command was not recorded and cannot replace the terminal run.
7531    /// Every other completion rejection remains an error. This worker-level
7532    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
7533    /// only bounds how long a client waits for a result.
7534    ///
7535    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
7536    /// the original [`Error::Http`] status and response body.
7537    pub async fn run_once(&self) -> Result<usize> {
7538        if self.client.worker_sessions_enabled {
7539            self.require_session_registration()?;
7540        }
7541        if self.cooperative_cancellation_enabled
7542            && !self
7543                .cooperative_registration_confirmed
7544                .load(Ordering::SeqCst)
7545        {
7546            return Err(Error::CooperativeCancellationUnavailable(
7547                "register this cooperative worker before polling tasks".into(),
7548            ));
7549        }
7550        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
7551        let mut handled = 0;
7552        match worker.poll_workflow_once().await? {
7553            ManagedPollOutcome::Handled => handled += 1,
7554            ManagedPollOutcome::Stop => return Ok(handled),
7555            ManagedPollOutcome::Idle => {}
7556        }
7557        match worker.poll_activity_once().await? {
7558            ManagedPollOutcome::Handled => handled += 1,
7559            ManagedPollOutcome::Stop => return Ok(handled),
7560            ManagedPollOutcome::Idle => {}
7561        }
7562        if !self.queries.is_empty() {
7563            match worker.poll_query_once().await? {
7564                ManagedPollOutcome::Handled => handled += 1,
7565                ManagedPollOutcome::Stop => return Ok(handled),
7566                ManagedPollOutcome::Idle => {}
7567            }
7568        }
7569        Ok(handled)
7570    }
7571
7572    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
7573        if self.client.sticky_cache.is_some()
7574            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
7575        {
7576            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
7577        }
7578        if self.client.local_activities_enabled
7579            && !self.local_registration_confirmed.load(Ordering::SeqCst)
7580        {
7581            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
7582        }
7583        if self.cooperative_cancellation_enabled {
7584            return self.poll_cooperative_workflow_once().await;
7585        }
7586        let poll_request_id = unique_request_id("rust-workflow-poll");
7587        let response = self
7588            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
7589            .await;
7590        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
7591            return Ok(ManagedPollOutcome::Idle);
7592        };
7593        if response.outcome().should_stop() {
7594            return Ok(ManagedPollOutcome::Stop);
7595        }
7596        let memo_updates_supported =
7597            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
7598        let Some(task) = response.task else {
7599            return Ok(ManagedPollOutcome::Idle);
7600        };
7601
7602        let task_id = task.task_id.clone();
7603        let attempt = task.workflow_task_attempt;
7604        let run_id = task.run_id.clone();
7605        let lease_owner = task
7606            .lease_owner
7607            .clone()
7608            .unwrap_or_else(|| self.worker_id.clone());
7609
7610        let decision = match self.execute_workflow_with_local_activities(task).await {
7611            Ok(Some(decision)) => Ok(decision),
7612            Ok(None) => return Ok(ManagedPollOutcome::Handled),
7613            Err(error) => Err(error),
7614        };
7615        self.settle_workflow_task_decision(
7616            &task_id,
7617            &lease_owner,
7618            attempt,
7619            run_id.as_deref(),
7620            decision,
7621            memo_updates_supported,
7622            snapshot,
7623        )
7624        .await
7625    }
7626
7627    #[allow(clippy::too_many_arguments)]
7628    async fn settle_workflow_task_decision(
7629        &self,
7630        task_id: &str,
7631        lease_owner: &str,
7632        attempt: u64,
7633        run_id: Option<&str>,
7634        decision: Result<WorkflowTaskDecision>,
7635        memo_updates_supported: bool,
7636        snapshot: Option<sticky_worker::StickySnapshot>,
7637    ) -> Result<ManagedPollOutcome> {
7638        match decision {
7639            Ok(decision)
7640                if decision.cancellation_delivery.is_some()
7641                    || decision.cancellation_scope_delivery.is_some()
7642                    || decision.cancellation_scope_opening.is_some() =>
7643            {
7644                return Err(Error::CooperativeCancellationUnavailable(
7645                    "worker cancellation delivery has not been negotiated".into(),
7646                ));
7647            }
7648            Ok(decision)
7649                if commands_use_workflow_memo_updates(&decision.commands)
7650                    && !memo_updates_supported =>
7651            {
7652                self.client
7653                    .fail_workflow_task(
7654                        task_id,
7655                        lease_owner,
7656                        attempt,
7657                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
7658                    )
7659                    .await?;
7660            }
7661            Ok(decision) if decision.commands.is_empty() => {
7662                // A replay can consume a recorded pending durable command
7663                // without producing a new command. The standalone protocol
7664                // acknowledges that state through the typed waiting outcome;
7665                // an empty completion is rejected by servers that require at
7666                // least one executable command.
7667                self.client
7668                    .fail_workflow_task_with_type(
7669                        task_id,
7670                        lease_owner,
7671                        attempt,
7672                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
7673                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
7674                    )
7675                    .await?;
7676            }
7677            Ok(decision) => {
7678                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
7679                let completion = self
7680                    .client
7681                    .complete_workflow_task_with_message_streams(
7682                        task_id,
7683                        lease_owner,
7684                        attempt,
7685                        decision.commands,
7686                        decision.message_stream_cursors,
7687                        decision.message_stream_waits,
7688                        sticky_claim,
7689                    )
7690                    .await;
7691                if let Err(error) = completion {
7692                    self.discard_sticky_snapshot(snapshot.as_ref())?;
7693                    if !workflow_task_completion_is_terminal_timeout(
7694                        &error, task_id, attempt, run_id,
7695                    ) {
7696                        return Err(error);
7697                    }
7698                }
7699            }
7700            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
7701            Err(error) => {
7702                self.discard_sticky_snapshot(snapshot.as_ref())?;
7703                self.client
7704                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
7705                    .await?;
7706            }
7707        }
7708
7709        Ok(ManagedPollOutcome::Handled)
7710    }
7711
7712    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7713        while !stop.load(Ordering::SeqCst) {
7714            match self.poll_workflow_once().await {
7715                Ok(ManagedPollOutcome::Stop) => {
7716                    stop.store(true, Ordering::SeqCst);
7717                    break;
7718                }
7719                Err(error) => {
7720                    stop.store(true, Ordering::SeqCst);
7721                    return Err(error);
7722                }
7723                _ => {}
7724            }
7725        }
7726
7727        Ok(())
7728    }
7729
7730    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
7731        if self.client.worker_sessions_enabled {
7732            self.require_session_registration()?;
7733        }
7734        if self.cooperative_cancellation_enabled {
7735            return self.poll_cooperative_activity_once().await;
7736        }
7737        let poll_request_id = unique_request_id("rust-activity-poll");
7738        let response = self
7739            .retry_worker_operation(|| {
7740                self.client.poll_activity_task_response_with_request_id(
7741                    &self.worker_id,
7742                    &self.task_queue,
7743                    self.poll_timeout,
7744                    &poll_request_id,
7745                    0,
7746                )
7747            })
7748            .await;
7749        let Some(response) = self.settle_worker_poll_response(response).await? else {
7750            return Ok(ManagedPollOutcome::Idle);
7751        };
7752        if response.outcome().should_stop() {
7753            return Ok(ManagedPollOutcome::Stop);
7754        }
7755        let Some(task) = response.task else {
7756            return Ok(ManagedPollOutcome::Idle);
7757        };
7758
7759        let session = self.track_session_task(task.worker_session.as_ref())?;
7760        let task = task.task;
7761
7762        let task_id = task.task_id.clone();
7763        let attempt_id = task
7764            .activity_attempt_id
7765            .clone()
7766            .or(task.attempt_id.clone())
7767            .unwrap_or_default();
7768        let lease_owner = task
7769            .lease_owner
7770            .clone()
7771            .unwrap_or_else(|| self.worker_id.clone());
7772        let codec = task.payload_codec.clone();
7773        let result = self.execute_session_activity_task(task, session).await;
7774        match result {
7775            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
7776            Ok(value) => {
7777                let completion = self
7778                    .client
7779                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
7780                    .await;
7781                if let Err(error) = completion {
7782                    if !activity_task_rejection_is_final(&error) {
7783                        return Err(error);
7784                    }
7785                }
7786            }
7787            Err(error) => {
7788                let failure = self
7789                    .client
7790                    .fail_activity_task(
7791                        &task_id,
7792                        &attempt_id,
7793                        &lease_owner,
7794                        error.to_string(),
7795                        false,
7796                    )
7797                    .await;
7798                if let Err(error) = failure {
7799                    if !activity_task_rejection_is_final(&error) {
7800                        return Err(error);
7801                    }
7802                }
7803            }
7804        }
7805
7806        Ok(ManagedPollOutcome::Handled)
7807    }
7808
7809    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7810        // Each lane retains its leased response through callback settlement.
7811        // A bounded independent activity must not occupy the cleanup lane too.
7812        // Preserve the existing serial loop for default protocol 1.19 workers.
7813        let lane_count = if self.cooperative_cancellation_enabled {
7814            self.max_concurrent_activity_tasks
7815        } else {
7816            1
7817        };
7818        let mut lanes = FuturesUnordered::new();
7819        for _ in 0..lane_count {
7820            let worker = self.clone();
7821            let stop = Arc::clone(&stop);
7822            lanes.push(async move {
7823                while !stop.load(Ordering::SeqCst) {
7824                    match worker.poll_activity_once().await {
7825                        Ok(ManagedPollOutcome::Stop) => {
7826                            stop.store(true, Ordering::SeqCst);
7827                            break;
7828                        }
7829                        Err(error) => {
7830                            stop.store(true, Ordering::SeqCst);
7831                            return Err(error);
7832                        }
7833                        _ => {}
7834                    }
7835                }
7836                Ok(())
7837            });
7838        }
7839        // Join every lane before deregistration, including after one fails.
7840        let mut first_error = None;
7841        while let Some(result) = lanes.next().await {
7842            if let Err(error) = result {
7843                first_error.get_or_insert(error);
7844            }
7845        }
7846        first_error.map_or(Ok(()), Err)
7847    }
7848
7849    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
7850        let poll_request_id = unique_request_id("rust-query-poll");
7851        let response = self
7852            .retry_worker_operation(|| {
7853                self.client.poll_query_task_response_with_request_id(
7854                    &self.worker_id,
7855                    &self.task_queue,
7856                    self.poll_timeout,
7857                    &poll_request_id,
7858                    0,
7859                )
7860            })
7861            .await;
7862        let Some(response) = self.settle_worker_poll_response(response).await? else {
7863            return Ok(ManagedPollOutcome::Idle);
7864        };
7865        if response.outcome().should_stop() {
7866            return Ok(ManagedPollOutcome::Stop);
7867        }
7868        let Some(task) = response.task else {
7869            return Ok(ManagedPollOutcome::Idle);
7870        };
7871
7872        let query_task_id = task.query_task_id.clone();
7873        let attempt = task.query_task_attempt;
7874        let lease_owner = task
7875            .lease_owner
7876            .clone()
7877            .unwrap_or_else(|| self.worker_id.clone());
7878        let codec = task.payload_codec.clone();
7879
7880        match self.execute_query_task(task).await {
7881            Ok(value) => {
7882                let result_envelope = match encode_typed_envelope(&value, &codec) {
7883                    Ok(result_envelope) => result_envelope,
7884                    Err(error) => {
7885                        let failure = self
7886                            .client
7887                            .fail_query_task(
7888                                &query_task_id,
7889                                &lease_owner,
7890                                attempt,
7891                                error.to_string(),
7892                                "query_result_encode_failed",
7893                                "QueryResultEncodeFailed",
7894                            )
7895                            .await;
7896                        if let Err(error) = failure {
7897                            if !query_task_rejection_is_final(&error) {
7898                                return Err(error);
7899                            }
7900                        }
7901                        return Ok(ManagedPollOutcome::Handled);
7902                    }
7903                };
7904
7905                if let Err(error) = self
7906                    .client
7907                    .complete_query_task_with_envelope(
7908                        &query_task_id,
7909                        &lease_owner,
7910                        attempt,
7911                        value.clone().into_json()?,
7912                        result_envelope,
7913                    )
7914                    .await
7915                {
7916                    if !query_task_rejection_is_final(&error) {
7917                        return Err(error);
7918                    }
7919                }
7920            }
7921            Err(failure) => {
7922                let result = self
7923                    .client
7924                    .fail_query_task(
7925                        &query_task_id,
7926                        &lease_owner,
7927                        attempt,
7928                        failure.message,
7929                        failure.reason,
7930                        failure.failure_type,
7931                    )
7932                    .await;
7933                if let Err(error) = result {
7934                    if !query_task_rejection_is_final(&error) {
7935                        return Err(error);
7936                    }
7937                }
7938            }
7939        }
7940
7941        Ok(ManagedPollOutcome::Handled)
7942    }
7943
7944    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
7945        while !stop.load(Ordering::SeqCst) {
7946            match self.poll_query_once().await {
7947                Ok(ManagedPollOutcome::Stop) => {
7948                    stop.store(true, Ordering::SeqCst);
7949                    break;
7950                }
7951                Err(error) => {
7952                    stop.store(true, Ordering::SeqCst);
7953                    return Err(error);
7954                }
7955                _ => {}
7956            }
7957        }
7958
7959        Ok(())
7960    }
7961
7962    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
7963    where
7964        F: FnMut() -> Fut,
7965        Fut: Future<Output = Result<T>>,
7966    {
7967        let mut retries = 0;
7968
7969        loop {
7970            if self
7971                .run_stop
7972                .as_ref()
7973                .is_some_and(|stop| stop.load(Ordering::SeqCst))
7974            {
7975                return Ok(None);
7976            }
7977            match operation().await {
7978                Err(error)
7979                    if worker_operation_is_retryable(&error)
7980                        && (retries < self.retry_policy.max_retries
7981                            || (self.recover_transient_outages
7982                                && self.run_stop.is_some()
7983                                && self.retry_policy.max_retries > 0)) =>
7984                {
7985                    retries = retries.saturating_add(1);
7986                    let delay = worker_retry_delay(self.retry_policy, retries)
7987                        .max(Duration::from_millis(1));
7988                    if let Some(stop) = &self.run_stop {
7989                        tokio::select! {
7990                            _ = tokio::time::sleep(delay) => {}
7991                            _ = wait_for_worker_stop(stop) => return Ok(None),
7992                        }
7993                    } else {
7994                        tokio::time::sleep(delay).await;
7995                    }
7996                }
7997                result => return result.map(Some),
7998            }
7999        }
8000    }
8001
8002    async fn settle_worker_poll_response<T>(
8003        &self,
8004        response: Result<Option<T>>,
8005    ) -> Result<Option<T>> {
8006        match response {
8007            Ok(response) => Ok(response),
8008            Err(error) => {
8009                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
8010                    return Err(error);
8011                };
8012                let minimum_delay = self
8013                    .retry_policy
8014                    .initial_backoff
8015                    .max(Duration::from_millis(1));
8016                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
8017                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
8018                Ok(None)
8019            }
8020        }
8021    }
8022
8023    async fn execute_query_task(
8024        &self,
8025        mut task: QueryTask,
8026    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8027        validate_query_task_payloads(&task).map_err(|error| {
8028            QueryTaskExecutionFailure::new(
8029                "query_payload_decode_failed",
8030                error.to_string(),
8031                "QueryPayloadDecodeFailed",
8032            )
8033        })?;
8034
8035        if !self.workflows.contains_key(&task.workflow_type) {
8036            return Err(QueryTaskExecutionFailure::new(
8037                "query_workflow_type_not_registered",
8038                format!("no workflow registered for type {:?}", task.workflow_type),
8039                "WorkflowTypeNotRegistered",
8040            ));
8041        }
8042
8043        let Some(handlers) = self.queries.get(&task.workflow_type) else {
8044            return Err(QueryTaskExecutionFailure::new(
8045                "query_handler_unavailable",
8046                format!(
8047                    "query handlers are unavailable for workflow type {:?}",
8048                    task.workflow_type
8049                ),
8050                "QueryHandlerUnavailable",
8051            ));
8052        };
8053        let Some(query) = handlers.get(&task.query_name) else {
8054            return Err(QueryTaskExecutionFailure::new(
8055                "rejected_unknown_query",
8056                format!("unknown query {:?}", task.query_name),
8057                "QueryFailed",
8058            ));
8059        };
8060
8061        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
8062            .map_err(|error| {
8063            QueryTaskExecutionFailure::new(
8064                "query_payload_decode_failed",
8065                format!("cannot decode query arguments: {error}"),
8066                "QueryPayloadDecodeFailed",
8067            )
8068        })?;
8069        let workflow_input_typed =
8070            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8071                .map_err(|error| {
8072                    QueryTaskExecutionFailure::new(
8073                        "query_workflow_state_unavailable",
8074                        format!("cannot decode workflow start input: {error}"),
8075                        "QueryWorkflowStateUnavailable",
8076                    )
8077                })?;
8078        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8079            QueryTaskExecutionFailure::new(
8080                "query_workflow_state_unavailable",
8081                format!("cannot project workflow start input: {error}"),
8082                "QueryWorkflowStateUnavailable",
8083            )
8084        })?;
8085        hydrate_query_history_from_export(&mut task).map_err(|error| {
8086            QueryTaskExecutionFailure::new(
8087                "query_workflow_state_unavailable",
8088                format!("cannot restore query history snapshot: {error}"),
8089                "QueryWorkflowStateUnavailable",
8090            )
8091        })?;
8092        enrich_query_history_from_export(&mut task).map_err(|error| {
8093            QueryTaskExecutionFailure::new(
8094                "query_workflow_state_unavailable",
8095                format!("cannot restore compact query history payloads: {error}"),
8096                "QueryWorkflowStateUnavailable",
8097            )
8098        })?;
8099        let signal_events = query_signal_events(&task).map_err(|error| {
8100            QueryTaskExecutionFailure::new(
8101                "query_workflow_state_unavailable",
8102                format!("cannot decode committed workflow signals: {error}"),
8103                "QueryWorkflowStateUnavailable",
8104            )
8105        })?;
8106        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8107        let context = QueryContext {
8108            workflow_id: task.workflow_id,
8109            run_id: task.run_id,
8110            workflow_type: task.workflow_type.clone(),
8111            run_status: task.run_status,
8112            workflow_input,
8113            workflow_input_avro_value: workflow_input_typed.clone(),
8114            history_events: Arc::clone(&history_events),
8115            signal_events: Arc::new(signal_events),
8116        };
8117
8118        let future = match query {
8119            RegisteredQuery::Snapshot(handler) => handler(context, args),
8120            RegisteredQuery::Replayed {
8121                state_type,
8122                handler,
8123            } => {
8124                let workflow = self
8125                    .workflows
8126                    .get(&task.workflow_type)
8127                    .expect("workflow registration was checked above");
8128                if workflow.state_type != Some(*state_type) {
8129                    return Err(QueryTaskExecutionFailure::new(
8130                        "query_workflow_state_unavailable",
8131                        "replayed query state type does not match its workflow registration",
8132                        "QueryWorkflowStateUnavailable",
8133                    ));
8134                }
8135                let replay = workflow.replay.as_ref().ok_or_else(|| {
8136                    QueryTaskExecutionFailure::new(
8137                        "query_workflow_state_unavailable",
8138                        format!(
8139                            "workflow type {:?} is not registered for instance-state replay",
8140                            task.workflow_type
8141                        ),
8142                        "QueryWorkflowStateUnavailable",
8143                    )
8144                })?;
8145                let workflow_state = Arc::new(Mutex::new(
8146                    WorkflowState::new_with_identity(
8147                        history_events.as_ref().clone(),
8148                        context.workflow_id.clone(),
8149                        context.run_id.clone(),
8150                        self.task_queue.clone(),
8151                        task.payload_codec,
8152                        None,
8153                    )
8154                    .map_err(|error| {
8155                        QueryTaskExecutionFailure::new(
8156                            "query_workflow_state_unavailable",
8157                            format!("workflow replay failed before query: {error}"),
8158                            "QueryWorkflowStateUnavailable",
8159                        )
8160                    })?,
8161                ));
8162                let workflow_context = WorkflowContext {
8163                    state: workflow_state,
8164                    cancellation_scope_id: "root".into(),
8165                };
8166                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8167                let mut cx = TaskContext::from_waker(noop_waker_ref());
8168                let outcome = {
8169                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8170                        .map_err(|error| {
8171                            QueryTaskExecutionFailure::new(
8172                                "query_workflow_state_unavailable",
8173                                error.to_string(),
8174                                "QueryWorkflowStateUnavailable",
8175                            )
8176                        })?;
8177                    invocation.future.as_mut().poll(&mut cx)
8178                };
8179                match outcome {
8180                    Poll::Ready(Ok(_)) => {
8181                        workflow_context
8182                            .ensure_history_consumed()
8183                            .map_err(|error| {
8184                                QueryTaskExecutionFailure::new(
8185                                    "query_workflow_state_unavailable",
8186                                    format!("workflow replay failed before query: {error}"),
8187                                    "QueryWorkflowStateUnavailable",
8188                                )
8189                            })?;
8190                    }
8191                    Poll::Ready(Err(error)) => {
8192                        return Err(QueryTaskExecutionFailure::new(
8193                            "query_workflow_state_unavailable",
8194                            format!("workflow replay failed before query: {error}"),
8195                            "QueryWorkflowStateUnavailable",
8196                        ));
8197                    }
8198                    Poll::Pending => {
8199                        let commands = workflow_context.take_commands().map_err(|error| {
8200                            QueryTaskExecutionFailure::new(
8201                                "query_workflow_state_unavailable",
8202                                format!("workflow replay failed before query: {error}"),
8203                                "QueryWorkflowStateUnavailable",
8204                            )
8205                        })?;
8206                        if commands.is_empty()
8207                            && !workflow_context
8208                                .matched_recorded_pending()
8209                                .map_err(|error| {
8210                                    QueryTaskExecutionFailure::new(
8211                                        "query_workflow_state_unavailable",
8212                                        format!("workflow replay failed before query: {error}"),
8213                                        "QueryWorkflowStateUnavailable",
8214                                    )
8215                                })?
8216                        {
8217                            return Err(QueryTaskExecutionFailure::new(
8218                                "query_workflow_state_unavailable",
8219                                "workflow replay yielded without a durable command",
8220                                "QueryWorkflowStateUnavailable",
8221                            ));
8222                        }
8223                    }
8224                }
8225                let state = (invocation.snapshot)().map_err(|error| {
8226                    QueryTaskExecutionFailure::new(
8227                        "query_workflow_state_unavailable",
8228                        format!("cannot snapshot replayed workflow state: {error}"),
8229                        "QueryWorkflowStateUnavailable",
8230                    )
8231                })?;
8232                handler(context, state, args).map_err(|message| {
8233                    QueryTaskExecutionFailure::new(
8234                        "query_workflow_state_unavailable",
8235                        message,
8236                        "QueryWorkflowStateUnavailable",
8237                    )
8238                })?
8239            }
8240        };
8241
8242        future.await.map_err(|error| {
8243            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8244        })
8245    }
8246
8247    #[cfg(test)]
8248    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8249        Ok(self.execute_workflow_task_decision(task)?.commands)
8250    }
8251
8252    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8253        self.execute_workflow_task_decision_with_cancellation(task, None)
8254    }
8255
8256    fn execute_workflow_task_decision_with_cancellation(
8257        &self,
8258        task: WorkflowTask,
8259        observation: Option<&CancellationRequest>,
8260    ) -> Result<WorkflowTaskDecision> {
8261        match self.prepare_workflow_task_execution(task, observation)? {
8262            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8263            PreparedWorkflowTask::Execution {
8264                task,
8265                context,
8266                mut future,
8267            } => {
8268                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8269                self.finish_workflow_task_execution(&task, &context, outcome)
8270            }
8271        }
8272    }
8273
8274    fn prepare_workflow_task_execution(
8275        &self,
8276        task: WorkflowTask,
8277        observation: Option<&CancellationRequest>,
8278    ) -> Result<PreparedWorkflowTask> {
8279        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8280            && !self.cooperative_cancellation_enabled
8281        {
8282            return Err(Error::CancellationScopeExecutionUnavailable);
8283        }
8284        validate_workflow_task_payloads(&task)?;
8285        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8286            &task.history_events,
8287            self.allow_cancellation_scope_authoring,
8288            self.allow_cancellation_scope_delivery,
8289        )?;
8290        let cancellation_history = if let Some(observation) = observation {
8291            observation.validate_observation()?;
8292            cooperative_cancellation::cancellation_claim(&task)?;
8293            let canonical = CancellationHistory::from_events(
8294                &task.history_events,
8295                task.run_id.as_deref().unwrap_or_default(),
8296                Some(observation),
8297            )?;
8298            if canonical.request_index >= task.history_events.len() {
8299                return Err(Error::InvalidCooperativeCancellation(
8300                    "workflow replay requires the observed canonical request".into(),
8301                ));
8302            }
8303            Some(canonical)
8304        } else {
8305            None
8306        };
8307        if let Some(update_id) = task
8308            .workflow_update_id
8309            .as_deref()
8310            .filter(|update_id| !update_id.is_empty())
8311        {
8312            if self.allow_cancellation_scope_delivery {
8313                return Err(Error::CancellationScopeExecutionUnavailable);
8314            }
8315            CancellationHistory::from_events(
8316                &task.history_events,
8317                task.run_id.as_deref().unwrap_or_default(),
8318                None,
8319            )?;
8320            return self
8321                .execute_update_task(&task, update_id)
8322                .map(WorkflowTaskDecision::without_message_streams)
8323                .map(PreparedWorkflowTask::Decision);
8324        }
8325
8326        let workflow = self
8327            .workflows
8328            .get(&task.workflow_type)
8329            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8330        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8331        let resume_signal = decode_resume_signal(&task)?;
8332        let history_budget = WorkflowHistoryBudget {
8333            event_count: task
8334                .total_history_events
8335                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8336            size_bytes: task.history_size_bytes,
8337            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8338            pressure: task.history_budget_pressure.clone(),
8339        };
8340        let workflow_command_identity = task
8341            .workflow_command_id
8342            .clone()
8343            .filter(|identity| !identity.is_empty())
8344            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8345            .unwrap_or_default();
8346        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8347            task.history_events.clone(),
8348            task.workflow_id.clone(),
8349            task.run_id.clone(),
8350            self.task_queue.clone(),
8351            task.payload_codec.clone(),
8352            resume_signal,
8353            self.allow_cancellation_scope_authoring,
8354            self.allow_cancellation_scope_delivery,
8355        )?;
8356        workflow_state.history_budget = history_budget;
8357        workflow_state.workflow_command_identity = workflow_command_identity;
8358        if let Some(canonical) = cancellation_history {
8359            workflow_state.cancellation_history = canonical;
8360            workflow_state.cancellation_delivery_enabled = true;
8361        }
8362        if workflow_state.cancellation_history.request.is_none() {
8363            workflow_state.cancel_requested = task.cancel_requested;
8364        }
8365        let state = Arc::new(Mutex::new(workflow_state));
8366        let ctx = WorkflowContext {
8367            state,
8368            cancellation_scope_id: "root".into(),
8369        };
8370        let future = (workflow.execute)(ctx.clone(), input);
8371        Ok(PreparedWorkflowTask::Execution {
8372            task,
8373            context: ctx,
8374            future,
8375        })
8376    }
8377
8378    fn poll_workflow_future(
8379        ctx: &WorkflowContext,
8380        future: &mut WorkflowFuture,
8381    ) -> Result<Poll<Result<AvroValue>>> {
8382        let mut cx = TaskContext::from_waker(noop_waker_ref());
8383        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
8384        Ok(future.as_mut().poll(&mut cx))
8385    }
8386
8387    fn finish_workflow_task_execution(
8388        &self,
8389        task: &WorkflowTask,
8390        ctx: &WorkflowContext,
8391        outcome: Poll<Result<AvroValue>>,
8392    ) -> Result<WorkflowTaskDecision> {
8393        if !ctx
8394            .state
8395            .lock()
8396            .map_err(|_| Error::WorkflowStatePoisoned)?
8397            .local_activity_requests
8398            .is_empty()
8399        {
8400            return Err(Error::CooperativeCancellationUnavailable(
8401                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
8402            ));
8403        }
8404        let awaiting_canonical_boundary = {
8405            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8406            state.cancellation_delivery_intent.is_some()
8407                || state.cancellation_scope_opening.is_some()
8408                || state
8409                    .scope_delivery
8410                    .as_ref()
8411                    .is_some_and(|replay| replay.intent.is_some())
8412        };
8413        if awaiting_canonical_boundary {
8414            // A private delivery intent never becomes an application error.
8415            // Even a custom future which ignores a pending durable call cannot
8416            // publish terminal commands before canonical delivery and replay.
8417            if let Poll::Ready(Err(error)) = outcome {
8418                if workflow_task_integrity_error(&error) {
8419                    return Err(error);
8420                }
8421            }
8422            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8423        }
8424
8425        match outcome {
8426            Poll::Ready(Ok(result)) => {
8427                ctx.ensure_history_consumed()?;
8428                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8429                let mut commands = ctx.take_commands()?;
8430                commands.push(json!({
8431                    "type": "complete_workflow",
8432                    "result": result
8433                }));
8434                self.message_stream_decision(&ctx, commands)
8435            }
8436            Poll::Ready(Err(error)) => {
8437                if let Error::ContinueAsNew(request) = error {
8438                    let mut commands = ctx.take_commands()?;
8439                    if let Some(command) = ctx.continue_as_new_command(request)? {
8440                        commands.push(command);
8441                    }
8442                    ctx.ensure_history_consumed()?;
8443                    return self.message_stream_decision(&ctx, commands);
8444                }
8445                if workflow_task_integrity_error(&error) {
8446                    // Replay and protocol failures describe the workflow-task
8447                    // decision itself. Preserve their specific failure reason
8448                    // instead of replacing it with the derivative fact that
8449                    // recorded commands remain unconsumed.
8450                    return Err(error);
8451                }
8452                // A handler error must not hide a committed durable command that
8453                // upgraded workflow code no longer consumes.
8454                ctx.ensure_history_consumed()?;
8455                let mut commands = ctx.take_commands()?;
8456                commands.push(workflow_failure_command(
8457                    &error,
8458                    recorded_activity_failure_boundary(&ctx, &error),
8459                ));
8460                self.message_stream_decision(&ctx, commands)
8461            }
8462            Poll::Pending => {
8463                let commands = ctx.take_commands()?;
8464                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8465                    Err(Error::WorkflowYieldedWithoutCommand)
8466                } else {
8467                    self.message_stream_decision(&ctx, commands)
8468                }
8469            }
8470        }
8471    }
8472
8473    fn message_stream_decision(
8474        &self,
8475        ctx: &WorkflowContext,
8476        commands: Vec<Value>,
8477    ) -> Result<WorkflowTaskDecision> {
8478        if !self.cooperative_cancellation_enabled
8479            && commands.iter().any(|command| {
8480                command["type"] == "schedule_activity"
8481                    && command.get("cancellation_policy").is_some()
8482            })
8483        {
8484            return Err(Error::CooperativeCancellationUnavailable(format!(
8485                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8486                self.worker_id,
8487            )));
8488        }
8489        if !self.cooperative_cancellation_enabled
8490            && commands.iter().any(|command| {
8491                command["type"] == "start_child_workflow"
8492                    && (command["parent_close_policy"] == "request_cancellation"
8493                        || matches!(
8494                            command["cancellation_policy"].as_str(),
8495                            Some("try_cancel" | "wait_cancellation_completed")
8496                        ))
8497            })
8498        {
8499            return Err(Error::CooperativeCancellationUnavailable(format!(
8500                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8501                self.worker_id,
8502            )));
8503        }
8504        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
8505        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8506        let scope_delivery = state
8507            .scope_delivery
8508            .as_ref()
8509            .and_then(|replay| replay.intent.clone());
8510        if scope_delivery
8511            .as_ref()
8512            .is_some_and(|intent| commands.len() != intent.command_count)
8513        {
8514            return Err(invalid_recorded_history(
8515                "cancellation_scope_pending_call_escaped",
8516                scope_delivery.as_ref().unwrap().boundary.sequence,
8517                "commands preceding the pending scoped call",
8518                "commands after suspension",
8519                "workflow cannot publish beyond an uncommitted scope delivery",
8520            ));
8521        }
8522        if let Some(opening) = &state.cancellation_scope_opening {
8523            if commands.len() != opening.command_count {
8524                return Err(invalid_recorded_history(
8525                    "cancellation_scope_pending_call_escaped",
8526                    opening.sequence,
8527                    "commands before original scope opening",
8528                    "commands after suspended opening",
8529                    "workflow cannot publish beyond an uncommitted scope opening",
8530                ));
8531            }
8532        }
8533        if state.cancellation_delivery_intent.is_some()
8534            && commands.len() != state.cancellation_delivery_command_count
8535        {
8536            return Err(invalid_recorded_history(
8537                "cooperative_cancellation_pending_call_escaped",
8538                state
8539                    .cancellation_delivery_intent
8540                    .as_ref()
8541                    .expect("pending delivery")
8542                    .sequence,
8543                "only commands preceding the pending cancellation call",
8544                "commands authored after a suspended call",
8545                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
8546            ));
8547        }
8548        Ok(WorkflowTaskDecision {
8549            commands,
8550            message_stream_cursors,
8551            message_stream_waits,
8552            cancellation_delivery: state.cancellation_delivery_intent.clone(),
8553            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
8554            cancellation_scope_delivery: scope_delivery,
8555        })
8556    }
8557
8558    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
8559        if !self.workflows.contains_key(&task.workflow_type) {
8560            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
8561        }
8562
8563        let accepted = task.history_events.iter().rev().find_map(|event| {
8564            (event.event_type == "UpdateAccepted"
8565                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
8566            .then_some(&event.payload)
8567        });
8568        let update_name = accepted
8569            .and_then(|payload| payload.get("update_name"))
8570            .and_then(Value::as_str)
8571            .or(task.update_name.as_deref())
8572            .unwrap_or_default();
8573        let Some(handler) = self
8574            .updates
8575            .get(&task.workflow_type)
8576            .and_then(|handlers| handlers.get(update_name))
8577        else {
8578            return Ok(vec![json!({
8579                "type": "fail_update",
8580                "update_id": update_id,
8581                "message": format!(
8582                    "no update handler is registered for {}.{update_name}",
8583                    task.workflow_type
8584                ),
8585                "exception_type": "UnknownUpdate",
8586                "non_retryable": true,
8587            })]);
8588        };
8589        let arguments = accepted
8590            .and_then(|payload| payload.get("arguments"))
8591            .or(task.arguments.as_ref());
8592        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
8593        let workflow_input_avro_value =
8594            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8595        let workflow_input = workflow_input_avro_value.clone().into_json()?;
8596        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
8597        let context = QueryContext {
8598            workflow_id: task.workflow_id.clone(),
8599            run_id: task.run_id.clone(),
8600            workflow_type: task.workflow_type.clone(),
8601            run_status: Some("running".to_string()),
8602            workflow_input,
8603            workflow_input_avro_value,
8604            history_events: Arc::new(task.history_events.clone()),
8605            signal_events: Arc::new(signal_events),
8606        };
8607        let mut future = handler(context, arguments);
8608        let mut cx = TaskContext::from_waker(noop_waker_ref());
8609
8610        match future.as_mut().poll(&mut cx) {
8611            Poll::Ready(Ok(result)) => Ok(vec![json!({
8612                "type": "complete_update",
8613                "update_id": update_id,
8614                "result": encode_typed_envelope(&result, &task.payload_codec)?,
8615            })]),
8616            Poll::Ready(Err(error)) => Ok(vec![json!({
8617                "type": "fail_update",
8618                "update_id": update_id,
8619                "message": error.to_string(),
8620                "exception_type": "UpdateFailed",
8621                "non_retryable": true,
8622            })]),
8623            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
8624        }
8625    }
8626
8627    #[cfg(test)]
8628    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
8629        self.execute_session_activity_task(task, None).await
8630    }
8631
8632    async fn execute_session_activity_task(
8633        &self,
8634        task: ActivityTask,
8635        worker_session: Option<WorkerSession>,
8636    ) -> Result<AvroValue> {
8637        validate_activity_task_payloads(&task)?;
8638        if worker_session.is_some() {
8639            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
8640                || task
8641                    .activity_attempt_id
8642                    .as_deref()
8643                    .or(task.attempt_id.as_deref())
8644                    .is_none_or(str::is_empty)
8645                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
8646            {
8647                return Err(Error::ActivityExecutionAbandoned(
8648                    "session activity requires this worker's exact immutable claim".into(),
8649                ));
8650            }
8651        }
8652
8653        let handler = self
8654            .activities
8655            .get(&task.activity_type)
8656            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
8657        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8658        let attempt_id = task
8659            .activity_attempt_id
8660            .clone()
8661            .or(task.attempt_id.clone())
8662            .unwrap_or_default();
8663        let lease_owner = task
8664            .lease_owner
8665            .clone()
8666            .unwrap_or_else(|| self.worker_id.clone());
8667        let session = worker_session.clone();
8668        let ctx = ActivityContext {
8669            client: self.client.clone(),
8670            task_id: task.task_id,
8671            activity_attempt_id: attempt_id,
8672            lease_owner,
8673            activity_type: task.activity_type,
8674            attempt_number: task.attempt_number,
8675            task_queue: self.task_queue.clone(),
8676            worker_id: self.worker_id.clone(),
8677            claim_guard: None,
8678            local_heartbeats: None,
8679            worker_session,
8680        };
8681
8682        let callback = handler(ctx, args);
8683        if let Some(session) = session {
8684            tokio::select! {
8685                biased;
8686                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
8687                result = callback => if session.active() { result } else {
8688                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
8689                },
8690            }
8691        } else {
8692            callback.await
8693        }
8694    }
8695}
8696
8697fn poller_result(
8698    kind: &str,
8699    result: std::result::Result<Result<()>, tokio::task::JoinError>,
8700) -> Result<()> {
8701    match result {
8702        Ok(result) => result,
8703        Err(error) => Err(Error::WorkerLoop(format!(
8704            "{kind} poller join error: {error}"
8705        ))),
8706    }
8707}
8708
8709fn optional_poller_result(
8710    kind: &str,
8711    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
8712) -> Result<()> {
8713    match result {
8714        Some(result) => poller_result(kind, result),
8715        None => Ok(()),
8716    }
8717}
8718
8719async fn join_pollers(
8720    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8721    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8722    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
8723) -> Result<()> {
8724    let mut first_error = None;
8725
8726    if let Some(handle) = workflow_poller {
8727        if let Err(error) = poller_result("workflow", handle.await) {
8728            first_error.get_or_insert(error);
8729        }
8730    }
8731
8732    if let Some(handle) = activity_poller {
8733        if let Err(error) = poller_result("activity", handle.await) {
8734            first_error.get_or_insert(error);
8735        }
8736    }
8737
8738    if let Some(handle) = query_poller {
8739        if let Err(error) = poller_result("query", handle.await) {
8740            first_error.get_or_insert(error);
8741        }
8742    }
8743
8744    if let Some(error) = first_error {
8745        Err(error)
8746    } else {
8747        Ok(())
8748    }
8749}
8750
8751fn default_worker_id() -> String {
8752    let millis = SystemTime::now()
8753        .duration_since(UNIX_EPOCH)
8754        .unwrap_or_default()
8755        .as_millis();
8756    format!("rust-worker-{}-{millis}", std::process::id())
8757}
8758
8759fn percent_encode_path_segment(segment: &str) -> String {
8760    const HEX: &[u8; 16] = b"0123456789ABCDEF";
8761    let mut encoded = String::with_capacity(segment.len());
8762
8763    for byte in segment.bytes() {
8764        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
8765            encoded.push(char::from(byte));
8766        } else {
8767            encoded.push('%');
8768            encoded.push(char::from(HEX[(byte >> 4) as usize]));
8769            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
8770        }
8771    }
8772
8773    encoded
8774}
8775
8776fn unique_request_id(prefix: &str) -> String {
8777    let nanos = SystemTime::now()
8778        .duration_since(UNIX_EPOCH)
8779        .unwrap_or_default()
8780        .as_nanos();
8781    format!("{prefix}-{}-{nanos}", std::process::id())
8782}
8783
8784#[derive(Debug)]
8785struct QueryTaskExecutionFailure {
8786    reason: String,
8787    message: String,
8788    failure_type: String,
8789}
8790
8791impl QueryTaskExecutionFailure {
8792    fn new(
8793        reason: impl Into<String>,
8794        message: impl Into<String>,
8795        failure_type: impl Into<String>,
8796    ) -> Self {
8797        Self {
8798            reason: reason.into(),
8799            message: message.into(),
8800            failure_type: failure_type.into(),
8801        }
8802    }
8803}
8804
8805/// Typed local state owned by one deterministic workflow invocation.
8806///
8807/// Use [`WorkflowInstance::update`] for the same state transitions during
8808/// ordinary execution and replay. A replayed query receives a detached
8809/// immutable `Arc<S>` rather than this mutation-capable handle.
8810#[derive(Clone, Debug)]
8811pub struct WorkflowInstance<S> {
8812    state: Arc<Mutex<S>>,
8813}
8814
8815impl<S> WorkflowInstance<S> {
8816    fn new(state: S) -> Self {
8817        Self {
8818            state: Arc::new(Mutex::new(state)),
8819        }
8820    }
8821
8822    /// Read the current workflow-instance state without changing it.
8823    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
8824        let state = self
8825            .state
8826            .lock()
8827            .map_err(|_| Error::WorkflowStatePoisoned)?;
8828        Ok(reader(&state))
8829    }
8830
8831    /// Apply one deterministic workflow-instance state transition.
8832    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
8833        let mut state = self
8834            .state
8835            .lock()
8836            .map_err(|_| Error::WorkflowStatePoisoned)?;
8837        Ok(transition(&mut state))
8838    }
8839}
8840
8841impl<S: Clone> WorkflowInstance<S> {
8842    fn snapshot(&self) -> Result<S> {
8843        self.read(Clone::clone)
8844    }
8845}
8846
8847#[derive(Clone, Debug, PartialEq)]
8848pub struct MessageStreamMessage {
8849    pub stream_name: String,
8850    pub message_id: String,
8851    pub position: u64,
8852    pub arguments: Vec<AvroValue>,
8853}
8854
8855#[derive(Clone, Debug)]
8856pub struct MessageStream {
8857    ctx: WorkflowContext,
8858    name: String,
8859}
8860
8861impl MessageStream {
8862    /// Wait for one message, then return a bounded currently-available batch.
8863    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
8864        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
8865            return Err(Error::Codec(format!(
8866                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
8867            )));
8868        }
8869        loop {
8870            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
8871                return Ok(batch);
8872            }
8873
8874            self.ctx.record_message_stream_wait(&self.name)?;
8875            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
8876            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
8877            self.ctx.buffer_message_stream_delivery(arguments)?;
8878            if let Some(sequence) = replay_wait_sequence {
8879                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
8880            }
8881        }
8882    }
8883
8884    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
8885        self.receive(1)
8886            .await?
8887            .into_iter()
8888            .next()
8889            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
8890    }
8891}
8892
8893#[derive(Clone, Debug)]
8894pub struct WorkflowContext {
8895    state: Arc<Mutex<WorkflowState>>,
8896    cancellation_scope_id: String,
8897}
8898
8899fn valid_memo_key(key: &str) -> bool {
8900    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
8901
8902    !key.is_empty()
8903        && key.len() <= 64
8904        && (numeric_candidate.is_empty()
8905            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
8906        && key
8907            .bytes()
8908            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
8909}
8910
8911fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
8912    BASE64
8913        .decode(encode_avro_value(value)?.blob)
8914        .map(|bytes| bytes.len())
8915        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
8916}
8917
8918fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
8919    let AvroValue::Map(entries) = value else {
8920        return Err(Error::InvalidMemoUpdate(
8921            "entries must serialize to an Avro string-keyed map".to_string(),
8922        ));
8923    };
8924    if require_entries && entries.is_empty() {
8925        return Err(Error::InvalidMemoUpdate(
8926            "at least one entry is required".to_string(),
8927        ));
8928    }
8929    if entries.len() > MAX_MEMO_ENTRIES {
8930        return Err(Error::InvalidMemoUpdate(format!(
8931            "at most {MAX_MEMO_ENTRIES} entries are allowed"
8932        )));
8933    }
8934
8935    for (key, value) in &entries {
8936        if !valid_memo_key(&key) {
8937            return Err(Error::InvalidMemoUpdate(
8938                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
8939            ));
8940        }
8941        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
8942            return Err(Error::InvalidMemoUpdate(format!(
8943                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
8944            )));
8945        }
8946    }
8947
8948    let value = AvroValue::Map(entries);
8949    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
8950        return Err(Error::InvalidMemoUpdate(format!(
8951            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
8952        )));
8953    }
8954    Ok(value)
8955}
8956
8957fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
8958    let object = envelope.as_object().ok_or_else(|| {
8959        Error::InvalidMemoUpdate(
8960            "history field must use the public {codec, blob} payload envelope".to_string(),
8961        )
8962    })?;
8963    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
8964        return Err(Error::InvalidMemoUpdate(
8965            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
8966        ));
8967    }
8968
8969    canonical_memo_entries(
8970        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
8971        require_entries,
8972    )
8973}
8974
8975impl WorkflowContext {
8976    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
8977        let name = name.into();
8978        if name.is_empty()
8979            || name.len() > 128
8980            || !name.bytes().all(|byte| {
8981                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
8982            })
8983        {
8984            return Err(Error::Codec(
8985                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
8986                    .to_string(),
8987            ));
8988        }
8989        Ok(MessageStream {
8990            ctx: self.clone(),
8991            name,
8992        })
8993    }
8994
8995    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
8996        let mut state = self
8997            .state
8998            .lock()
8999            .map_err(|_| Error::WorkflowStatePoisoned)?;
9000        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9001        state
9002            .message_stream_waits
9003            .insert(name.to_string(), position);
9004        Ok(())
9005    }
9006
9007    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
9008        let mut state = self
9009            .state
9010            .lock()
9011            .map_err(|_| Error::WorkflowStatePoisoned)?;
9012        let cursor = state
9013            .message_stream_cursors
9014            .get(&message.stream_name)
9015            .copied()
9016            .unwrap_or(0);
9017        if message.position <= cursor {
9018            return Ok(());
9019        }
9020        let pending = state
9021            .message_stream_messages
9022            .entry(message.stream_name.clone())
9023            .or_default();
9024        if pending.iter().any(|candidate| {
9025            candidate.position == message.position || candidate.message_id == message.message_id
9026        }) {
9027            return Ok(());
9028        }
9029        pending.push(message);
9030        pending.sort_by_key(|candidate| candidate.position);
9031        Ok(())
9032    }
9033
9034    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
9035        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
9036            match delivery {
9037                MessageStreamDelivery::Message(message) => {
9038                    let stream_name = message.stream_name.clone();
9039                    self.buffer_message_stream(message)?;
9040                    return Ok(Some(stream_name));
9041                }
9042                MessageStreamDelivery::Cursor {
9043                    stream_name,
9044                    through_position,
9045                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
9046            }
9047        }
9048        Ok(None)
9049    }
9050
9051    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
9052        let state = self
9053            .state
9054            .lock()
9055            .map_err(|_| Error::WorkflowStatePoisoned)?;
9056        Ok(match state.recorded_commands.get(state.command_cursor) {
9057            Some(RecordedCommand::SignalWait {
9058                sequence,
9059                signal_name,
9060                ..
9061            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
9062            _ => None,
9063        })
9064    }
9065
9066    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
9067        let (history, payload_codec) = {
9068            let state = self
9069                .state
9070                .lock()
9071                .map_err(|_| Error::WorkflowStatePoisoned)?;
9072            (
9073                Arc::clone(&state.history_events),
9074                state.payload_codec.clone(),
9075            )
9076        };
9077
9078        let Some(opened_index) = history.iter().position(|event| {
9079            event.event_type == "SignalWaitOpened"
9080                && durable_event_sequence(event) == Some(wait_sequence)
9081                && event.payload.get("signal_name").and_then(Value::as_str)
9082                    == Some(MESSAGE_STREAM_SIGNAL)
9083        }) else {
9084            return Ok(());
9085        };
9086        let boundary_index = history
9087            .iter()
9088            .enumerate()
9089            .skip(opened_index + 1)
9090            .find_map(|(index, event)| {
9091                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9092                    && is_authored_command_open_event(event))
9093                .then_some(index)
9094            })
9095            .unwrap_or(history.len());
9096
9097        for event in history[opened_index + 1..boundary_index]
9098            .iter()
9099            .filter(|event| {
9100                event.event_type == "SignalReceived"
9101                    && event.payload.get("signal_name").and_then(Value::as_str)
9102                        == Some(MESSAGE_STREAM_SIGNAL)
9103            })
9104        {
9105            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9106                .into_iter()
9107                .map(AvroValue::into_json)
9108                .collect::<Result<Vec<_>>>()?;
9109            self.buffer_message_stream_delivery(arguments)?;
9110        }
9111        Ok(())
9112    }
9113
9114    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9115        let mut state = self
9116            .state
9117            .lock()
9118            .map_err(|_| Error::WorkflowStatePoisoned)?;
9119        let cursor = state
9120            .message_stream_cursors
9121            .entry(name.to_string())
9122            .or_default();
9123        *cursor = (*cursor).max(through_position);
9124        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9125            pending.retain(|message| message.position > through_position);
9126        }
9127        Ok(())
9128    }
9129
9130    fn take_message_stream_batch(
9131        &self,
9132        name: &str,
9133        max_items: usize,
9134    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9135        let mut state = self
9136            .state
9137            .lock()
9138            .map_err(|_| Error::WorkflowStatePoisoned)?;
9139        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9140        let pending = state
9141            .message_stream_messages
9142            .entry(name.to_string())
9143            .or_default();
9144        let count = contiguous_message_stream_count(pending, cursor, max_items);
9145        if count == 0 {
9146            return Ok(None);
9147        }
9148        let batch = pending.drain(..count).collect::<Vec<_>>();
9149        let position = batch.last().map(|message| message.position).unwrap_or(0);
9150        state
9151            .message_stream_cursors
9152            .insert(name.to_string(), position);
9153        state.message_stream_waits.remove(name);
9154        Ok(Some(batch))
9155    }
9156
9157    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9158        let state = self
9159            .state
9160            .lock()
9161            .map_err(|_| Error::WorkflowStatePoisoned)?;
9162        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9163        cursors.sort_by_key(|(name, _)| *name);
9164        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9165        waits.sort_by_key(|(name, _)| *name);
9166        Ok((
9167            cursors
9168                .into_iter()
9169                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9170                .collect(),
9171            waits
9172                .into_iter()
9173                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9174                .collect(),
9175        ))
9176    }
9177    /// Identity of the parent workflow currently being replayed.
9178    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9179        let state = self
9180            .state
9181            .lock()
9182            .map_err(|_| Error::WorkflowStatePoisoned)?;
9183        Ok(WorkflowIdentity {
9184            workflow_id: state.workflow_id.clone(),
9185            run_id: state.run_id.clone(),
9186        })
9187    }
9188
9189    /// Return the server-published history budget for this workflow task.
9190    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9191        let state = self
9192            .state
9193            .lock()
9194            .map_err(|_| Error::WorkflowStatePoisoned)?;
9195        Ok(state.history_budget.clone())
9196    }
9197
9198    /// Continue this workflow instance as a fresh run with replacement arguments.
9199    ///
9200    /// Return this value directly from the workflow handler. The worker converts
9201    /// it to the terminal protocol command only after replay has consumed every
9202    /// recorded durable command.
9203    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9204        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9205    }
9206
9207    /// Continue as new with optional workflow-type and task-queue overrides.
9208    pub fn continue_as_new_with_options<T: Serialize>(
9209        &self,
9210        options: ContinueAsNewOptions,
9211        args: T,
9212    ) -> Result<Value> {
9213        options.validate()?;
9214        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9215            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9216            options,
9217        }))
9218    }
9219
9220    pub fn activity<T: Serialize>(
9221        &self,
9222        activity_type: impl Into<String>,
9223        args: T,
9224    ) -> ActivityCall {
9225        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9226    }
9227
9228    pub fn activity_on_queue<T, Q>(
9229        &self,
9230        activity_type: impl Into<String>,
9231        task_queue: Option<Q>,
9232        args: T,
9233    ) -> ActivityCall
9234    where
9235        T: Serialize,
9236        Q: Into<String>,
9237    {
9238        let mut options = ActivityOptions::new();
9239        options.task_queue = task_queue.map(Into::into);
9240        self.activity_with_options(activity_type, options, args)
9241    }
9242
9243    /// Schedule one durable activity with retry, routing, and timeout options.
9244    ///
9245    /// Options are validated before the command is emitted. Once the command is
9246    /// recorded, replay consumes the same activity lifecycle at this command
9247    /// position and never emits a duplicate schedule.
9248    ///
9249    /// ```no_run
9250    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9251    /// # use std::time::Duration;
9252    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9253    /// let result = ctx
9254    ///     .activity_with_options(
9255    ///         "charge-card",
9256    ///         ActivityOptions::new()
9257    ///             .task_queue("payments")
9258    ///             .retry_policy(
9259    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9260    ///                     Duration::from_secs(1),
9261    ///                     2,
9262    ///                     Some(Duration::from_secs(30)),
9263    ///                 ),
9264    ///             )
9265    ///             .start_to_close_timeout(Duration::from_secs(60))
9266    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9267    ///             .heartbeat_timeout(Duration::from_secs(15)),
9268    ///         json!([{"order_id": "order-42"}]),
9269    ///     )
9270    ///     .await;
9271    /// match result {
9272    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9273    ///         "reason": failure.reason,
9274    ///         "timeout_kind": failure.timeout_kind,
9275    ///     })),
9276    ///     other => other,
9277    /// }
9278    /// # }
9279    /// ```
9280    pub fn activity_with_options<T: Serialize>(
9281        &self,
9282        activity_type: impl Into<String>,
9283        options: ActivityOptions,
9284        args: T,
9285    ) -> ActivityCall {
9286        ActivityCall {
9287            ctx: self.clone(),
9288            activity_type: activity_type.into(),
9289            options,
9290            worker_session: None,
9291            args: Some(AvroValue::from_serialize(&args)),
9292            scheduled: false,
9293            local: false,
9294            local_result: None,
9295            parallel_group_path: Vec::new(),
9296        }
9297    }
9298
9299    pub async fn activity_avro_value<T: Serialize>(
9300        &self,
9301        activity_type: impl Into<String>,
9302        args: T,
9303    ) -> Result<AvroValue> {
9304        let mut call = self.activity(activity_type, args);
9305        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9306    }
9307
9308    pub async fn activity_avro_value_with_options<T: Serialize>(
9309        &self,
9310        activity_type: impl Into<String>,
9311        options: ActivityOptions,
9312        args: T,
9313    ) -> Result<AvroValue> {
9314        let mut call = self.activity_with_options(activity_type, options, args);
9315        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9316    }
9317
9318    /// Schedule an activity with a Serde request and decode its Serde result.
9319    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9320    where
9321        I: Serialize,
9322        O: DeserializeOwned,
9323    {
9324        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9325            .await
9326    }
9327
9328    /// Schedule an activity with options and decode its result into `O`.
9329    ///
9330    /// Both directions use the fixed Avro Value codec. In particular, this
9331    /// method does not deserialize the JSON-safe inspection projection returned
9332    /// by the dynamic [`ActivityCall`] future.
9333    pub async fn activity_typed_with_options<I, O>(
9334        &self,
9335        activity_type: impl Into<String>,
9336        options: ActivityOptions,
9337        args: I,
9338    ) -> Result<O>
9339    where
9340        I: Serialize,
9341        O: DeserializeOwned,
9342    {
9343        let activity_type = activity_type.into();
9344        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9345            handler_type_error::<I>(
9346                HandlerKind::Activity,
9347                &activity_type,
9348                HandlerValueKind::Input,
9349                error.to_string(),
9350            )
9351        });
9352        let mut call = ActivityCall {
9353            ctx: self.clone(),
9354            activity_type: activity_type.clone(),
9355            options,
9356            worker_session: None,
9357            args: Some(encoded),
9358            scheduled: false,
9359            local: false,
9360            local_result: None,
9361            parallel_group_path: Vec::new(),
9362        };
9363        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9364        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9365    }
9366
9367    /// Schedule and join a deterministic activity/child/timer group.
9368    ///
9369    /// Nested groups retain their input shape. Every durable leaf is scheduled
9370    /// before this future yields, results are assembled by declaration order,
9371    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9372    /// declaration path, stable group metadata, and completed siblings.
9373    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9374        ParallelCall::new(self.clone(), operations)
9375    }
9376
9377    /// Alias for [`WorkflowContext::parallel`].
9378    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9379        self.parallel(operations)
9380    }
9381
9382    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
9383    pub async fn parallel_avro_value(
9384        &self,
9385        operations: Vec<ParallelOperation>,
9386    ) -> Result<Vec<ParallelAvroResult>> {
9387        let mut call = self.parallel(operations);
9388        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9389    }
9390
9391    /// Start every durable operation and resume from the one winner persisted
9392    /// by Server. Non-winning operations continue and remain addressable.
9393    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
9394        let operations = operations
9395            .into_iter()
9396            .enumerate()
9397            .map(|(index, operation)| (SelectionKey::Index(index), operation))
9398            .collect();
9399        SelectCall::new(self.clone(), operations)
9400    }
9401
9402    /// Named-key variant of [`WorkflowContext::select`].
9403    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
9404    where
9405        K: Into<SelectionKey>,
9406    {
9407        SelectCall::new(
9408            self.clone(),
9409            operations
9410                .into_iter()
9411                .map(|(key, operation)| (key.into(), operation))
9412                .collect(),
9413        )
9414    }
9415
9416    /// Create a workflow-local deterministic compensation registry.
9417    pub fn saga(&self) -> Saga {
9418        Saga::new(self.clone())
9419    }
9420
9421    /// Whether cancellation has reached this replay's authored boundary.
9422    ///
9423    /// Server's current `/cancel` route is terminal and does not set this flag.
9424    /// A canonical service request remains pending until its committed delivery
9425    /// is consumed. Request observation alone does not authorize an exception.
9426    pub fn is_cancellation_requested(&self) -> Result<bool> {
9427        let state = self
9428            .state
9429            .lock()
9430            .map_err(|_| Error::WorkflowStatePoisoned)?;
9431        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9432            return Ok(state
9433                .scope_delivery
9434                .as_ref()
9435                .unwrap()
9436                .contexts
9437                .contains_key(&self.cancellation_scope_id));
9438        }
9439        Ok(state.cancel_requested
9440            || state
9441                .scope_delivery
9442                .as_ref()
9443                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
9444    }
9445
9446    /// Raise a typed cooperative cancellation at an author-controlled point.
9447    ///
9448    /// Passing this result to [`Saga::finish`] compensates already registered
9449    /// forward steps before the cancellation remains the initiating outcome.
9450    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
9451        let mut state = self
9452            .state
9453            .lock()
9454            .map_err(|_| Error::WorkflowStatePoisoned)?;
9455        if state.cancellation_shield_depth == 0 {
9456            if let Some(replay) = &state.scope_delivery {
9457                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
9458                    let delivered = replay
9459                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
9460                        .ok_or_else(|| {
9461                            Error::InvalidCooperativeCancellation(
9462                                "scoped request lacks its consumed original delivery".into(),
9463                            )
9464                        })?;
9465                    return Err(Error::CancellationScopeRequested(
9466                        CancellationScopeRequested {
9467                            context: context
9468                                .clone()
9469                                .with_replay(Some(Arc::downgrade(&self.state))),
9470                            delivery: delivered.boundary.clone(),
9471                        },
9472                    ));
9473                }
9474            }
9475        }
9476        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9477            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9478                return Ok(());
9479            }
9480            return Err(state.cancellation_error());
9481        }
9482        Ok(())
9483    }
9484
9485    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9486        SignalCall {
9487            ctx: self.clone(),
9488            signal_name: signal_name.into(),
9489            runtime_reserved_allowed: false,
9490            opened_wait: false,
9491            matched_pending: false,
9492            parallel_group_path: Vec::new(),
9493        }
9494    }
9495
9496    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9497        SignalCall {
9498            ctx: self.clone(),
9499            signal_name: signal_name.into(),
9500            runtime_reserved_allowed: true,
9501            opened_wait: false,
9502            matched_pending: false,
9503            parallel_group_path: Vec::new(),
9504        }
9505    }
9506
9507    pub async fn wait_signal_avro_value(
9508        &self,
9509        signal_name: impl Into<String>,
9510    ) -> Result<Vec<AvroValue>> {
9511        let mut call = self.wait_signal(signal_name);
9512        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9513    }
9514
9515    /// Return every committed signal argument list with the given name.
9516    ///
9517    /// This history-backed view is deterministic and is intended for
9518    /// condition predicates that must be re-evaluated after a signal while the
9519    /// workflow is blocked on [`WorkflowContext::wait_condition`].
9520    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
9521        self.signals_avro_value(signal_name)?
9522            .into_iter()
9523            .map(|arguments| {
9524                arguments
9525                    .into_iter()
9526                    .map(AvroValue::into_json)
9527                    .collect::<Result<Vec<_>>>()
9528            })
9529            .collect()
9530    }
9531
9532    /// Lossless fixed Avro Value view of committed signals with the given name.
9533    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9534        let state = self
9535            .state
9536            .lock()
9537            .map_err(|_| Error::WorkflowStatePoisoned)?;
9538        state
9539            .history_events
9540            .iter()
9541            .filter(|event| {
9542                event.event_type == "SignalReceived"
9543                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
9544            })
9545            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
9546            .collect()
9547    }
9548
9549    /// Return every committed update argument list with the given name.
9550    ///
9551    /// Accepted and applied records for the same update ID are de-duplicated.
9552    /// A Server task created after an update therefore replays the workflow and
9553    /// re-evaluates an open condition without application polling.
9554    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
9555        self.updates_avro_value(update_name)?
9556            .into_iter()
9557            .map(|arguments| {
9558                arguments
9559                    .into_iter()
9560                    .map(AvroValue::into_json)
9561                    .collect::<Result<Vec<_>>>()
9562            })
9563            .collect()
9564    }
9565
9566    /// Lossless fixed Avro Value view of committed updates with the given name.
9567    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9568        let state = self
9569            .state
9570            .lock()
9571            .map_err(|_| Error::WorkflowStatePoisoned)?;
9572        let mut seen = Vec::new();
9573        let mut updates = Vec::new();
9574        for event in state.history_events.iter() {
9575            if !matches!(
9576                event.event_type.as_str(),
9577                "UpdateAccepted" | "UpdateApplied"
9578            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
9579                || event.payload.get("arguments").is_none()
9580            {
9581                continue;
9582            }
9583            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
9584                if seen.iter().any(|recorded| recorded == update_id) {
9585                    continue;
9586                }
9587                seen.push(update_id.to_string());
9588            }
9589            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
9590        }
9591        Ok(updates)
9592    }
9593
9594    /// Wait for a deterministic predicate to become true or for its durable
9595    /// timeout to elapse.
9596    ///
9597    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
9598    /// predicate tokens automatically change the recorded definition
9599    /// fingerprint. Direct callers must provide an equally stable identity in
9600    /// [`ConditionWaitOptions`].
9601    pub fn wait_condition<F>(
9602        &self,
9603        options: ConditionWaitOptions,
9604        predicate: F,
9605    ) -> ConditionWaitCall
9606    where
9607        F: Fn() -> Result<bool> + Send + 'static,
9608    {
9609        ConditionWaitCall {
9610            ctx: self.clone(),
9611            options,
9612            predicate: Box::new(predicate),
9613            occurrence_id: None,
9614            opened_wait: false,
9615            parallel_group_path: Vec::new(),
9616        }
9617    }
9618
9619    /// Wait for server-backed durable time without blocking the worker executor.
9620    ///
9621    /// Polling this future emits one `start_timer` command and yields. The
9622    /// server records the deadline, so neither worker nor server restarts reset
9623    /// the wait. Replay resolves the future only from a `TimerScheduled` and
9624    /// `TimerFired` pair at the same position in the shared durable-command
9625    /// stream, with matching sequence, timer identity, and delay. Sub-second
9626    /// durations round up because protocol deadlines use whole seconds.
9627    ///
9628    /// ```no_run
9629    /// # use durable_workflow::{json, Client, Worker};
9630    /// # use std::time::Duration;
9631    /// # fn configure(client: Client) {
9632    /// let mut worker = Worker::new(client, "rust-workers");
9633    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
9634    ///     ctx.sleep(Duration::from_secs(5)).await?;
9635    ///     Ok(json!({"status": "timer fired"}))
9636    /// });
9637    /// # }
9638    /// ```
9639    pub fn sleep(&self, duration: Duration) -> TimerCall {
9640        let delay_seconds = duration
9641            .as_secs()
9642            .checked_add(u64::from(duration.subsec_nanos() > 0));
9643        TimerCall {
9644            ctx: self.clone(),
9645            delay_seconds,
9646            scheduled: false,
9647            matched_pending: false,
9648            parallel_group_path: Vec::new(),
9649        }
9650    }
9651
9652    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
9653    pub fn start_timer(&self, duration: Duration) -> TimerCall {
9654        self.sleep(duration)
9655    }
9656
9657    /// Evaluate a non-deterministic callback once and durably record its typed value.
9658    ///
9659    /// On replay the callback is not invoked: the value is decoded from the
9660    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
9661    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
9662    /// small values that must remain fixed for the lifetime of a workflow run.
9663    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
9664    where
9665        T: Serialize + DeserializeOwned,
9666        F: FnOnce() -> T,
9667    {
9668        {
9669            let mut state = self
9670                .state
9671                .lock()
9672                .map_err(|_| Error::WorkflowStatePoisoned)?;
9673            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9674                return match recorded {
9675                    RecordedCommand::SideEffect { sequence, value } => {
9676                        state.command_cursor += 1;
9677                        value.deserialize().map_err(|error| {
9678                            Error::NonDeterministicReplay(ReplayFailure::new(
9679                                "side_effect_type_mismatch",
9680                                Some(sequence),
9681                                Some(std::any::type_name::<T>().to_string()),
9682                                Some(error.to_string()),
9683                                "recorded side-effect value is incompatible with the requested Rust type",
9684                            ))
9685                        })
9686                    }
9687                    other => Err(command_mismatch(&other, "side effect")),
9688                };
9689            }
9690        }
9691
9692        let value = callback();
9693        let avro_value = AvroValue::from_serialize(&value)?;
9694        let mut state = self
9695            .state
9696            .lock()
9697            .map_err(|_| Error::WorkflowStatePoisoned)?;
9698        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
9699        state.commands.push(json!({
9700            "type": "record_side_effect",
9701            "result": result,
9702        }));
9703        Ok(value)
9704    }
9705
9706    /// Record or replay a lossless fixed Avro Value side effect.
9707    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
9708    where
9709        F: FnOnce() -> AvroValue,
9710    {
9711        {
9712            let mut state = self
9713                .state
9714                .lock()
9715                .map_err(|_| Error::WorkflowStatePoisoned)?;
9716            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9717                return match recorded {
9718                    RecordedCommand::SideEffect { value, .. } => {
9719                        state.command_cursor += 1;
9720                        Ok(value)
9721                    }
9722                    other => Err(command_mismatch(&other, "side effect")),
9723                };
9724            }
9725        }
9726
9727        let value = callback();
9728        let mut state = self
9729            .state
9730            .lock()
9731            .map_err(|_| Error::WorkflowStatePoisoned)?;
9732        let result = encode_typed_envelope(&value, &state.payload_codec)?;
9733        state.commands.push(json!({
9734            "type": "record_side_effect",
9735            "result": result,
9736        }));
9737        Ok(value)
9738    }
9739
9740    /// Append output items at a deterministic workflow command boundary.
9741    ///
9742    /// Stable idempotency keys are derived from the server-provided durable
9743    /// workflow command identity, command ordinal, and item index. Replay
9744    /// consumes the recorded side effect and never emits another append.
9745    pub fn append_workflow_stream(
9746        &self,
9747        stream_name: impl Into<String>,
9748        items: &[WorkflowStreamAppendItem],
9749        max_pending_items: Option<u64>,
9750    ) -> Result<()> {
9751        if items.is_empty() {
9752            return Err(Error::Codec(
9753                "workflow_stream_items_empty: append requires at least one item".to_string(),
9754            ));
9755        }
9756        if max_pending_items == Some(0) {
9757            return Err(Error::Codec(
9758                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
9759                    .to_string(),
9760            ));
9761        }
9762        let stream_name = stream_name.into();
9763        if stream_name.is_empty() {
9764            return Err(Error::Codec(
9765                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9766            ));
9767        }
9768
9769        let mut state = self
9770            .state
9771            .lock()
9772            .map_err(|_| Error::WorkflowStatePoisoned)?;
9773        let command_ordinal = state.workflow_stream_command_counter;
9774        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9775            state.workflow_stream_command_counter += 1;
9776            return match recorded {
9777                RecordedCommand::SideEffect { .. } => {
9778                    state.command_cursor += 1;
9779                    Ok(())
9780                }
9781                other => Err(command_mismatch(&other, "workflow stream append")),
9782            };
9783        }
9784
9785        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9786        state.workflow_stream_command_counter += 1;
9787        let wire_items = items
9788            .iter()
9789            .enumerate()
9790            .map(|(item_index, item)| {
9791                item.wire_value(Some(format!(
9792                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
9793                )))
9794            })
9795            .collect::<Vec<_>>();
9796        let mut directive = json!({
9797            "operation": "append",
9798            "stream_name": stream_name,
9799            "command_identity": identity,
9800            "command_ordinal": command_ordinal,
9801            "items": wire_items,
9802        });
9803        if let Some(max_pending_items) = max_pending_items {
9804            directive["max_pending_items"] = json!(max_pending_items);
9805        }
9806        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9807        state.commands.push(json!({
9808            "type": "record_side_effect",
9809            "result": result,
9810            "workflow_stream": directive,
9811        }));
9812        Ok(())
9813    }
9814
9815    /// Close a run-scoped output stream at a deterministic command boundary.
9816    pub fn close_workflow_stream(
9817        &self,
9818        stream_name: impl Into<String>,
9819        retention_seconds: Option<u64>,
9820    ) -> Result<()> {
9821        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
9822    }
9823
9824    /// Mark a run-scoped output stream errored at a deterministic command boundary.
9825    pub fn error_workflow_stream(
9826        &self,
9827        stream_name: impl Into<String>,
9828        error_reason: impl Into<String>,
9829        retention_seconds: Option<u64>,
9830    ) -> Result<()> {
9831        let error_reason = error_reason.into();
9832        if error_reason.is_empty() {
9833            return Err(Error::Codec(
9834                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
9835            ));
9836        }
9837        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
9838    }
9839
9840    fn finish_workflow_stream(
9841        &self,
9842        stream_name: String,
9843        error_reason: Option<String>,
9844        retention_seconds: Option<u64>,
9845    ) -> Result<()> {
9846        if stream_name.is_empty() {
9847            return Err(Error::Codec(
9848                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
9849            ));
9850        }
9851        if retention_seconds == Some(0) {
9852            return Err(Error::Codec(
9853                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
9854            ));
9855        }
9856        let mut state = self
9857            .state
9858            .lock()
9859            .map_err(|_| Error::WorkflowStatePoisoned)?;
9860        let command_ordinal = state.workflow_stream_command_counter;
9861        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9862            state.workflow_stream_command_counter += 1;
9863            return match recorded {
9864                RecordedCommand::SideEffect { .. } => {
9865                    state.command_cursor += 1;
9866                    Ok(())
9867                }
9868                other => Err(command_mismatch(&other, "workflow stream close")),
9869            };
9870        }
9871        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
9872        state.workflow_stream_command_counter += 1;
9873        let mut directive = json!({
9874            "operation": if error_reason.is_some() { "error" } else { "close" },
9875            "stream_name": stream_name,
9876            "command_identity": identity,
9877            "command_ordinal": command_ordinal,
9878        });
9879        if let Some(error_reason) = error_reason {
9880            directive["error_reason"] = json!(error_reason);
9881        }
9882        if let Some(retention_seconds) = retention_seconds {
9883            directive["retention_seconds"] = json!(retention_seconds);
9884        }
9885        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
9886        state.commands.push(json!({
9887            "type": "record_side_effect",
9888            "result": result,
9889            "workflow_stream": directive,
9890        }));
9891        Ok(())
9892    }
9893
9894    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
9895        let identity = state.workflow_command_identity.as_str();
9896        if identity.is_empty() {
9897            return Err(Error::MissingWorkflowCommandIdentity);
9898        }
9899        Ok(identity)
9900    }
9901
9902    /// Validate, emit, or replay a typed workflow search-attribute update.
9903    ///
9904    /// The command is non-blocking within a workflow decision, but its
9905    /// `SearchAttributesUpserted` event occupies the same deterministic command
9906    /// stream as activities, timers, conditions, and other durable operations.
9907    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
9908        update.validate()?;
9909        let (attributes, attribute_types) = update.into_wire_parts();
9910        let mut state = self
9911            .state
9912            .lock()
9913            .map_err(|_| Error::WorkflowStatePoisoned)?;
9914
9915        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
9916            return match recorded {
9917                RecordedCommand::SearchAttributes {
9918                    sequence,
9919                    attributes: recorded_attributes,
9920                    attribute_types: recorded_attribute_types,
9921                } => {
9922                    if recorded_attributes != attributes {
9923                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9924                            "search_attribute_value_mismatch",
9925                            Some(sequence),
9926                            Some(recorded_attributes.to_string()),
9927                            Some(attributes.to_string()),
9928                            "search-attribute values differ from the recorded durable command",
9929                        )));
9930                    }
9931                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
9932                        if recorded_types != attribute_types {
9933                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9934                                "search_attribute_type_mismatch",
9935                                Some(sequence),
9936                                Some(json!(recorded_types).to_string()),
9937                                Some(json!(attribute_types).to_string()),
9938                                "search-attribute declared types differ from the recorded durable command",
9939                            )));
9940                        }
9941                    }
9942                    state.command_cursor += 1;
9943                    Ok(())
9944                }
9945                other => Err(command_mismatch(&other, "search-attribute update")),
9946            };
9947        }
9948
9949        let mut command = serde_json::Map::from_iter([
9950            ("type".to_string(), json!("upsert_search_attributes")),
9951            ("attributes".to_string(), attributes),
9952        ]);
9953        if !attribute_types.is_empty() {
9954            command.insert("attribute_types".to_string(), json!(attribute_types));
9955        }
9956        state.commands.push(Value::Object(command));
9957        Ok(())
9958    }
9959
9960    /// Record a UUIDv4 once and return the same UUID on every replay.
9961    pub fn uuid_v4(&self) -> Result<Uuid> {
9962        self.side_effect(Uuid::new_v4)
9963    }
9964
9965    /// Select the newest supported version for a change, or replay the version
9966    /// already committed for that stable change ID.
9967    ///
9968    /// An unmarked old history that reached its next durable operation, or
9969    /// already completed, selects `-1` when that version is supported. This
9970    /// leaves the original operation available and writes no additional marker.
9971    /// Consistent markers written by older workers retain their original ordered
9972    /// positions. Repeated calls consume a matching marker at the current cursor.
9973    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
9974    pub fn get_version(
9975        &self,
9976        change_id: impl Into<String>,
9977        min_supported: i32,
9978        max_supported: i32,
9979    ) -> Result<i32> {
9980        let change_id = change_id.into();
9981        if change_id.trim().is_empty() {
9982            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9983                "version_change_id_invalid",
9984                None,
9985                Some("non-empty change ID".to_string()),
9986                Some(change_id),
9987                "version markers require a stable non-empty change ID",
9988            )));
9989        }
9990        if min_supported > max_supported {
9991            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
9992                "version_range_invalid",
9993                None,
9994                Some("min_supported <= max_supported".to_string()),
9995                Some(format!("{min_supported}..={max_supported}")),
9996                "version marker supported range is invalid",
9997            )));
9998        }
9999
10000        let mut state = self
10001            .state
10002            .lock()
10003            .map_err(|_| Error::WorkflowStatePoisoned)?;
10004        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
10005            if let Some(RecordedCommand::VersionMarker {
10006                sequence: alias_sequence,
10007                change_id: alias_change_id,
10008                version: alias_version,
10009            }) = state.recorded_commands.get(state.command_cursor)
10010            {
10011                if alias_change_id == &change_id {
10012                    if *alias_version != version {
10013                        return Err(invalid_recorded_history(
10014                            "version_marker_conflict",
10015                            *alias_sequence,
10016                            &format!("selected version {version} for change ID {change_id:?}"),
10017                            &format!("recorded version {alias_version}"),
10018                            "recorded marker conflicts with the decision already selected during replay",
10019                        ));
10020                    }
10021                    ensure_version_supported(
10022                        &change_id,
10023                        version,
10024                        min_supported,
10025                        max_supported,
10026                        *alias_sequence,
10027                    )?;
10028                    // Older workers could record the same decision again. Keep
10029                    // each physical boundary without skipping intervening work.
10030                    state.command_cursor += 1;
10031                    return Ok(version);
10032                }
10033            }
10034            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
10035            return Ok(version);
10036        }
10037
10038        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10039            return match recorded {
10040                RecordedCommand::VersionMarker {
10041                    sequence,
10042                    change_id: recorded_change_id,
10043                    version,
10044                    ..
10045                } => {
10046                    if recorded_change_id != change_id {
10047                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10048                            "version_change_id_mismatch",
10049                            Some(sequence),
10050                            Some(recorded_change_id),
10051                            Some(change_id),
10052                            "recorded version marker change ID differs from current workflow code",
10053                        )));
10054                    }
10055                    ensure_version_supported(
10056                        &change_id,
10057                        version,
10058                        min_supported,
10059                        max_supported,
10060                        sequence,
10061                    )?;
10062                    state.command_cursor += 1;
10063                    state.version_markers.insert(change_id, (version, sequence));
10064                    Ok(version)
10065                }
10066                other => {
10067                    let version = -1;
10068                    let sequence = other.sequence();
10069                    ensure_version_supported(
10070                        &change_id,
10071                        version,
10072                        min_supported,
10073                        max_supported,
10074                        sequence,
10075                    )?;
10076                    // The existing operation proves this patch site was reached
10077                    // before its marker existed. Keep its original cursor.
10078                    state.version_markers.insert(change_id, (version, sequence));
10079                    Ok(version)
10080                }
10081            };
10082        }
10083
10084        if state
10085            .history_events
10086            .iter()
10087            .any(|event| event.event_type == "WorkflowCompleted")
10088        {
10089            let version = -1;
10090            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
10091            state.version_markers.insert(change_id, (version, 0));
10092            return Ok(version);
10093        }
10094
10095        let version = max_supported;
10096        state.commands.push(json!({
10097            "type": "record_version_marker",
10098            "change_id": change_id,
10099            "version": version,
10100            "min_supported": min_supported,
10101            "max_supported": max_supported,
10102        }));
10103        // Sequence numbers are assigned by the server. Zero identifies a marker
10104        // selected in this uncommitted decision batch for duplicate-call checks.
10105        state.version_markers.insert(change_id, (version, 0));
10106        Ok(version)
10107    }
10108
10109    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
10110    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
10111        Ok(self.get_version(change_id, -1, 1)? == 1)
10112    }
10113
10114    /// Keep a patch marker in history after the legacy branch has been removed.
10115    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
10116        self.get_version(change_id, -1, 1).map(|_| ())
10117    }
10118
10119    /// Merge non-indexed workflow memo metadata through durable history.
10120    ///
10121    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
10122    /// public Avro payload envelope consumed by Server and Cloud runtimes.
10123    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
10124        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
10125        let mut state = self
10126            .state
10127            .lock()
10128            .map_err(|_| Error::WorkflowStatePoisoned)?;
10129
10130        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10131            return match recorded {
10132                RecordedCommand::Memo {
10133                    sequence,
10134                    entries: recorded_entries,
10135                } => {
10136                    if recorded_entries != entries {
10137                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10138                            "memo_update_mismatch",
10139                            Some(sequence),
10140                            Some(format!("{recorded_entries:?}")),
10141                            Some(format!("{entries:?}")),
10142                            "recorded memo entries differ from the current workflow update",
10143                        )));
10144                    }
10145                    state.command_cursor += 1;
10146                    Ok(())
10147                }
10148                other => Err(command_mismatch(&other, "memo upsert")),
10149            };
10150        }
10151
10152        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10153        state.commands.push(json!({
10154            "type": "upsert_memo",
10155            "entries": entries_envelope,
10156        }));
10157        Ok(())
10158    }
10159
10160    /// Start a named durable child on an explicit queue and await its result.
10161    ///
10162    /// The command is recorded in the parent's sequence-ordered durable command
10163    /// stream. Replay keeps a scheduled child pending without emitting another
10164    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10165    /// values preserve the history payload codec and include both sides of the
10166    /// durable relationship; failures are returned as
10167    /// [`Error::ChildWorkflowFailed`].
10168    ///
10169    /// ```no_run
10170    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10171    /// # fn configure(client: Client) {
10172    /// let mut worker = Worker::new(client, "parent-workers");
10173    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10174    ///     let child = ctx
10175    ///         .start_child_workflow(
10176    ///             "fulfil-order",
10177    ///             ChildWorkflowOptions::new("fulfilment-workers")
10178    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10179    ///             json!([{"order_id": "order-42"}]),
10180    ///         )
10181    ///         .await?;
10182    ///     Ok(child.result)
10183    /// });
10184    /// # }
10185    /// ```
10186    pub fn start_child_workflow<T: Serialize>(
10187        &self,
10188        workflow_type: impl Into<String>,
10189        options: ChildWorkflowOptions,
10190        args: T,
10191    ) -> ChildWorkflowCall {
10192        ChildWorkflowCall {
10193            ctx: self.clone(),
10194            workflow_type: workflow_type.into(),
10195            options,
10196            args: Some(AvroValue::from_serialize(&args)),
10197            scheduled: false,
10198            matched_pending: false,
10199            parallel_group_path: Vec::new(),
10200        }
10201    }
10202
10203    pub async fn start_child_workflow_avro_value<T: Serialize>(
10204        &self,
10205        workflow_type: impl Into<String>,
10206        options: ChildWorkflowOptions,
10207        args: T,
10208    ) -> Result<ChildWorkflowAvroResult> {
10209        let mut call = self.start_child_workflow(workflow_type, options, args);
10210        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10211    }
10212
10213    fn take_commands(&self) -> Result<Vec<Value>> {
10214        let mut state = self
10215            .state
10216            .lock()
10217            .map_err(|_| Error::WorkflowStatePoisoned)?;
10218        Ok(std::mem::take(&mut state.commands))
10219    }
10220
10221    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10222        let mut state = self
10223            .state
10224            .lock()
10225            .map_err(|_| Error::WorkflowStatePoisoned)?;
10226
10227        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10228            return Err(command_mismatch(&recorded, "continue as new"));
10229        }
10230        if state.recorded_continue_as_new_sequence.is_some() {
10231            state.continue_as_new_consumed = true;
10232            return Ok(None);
10233        }
10234
10235        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10236        let mut command = serde_json::Map::from_iter([
10237            ("type".to_string(), json!("continue_as_new")),
10238            ("arguments".to_string(), arguments),
10239            ("queue".to_string(), json!(state.task_queue.clone())),
10240        ]);
10241        if let Some(workflow_type) = request.options.workflow_type {
10242            command.insert("workflow_type".to_string(), json!(workflow_type));
10243        }
10244        if let Some(task_queue) = request.options.task_queue {
10245            command.insert("queue".to_string(), json!(task_queue));
10246        }
10247        Ok(Some(Value::Object(command)))
10248    }
10249
10250    fn matched_recorded_pending(&self) -> Result<bool> {
10251        let state = self
10252            .state
10253            .lock()
10254            .map_err(|_| Error::WorkflowStatePoisoned)?;
10255        Ok(state.matched_recorded_pending)
10256    }
10257
10258    fn ensure_history_consumed(&self) -> Result<()> {
10259        let state = self
10260            .state
10261            .lock()
10262            .map_err(|_| Error::WorkflowStatePoisoned)?;
10263        if let Some(replay) = &state.scope_delivery {
10264            if let Some((&sequence, _)) = replay
10265                .canonical
10266                .deliveries
10267                .iter()
10268                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10269            {
10270                return Err(invalid_recorded_history(
10271                    "cancellation_scope_delivery_unconsumed",
10272                    sequence,
10273                    "original scoped delivery",
10274                    "workflow completion",
10275                    "workflow completed without consuming its committed scope delivery",
10276                ));
10277            }
10278        }
10279        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10280            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10281                "recorded_commands_unconsumed",
10282                Some(command.sequence()),
10283                Some(command.shape().to_string()),
10284                Some("workflow completion".to_string()),
10285                "workflow completed before consuming all recorded durable commands",
10286            )));
10287        }
10288        if let Some(delivery) = state
10289            .cancellation_history
10290            .delivery
10291            .as_ref()
10292            .filter(|_| !state.cancellation_consumed)
10293        {
10294            return Err(invalid_recorded_history(
10295                "cooperative_cancellation_unconsumed",
10296                delivery.sequence,
10297                "committed cancellation call",
10298                "workflow completion",
10299                "workflow completed without reaching its committed cancellation boundary",
10300            ));
10301        }
10302        if let Some(sequence) = state
10303            .recorded_continue_as_new_sequence
10304            .filter(|_| !state.continue_as_new_consumed)
10305        {
10306            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10307                "recorded_continue_as_new_unconsumed",
10308                Some(sequence),
10309                Some("continue as new".to_string()),
10310                Some("workflow completion".to_string()),
10311                "workflow completed without consuming its recorded continue-as-new transition",
10312            )));
10313        }
10314        Ok(())
10315    }
10316}
10317
10318fn contiguous_message_stream_count(
10319    pending: &[MessageStreamMessage],
10320    cursor: u64,
10321    max_items: usize,
10322) -> usize {
10323    pending
10324        .iter()
10325        .take(max_items)
10326        .enumerate()
10327        .take_while(|(offset, message)| {
10328            u64::try_from(*offset)
10329                .ok()
10330                .and_then(|offset| cursor.checked_add(offset + 1))
10331                == Some(message.position)
10332        })
10333        .count()
10334}
10335
10336fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10337    matches!(
10338        event.event_type.as_str(),
10339        "ActivityScheduled"
10340            | "TimerScheduled"
10341            | "ChildWorkflowScheduled"
10342            | "SignalWaitOpened"
10343            | "ConditionWaitOpened"
10344            | "SearchAttributesUpserted"
10345            | "SideEffectRecorded"
10346            | "VersionMarkerRecorded"
10347            | "MemoUpserted"
10348            | "WorkflowContinuedAsNew"
10349    )
10350}
10351
10352#[derive(Debug)]
10353struct WorkflowState {
10354    workflow_id: Option<String>,
10355    run_id: Option<String>,
10356    task_queue: String,
10357    payload_codec: String,
10358    history_events: Arc<Vec<HistoryEvent>>,
10359    history_budget: WorkflowHistoryBudget,
10360    cancel_requested: bool,
10361    cancellation_history: CancellationHistory,
10362    cancellation_consumed: bool,
10363    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10364    cancellation_shield_depth: u64,
10365    cancellation_delivery_enabled: bool,
10366    cancellation_delivery_intent: Option<CancellationDelivery>,
10367    cancellation_delivery_command_count: usize,
10368    allow_cancellation_scope_authoring: bool,
10369    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10370    cancellation_scope_memberships: BTreeMap<u64, String>,
10371    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10372    resume_signal: Option<ResumeSignal>,
10373    recorded_commands: Vec<RecordedCommand>,
10374    selection_markers: Vec<SelectionMarker>,
10375    selection_marker_cursor: usize,
10376    cancelled_selection_members: Vec<SelectionCancellation>,
10377    recorded_continue_as_new_sequence: Option<u64>,
10378    continue_as_new_consumed: bool,
10379    command_cursor: usize,
10380    condition_wait_occurrence_counter: u64,
10381    matched_recorded_pending: bool,
10382    version_markers: HashMap<String, (i32, u64)>,
10383    workflow_command_identity: String,
10384    workflow_stream_command_counter: u64,
10385    commands: Vec<Value>,
10386    local_activity_requests: Vec<local_activity::Request>,
10387    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
10388    message_stream_cursors: HashMap<String, u64>,
10389    message_stream_waits: HashMap<String, u64>,
10390}
10391
10392impl WorkflowState {
10393    #[cfg(test)]
10394    fn new(
10395        history: Vec<HistoryEvent>,
10396        task_queue: String,
10397        payload_codec: String,
10398        resume_signal: Option<ResumeSignal>,
10399    ) -> Result<Self> {
10400        Self::new_with_identity(
10401            history,
10402            None,
10403            None,
10404            task_queue,
10405            payload_codec,
10406            resume_signal,
10407        )
10408    }
10409
10410    fn new_with_identity(
10411        history: Vec<HistoryEvent>,
10412        workflow_id: Option<String>,
10413        run_id: Option<String>,
10414        task_queue: String,
10415        payload_codec: String,
10416        resume_signal: Option<ResumeSignal>,
10417    ) -> Result<Self> {
10418        Self::new_with_identity_and_scopes(
10419            history,
10420            workflow_id,
10421            run_id,
10422            task_queue,
10423            payload_codec,
10424            resume_signal,
10425            false,
10426        )
10427    }
10428
10429    fn new_with_identity_and_scopes(
10430        history: Vec<HistoryEvent>,
10431        workflow_id: Option<String>,
10432        run_id: Option<String>,
10433        task_queue: String,
10434        payload_codec: String,
10435        resume_signal: Option<ResumeSignal>,
10436        allow_cancellation_scope_authoring: bool,
10437    ) -> Result<Self> {
10438        Self::new_with_identity_and_scope_delivery(
10439            history,
10440            workflow_id,
10441            run_id,
10442            task_queue,
10443            payload_codec,
10444            resume_signal,
10445            allow_cancellation_scope_authoring,
10446            false,
10447        )
10448    }
10449
10450    fn new_with_identity_and_scope_delivery(
10451        history: Vec<HistoryEvent>,
10452        workflow_id: Option<String>,
10453        run_id: Option<String>,
10454        task_queue: String,
10455        payload_codec: String,
10456        resume_signal: Option<ResumeSignal>,
10457        allow_cancellation_scope_authoring: bool,
10458        allow_cancellation_scope_delivery: bool,
10459    ) -> Result<Self> {
10460        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10461            &history,
10462            allow_cancellation_scope_authoring,
10463            allow_cancellation_scope_delivery,
10464        )?;
10465        let scopes = if allow_cancellation_scope_authoring {
10466            cancellation_scope::CancellationScopeHistory::read(
10467                &history,
10468                run_id.as_deref().unwrap_or_default(),
10469            )?
10470        } else {
10471            cancellation_scope::CancellationScopeHistory::default()
10472        };
10473        let cancellation_history = CancellationHistory::from_events(
10474            &history,
10475            run_id.as_deref().unwrap_or_default(),
10476            None,
10477        )?;
10478        if allow_cancellation_scope_authoring
10479            && cancellation_history.request.is_some()
10480            && !allow_cancellation_scope_delivery
10481        {
10482            return Err(Error::CancellationScopeExecutionUnavailable);
10483        }
10484        let scope_delivery = if allow_cancellation_scope_delivery {
10485            Some(cancellation_scope_replay::ScopeReplay::read(
10486                &history,
10487                &scopes,
10488                run_id.as_deref().unwrap_or_default(),
10489                workflow_id.as_deref().unwrap_or_default(),
10490            )?)
10491        } else {
10492            None
10493        };
10494        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
10495            &history,
10496            &payload_codec,
10497            WorkflowIdentity {
10498                workflow_id: workflow_id.clone(),
10499                run_id: run_id.clone(),
10500            },
10501        )?)?;
10502        for (sequence, opening) in &scopes.openings {
10503            if recorded_commands
10504                .iter()
10505                .any(|command| command.sequence() == *sequence)
10506            {
10507                return Err(invalid_recorded_history(
10508                    "invalid_cancellation_scope_history",
10509                    *sequence,
10510                    "distinct authored scope opening",
10511                    "operation collision",
10512                    "scope opening collides with a command",
10513                ));
10514            }
10515            recorded_commands.push(RecordedCommand::CancellationScope {
10516                sequence: *sequence,
10517                scope_id: opening.scope_id.clone(),
10518                parent_scope_id: opening.parent_scope_id.clone(),
10519                shield_parent: opening.shield_parent,
10520            });
10521        }
10522        recorded_commands.sort_by_key(RecordedCommand::sequence);
10523        if let Some(replay) = &scope_delivery {
10524            replay.bind_commands(&mut recorded_commands)?;
10525        }
10526        let selection_markers = recorded_selection_markers(&history)?;
10527        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
10528        let recorded_continue_as_new = history
10529            .iter()
10530            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
10531            .collect::<Vec<_>>();
10532        if recorded_continue_as_new.len() > 1 {
10533            return Err(invalid_recorded_history(
10534                "duplicate_continue_as_new_transition",
10535                recorded_continue_as_new
10536                    .last()
10537                    .and_then(|event| durable_event_sequence(event))
10538                    .unwrap_or(0),
10539                "one WorkflowContinuedAsNew event",
10540                &format!(
10541                    "{} WorkflowContinuedAsNew events",
10542                    recorded_continue_as_new.len()
10543                ),
10544                "workflow history records one continue-as-new transition more than once",
10545            ));
10546        }
10547        let recorded_continue_as_new_sequence = recorded_continue_as_new
10548            .first()
10549            .map(|event| {
10550                durable_event_sequence(event).ok_or_else(|| {
10551                    Error::NonDeterministicReplay(ReplayFailure::new(
10552                        "continue_as_new_sequence_missing",
10553                        None,
10554                        Some("recorded transition sequence".to_string()),
10555                        Some("missing sequence".to_string()),
10556                        "WorkflowContinuedAsNew history is missing its recorded sequence",
10557                    ))
10558                })
10559            })
10560            .transpose()?;
10561        let mut message_stream_cursors = HashMap::new();
10562        for event in &history {
10563            if !matches!(
10564                event.event_type.as_str(),
10565                "SignalReceived" | "SignalApplied"
10566            ) || event.payload.get("signal_name").and_then(Value::as_str)
10567                != Some(MESSAGE_STREAM_SIGNAL)
10568            {
10569                continue;
10570            }
10571            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
10572            if arguments.len() != 1 {
10573                continue;
10574            }
10575            let envelope = arguments[0].clone().into_json()?;
10576            let Some(envelope) = envelope.as_object() else {
10577                continue;
10578            };
10579            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
10580            {
10581                continue;
10582            }
10583            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10584                continue;
10585            };
10586            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10587            else {
10588                continue;
10589            };
10590            let cursor = message_stream_cursors
10591                .entry(stream_name.to_string())
10592                .or_insert(0);
10593            *cursor = (*cursor).max(through_position);
10594        }
10595        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
10596        let cancel_requested = history.iter().any(|event| {
10597            matches!(
10598                event.event_type.as_str(),
10599                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
10600            )
10601        });
10602        let cancellation_clock = cancellation_history
10603            .request
10604            .as_ref()
10605            .and_then(|request| request.context.as_ref())
10606            .map(|_| {
10607                cancellation_replay_clock::ReplayClock::new(
10608                    &history,
10609                    &recorded_commands,
10610                    cancellation_history.delivery_index,
10611                )
10612            })
10613            .or_else(|| {
10614                scope_delivery.as_ref().map(|_| {
10615                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
10616                })
10617            });
10618        Ok(Self {
10619            workflow_command_identity: String::new(),
10620            workflow_stream_command_counter: 0,
10621            workflow_id,
10622            run_id,
10623            task_queue,
10624            payload_codec,
10625            history_events: Arc::new(history),
10626            history_budget: WorkflowHistoryBudget {
10627                event_count,
10628                ..WorkflowHistoryBudget::default()
10629            },
10630            cancel_requested,
10631            cancellation_history,
10632            cancellation_consumed: false,
10633            cancellation_clock,
10634            cancellation_shield_depth: 0,
10635            cancellation_delivery_enabled: false,
10636            cancellation_delivery_intent: None,
10637            cancellation_delivery_command_count: 0,
10638            allow_cancellation_scope_authoring,
10639            cancellation_scope_opening: None,
10640            cancellation_scope_memberships: scopes.memberships,
10641            scope_delivery,
10642            resume_signal,
10643            recorded_commands,
10644            selection_markers,
10645            selection_marker_cursor: 0,
10646            cancelled_selection_members,
10647            recorded_continue_as_new_sequence,
10648            continue_as_new_consumed: false,
10649            command_cursor: 0,
10650            condition_wait_occurrence_counter: 0,
10651            matched_recorded_pending: false,
10652            version_markers: HashMap::new(),
10653            commands: Vec::new(),
10654            local_activity_requests: Vec::new(),
10655            message_stream_messages: HashMap::new(),
10656            message_stream_cursors,
10657            message_stream_waits: HashMap::new(),
10658        })
10659    }
10660}
10661
10662enum MessageStreamDelivery {
10663    Message(MessageStreamMessage),
10664    Cursor {
10665        stream_name: String,
10666        through_position: u64,
10667    },
10668}
10669
10670fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
10671    if arguments.len() != 1 {
10672        return Ok(None);
10673    }
10674    let envelope = arguments
10675        .into_iter()
10676        .next()
10677        .expect("one argument was checked");
10678    let Some(envelope) = envelope.as_object() else {
10679        return Ok(None);
10680    };
10681    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10682        return Ok(None);
10683    };
10684    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
10685        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10686        else {
10687            return Ok(None);
10688        };
10689        return Ok(Some(MessageStreamDelivery::Cursor {
10690            stream_name: stream_name.to_string(),
10691            through_position,
10692        }));
10693    }
10694    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
10695        return Ok(None);
10696    }
10697    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
10698        return Ok(None);
10699    };
10700    let Some(position) = envelope
10701        .get("position")
10702        .and_then(Value::as_u64)
10703        .filter(|value| *value > 0)
10704    else {
10705        return Ok(None);
10706    };
10707    let Some(payload_envelope) = envelope.get("payload_envelope") else {
10708        return Ok(None);
10709    };
10710    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
10711    else {
10712        return Ok(None);
10713    };
10714    let decoded = decode_avro_value(&payload_envelope)?;
10715    let AvroValue::Array(values) = decoded else {
10716        return Ok(None);
10717    };
10718    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
10719        stream_name: stream_name.to_string(),
10720        message_id: message_id.to_string(),
10721        position,
10722        arguments: values,
10723    })))
10724}
10725
10726#[derive(Clone, Debug)]
10727enum RecordedCommand {
10728    CancellationScope {
10729        sequence: u64,
10730        scope_id: String,
10731        parent_scope_id: String,
10732        shield_parent: bool,
10733    },
10734    CancellationGroup {
10735        sequence: u64,
10736        span: u64,
10737        original: Vec<RecordedCommand>,
10738    },
10739    CancellationBoundary {
10740        sequence: u64,
10741        call_kind: CancellationCallKind,
10742        original: Option<Box<RecordedCommand>>,
10743    },
10744    Activity {
10745        sequence: u64,
10746        activity_type: Option<String>,
10747        cancellation_policy: String,
10748        options: Option<RecordedActivityOptions>,
10749        outcome: Option<ActivityOutcome>,
10750        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10751    },
10752    Timer {
10753        sequence: u64,
10754        delay_seconds: u64,
10755        fired: bool,
10756        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10757    },
10758    ChildWorkflow {
10759        sequence: u64,
10760        workflow_type: Option<String>,
10761        policies: RecordedChildPolicies,
10762        outcome: Option<ChildWorkflowOutcome>,
10763        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10764    },
10765    SignalWait {
10766        sequence: u64,
10767        signal_name: String,
10768        value: Option<Vec<AvroValue>>,
10769        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10770    },
10771    ConditionWait {
10772        sequence: u64,
10773        occurrence_id: String,
10774        condition_key: Option<String>,
10775        predicate_identity: String,
10776        timeout_seconds: Option<u64>,
10777        result: Option<ConditionWaitResult>,
10778        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
10779    },
10780    SearchAttributes {
10781        sequence: u64,
10782        attributes: Value,
10783        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
10784    },
10785    SideEffect {
10786        sequence: u64,
10787        value: AvroValue,
10788    },
10789    VersionMarker {
10790        sequence: u64,
10791        change_id: String,
10792        version: i32,
10793    },
10794    Memo {
10795        sequence: u64,
10796        entries: AvroValue,
10797    },
10798}
10799
10800#[derive(Clone, Debug, PartialEq, Eq)]
10801struct SelectionMarker {
10802    selection_group_id: String,
10803    selection_group_base_sequence: u64,
10804    selection_group_size: usize,
10805    member_key: SelectionKey,
10806    member_index: usize,
10807    member_base_sequence: u64,
10808    member_size: usize,
10809    operation_kind: String,
10810    operation_identity: String,
10811    outcome: String,
10812    resolution_event_id: String,
10813    resolution_event_type: String,
10814}
10815
10816#[derive(Clone, Debug, PartialEq, Eq)]
10817struct SelectionCancellation {
10818    selection_group_id: String,
10819    member_key: SelectionKey,
10820    member_index: usize,
10821    member_base_sequence: u64,
10822    member_size: usize,
10823    operation_kind: String,
10824    operation_identity: String,
10825}
10826
10827fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
10828    let mut markers: Vec<SelectionMarker> = Vec::new();
10829    for event in events
10830        .iter()
10831        .filter(|event| event.event_type == "SelectionResolved")
10832    {
10833        let payload = &event.payload;
10834        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
10835        let group_size = required_selection_usize(payload, "selection_group_size")?;
10836        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
10837        let member_size = required_selection_usize(payload, "member_size")?;
10838        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
10839        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
10840            invalid_recorded_history(
10841                "selection_marker_invalid",
10842                base_sequence,
10843                "non-empty selection_group_id",
10844                &payload.to_string(),
10845                "selection winner history is missing its durable group identity",
10846            )
10847        })?;
10848        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
10849        if group_id != expected_group_id {
10850            return Err(invalid_recorded_history(
10851                "selection_marker_invalid",
10852                base_sequence,
10853                &expected_group_id,
10854                &group_id,
10855                "selection winner history contains an incompatible group identity",
10856            ));
10857        }
10858        let group_end = base_sequence
10859            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
10860            .unwrap_or(u64::MAX);
10861        let member_end = member_base_sequence
10862            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
10863            .unwrap_or(u64::MAX);
10864        if member_index >= group_size
10865            || member_base_sequence < base_sequence
10866            || member_end > group_end
10867        {
10868            return Err(invalid_recorded_history(
10869                "selection_marker_invalid",
10870                base_sequence,
10871                "winner member within selection group bounds",
10872                &payload.to_string(),
10873                "selection winner history contains an invalid member range",
10874            ));
10875        }
10876        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
10877            invalid_recorded_history(
10878                "selection_marker_invalid",
10879                base_sequence,
10880                "selection operation kind",
10881                &payload.to_string(),
10882                "selection winner history is missing its operation kind",
10883            )
10884        })?;
10885        if !matches!(
10886            operation_kind.as_str(),
10887            "activity" | "child" | "timer" | "signal" | "condition" | "group"
10888        ) {
10889            return Err(invalid_recorded_history(
10890                "selection_marker_invalid",
10891                base_sequence,
10892                "activity, child, timer, signal, condition, or group",
10893                &operation_kind,
10894                "selection winner history contains an unsupported operation kind",
10895            ));
10896        }
10897        let operation_identity =
10898            payload_string(payload, "operation_identity").ok_or_else(|| {
10899                invalid_recorded_history(
10900                    "selection_marker_invalid",
10901                    base_sequence,
10902                    "non-empty operation identity",
10903                    &payload.to_string(),
10904                    "selection winner history is missing its durable operation identity",
10905                )
10906            })?;
10907        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
10908            invalid_recorded_history(
10909                "selection_marker_invalid",
10910                base_sequence,
10911                "completed or failed selection outcome",
10912                &payload.to_string(),
10913                "selection winner history is missing its outcome",
10914            )
10915        })?;
10916        if !matches!(outcome.as_str(), "completed" | "failed") {
10917            return Err(invalid_recorded_history(
10918                "selection_marker_invalid",
10919                base_sequence,
10920                "completed or failed selection outcome",
10921                &outcome,
10922                "selection winner history contains an unsupported outcome",
10923            ));
10924        }
10925        let marker = SelectionMarker {
10926            selection_group_id: group_id,
10927            selection_group_base_sequence: base_sequence,
10928            selection_group_size: group_size,
10929            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
10930            member_index,
10931            member_base_sequence,
10932            member_size,
10933            operation_kind,
10934            operation_identity,
10935            outcome,
10936            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
10937                || {
10938                    invalid_recorded_history(
10939                        "selection_marker_invalid",
10940                        base_sequence,
10941                        "durable resolution_event_id",
10942                        &payload.to_string(),
10943                        "selection winner history is missing its terminal event identity",
10944                    )
10945                },
10946            )?,
10947            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
10948                || {
10949                    invalid_recorded_history(
10950                        "selection_marker_invalid",
10951                        base_sequence,
10952                        "durable resolution_event_type",
10953                        &payload.to_string(),
10954                        "selection winner history is missing its terminal event type",
10955                    )
10956                },
10957            )?,
10958        };
10959        if let Some(existing) = markers
10960            .iter()
10961            .find(|existing| existing.selection_group_id == marker.selection_group_id)
10962        {
10963            if existing != &marker {
10964                return Err(invalid_recorded_history(
10965                    "selection_marker_conflict",
10966                    base_sequence,
10967                    &format!("one winner for {}", marker.selection_group_id),
10968                    &payload.to_string(),
10969                    "selection history records conflicting winners for one durable group",
10970                ));
10971            }
10972            continue;
10973        }
10974        markers.push(marker);
10975    }
10976    Ok(markers)
10977}
10978
10979fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
10980    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
10981    for event in events
10982        .iter()
10983        .filter(|event| event.event_type == "SelectionOperationCancelled")
10984    {
10985        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
10986            invalid_recorded_history(
10987                "selection_cancellation_invalid",
10988                0,
10989                "non-empty selection_group_id",
10990                &event.payload.to_string(),
10991                "selection cancellation history is missing its group identity",
10992            )
10993        })?;
10994        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
10995        let marker = SelectionCancellation {
10996            selection_group_id: group_id,
10997            member_key: selection_key_from_value(
10998                event.payload.get("member_key"),
10999                member_base_sequence,
11000            )?,
11001            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
11002            member_base_sequence,
11003            member_size: required_selection_usize(&event.payload, "member_size")?,
11004            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
11005                invalid_recorded_history(
11006                    "selection_cancellation_invalid",
11007                    member_base_sequence,
11008                    "selection operation kind",
11009                    &event.payload.to_string(),
11010                    "selection cancellation is missing its operation kind",
11011                )
11012            })?,
11013            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
11014                || {
11015                    invalid_recorded_history(
11016                        "selection_cancellation_invalid",
11017                        member_base_sequence,
11018                        "selection operation identity",
11019                        &event.payload.to_string(),
11020                        "selection cancellation is missing its operation identity",
11021                    )
11022                },
11023            )?,
11024        };
11025        if let Some(existing) = cancelled.iter().find(|recorded| {
11026            recorded.selection_group_id == marker.selection_group_id
11027                && recorded.member_base_sequence == marker.member_base_sequence
11028        }) {
11029            if existing != &marker {
11030                return Err(invalid_recorded_history(
11031                    "selection_cancellation_conflict",
11032                    member_base_sequence,
11033                    "one stable SelectionOperationCancelled marker",
11034                    &event.payload.to_string(),
11035                    "selection cancellation history contains conflicting member metadata",
11036                ));
11037            }
11038        } else {
11039            cancelled.push(marker);
11040        }
11041    }
11042    Ok(cancelled)
11043}
11044
11045fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
11046    payload
11047        .get(field)
11048        .and_then(value_as_u64)
11049        .filter(|value| *value > 0)
11050        .ok_or_else(|| {
11051            invalid_recorded_history(
11052                "selection_marker_invalid",
11053                0,
11054                &format!("positive integer {field}"),
11055                &payload.to_string(),
11056                "selection history contains invalid durable identity metadata",
11057            )
11058        })
11059}
11060
11061fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
11062    required_selection_usize_allow_zero(payload, field).and_then(|value| {
11063        if value > 0 {
11064            Ok(value)
11065        } else {
11066            Err(invalid_recorded_history(
11067                "selection_marker_invalid",
11068                0,
11069                &format!("positive integer {field}"),
11070                &payload.to_string(),
11071                "selection history contains invalid durable identity metadata",
11072            ))
11073        }
11074    })
11075}
11076
11077fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
11078    payload
11079        .get(field)
11080        .and_then(value_as_u64)
11081        .and_then(|value| usize::try_from(value).ok())
11082        .ok_or_else(|| {
11083            invalid_recorded_history(
11084                "selection_marker_invalid",
11085                0,
11086                &format!("non-negative integer {field}"),
11087                &payload.to_string(),
11088                "selection history contains invalid durable identity metadata",
11089            )
11090        })
11091}
11092
11093#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11094struct RecordedActivityOptions {
11095    task_queue: RecordedSnapshotValue<Option<String>>,
11096    execution_mode: RecordedSnapshotValue<Option<String>>,
11097    retry_policy: ActivityRetrySnapshot,
11098    worker_session: Option<Value>,
11099}
11100
11101#[derive(Clone, Debug)]
11102struct RecordedChildPolicies {
11103    parent_close_policy: String,
11104    cancellation_policy: String,
11105}
11106
11107fn recorded_activity_cancellation_policy(
11108    events: &[&HistoryEvent],
11109    sequence: u64,
11110) -> Result<String> {
11111    let mut policy: Option<String> = None;
11112    for event in events.iter().filter(|event| {
11113        matches!(
11114            event.event_type.as_str(),
11115            "ActivityScheduled"
11116                | "ActivityStarted"
11117                | "ActivityCompleted"
11118                | "ActivityFailed"
11119                | "ActivityTimedOut"
11120                | "ActivityCancelled"
11121        )
11122    }) {
11123        for source in [Some(&event.payload), event.payload.get("activity")]
11124            .into_iter()
11125            .flatten()
11126        {
11127            let Some(value) = source.get("cancellation_policy") else {
11128                continue;
11129            };
11130            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11131                value.as_str()
11132            else {
11133                return Err(invalid_recorded_history(
11134                    "invalid_activity_cancellation_policy_history",
11135                    sequence,
11136                    "supported Activity cancellation policy",
11137                    &value.to_string(),
11138                    "Activity history contains an invalid cancellation policy",
11139                ));
11140            };
11141            if let Some(previous) = policy.as_deref() {
11142                if previous != incoming {
11143                    return Err(invalid_recorded_history(
11144                        "activity_cancellation_policy_history_conflict",
11145                        sequence,
11146                        previous,
11147                        incoming,
11148                        "Activity cancellation policy changed between history events",
11149                    ));
11150                }
11151            }
11152            policy = Some(incoming.to_string());
11153        }
11154        policy.get_or_insert_with(|| "try_cancel".to_string());
11155    }
11156    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11157}
11158
11159fn recorded_child_policy_value<'a>(
11160    payload: &'a Value,
11161    field: &str,
11162    sequence: u64,
11163) -> Result<Option<&'a str>> {
11164    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11165        return Ok(None);
11166    };
11167    let valid = match (field, value.as_str()) {
11168        (
11169            "parent_close_policy",
11170            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11171        ) => true,
11172        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11173            true
11174        }
11175        _ => false,
11176    };
11177    if !valid {
11178        return Err(invalid_recorded_history(
11179            "invalid_child_workflow_policy_history",
11180            sequence,
11181            "supported child workflow policy",
11182            &value.to_string(),
11183            "child workflow history contains an invalid policy",
11184        ));
11185    }
11186    Ok(value.as_str())
11187}
11188
11189fn recorded_child_policies(
11190    events: &[&HistoryEvent],
11191    scheduled: &HistoryEvent,
11192    sequence: u64,
11193) -> Result<RecordedChildPolicies> {
11194    let parent_close_policy =
11195        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11196            .unwrap_or("abandon")
11197            .to_string();
11198    let cancellation_policy =
11199        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11200            .unwrap_or("abandon")
11201            .to_string();
11202    for event in events {
11203        for (field, expected) in [
11204            ("parent_close_policy", parent_close_policy.as_str()),
11205            ("cancellation_policy", cancellation_policy.as_str()),
11206        ] {
11207            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11208                if actual != expected {
11209                    return Err(invalid_recorded_history(
11210                        "child_workflow_policy_history_conflict",
11211                        sequence,
11212                        expected,
11213                        actual,
11214                        "child workflow policy changed between history events",
11215                    ));
11216                }
11217            }
11218        }
11219    }
11220    Ok(RecordedChildPolicies {
11221        parent_close_policy,
11222        cancellation_policy,
11223    })
11224}
11225
11226fn ensure_child_policies_match(
11227    sequence: u64,
11228    recorded: &RecordedChildPolicies,
11229    current: &ChildWorkflowOptions,
11230) -> Result<()> {
11231    for (field, expected, actual) in [
11232        (
11233            "parent_close_policy",
11234            recorded.parent_close_policy.as_str(),
11235            current.parent_close_policy.as_str(),
11236        ),
11237        (
11238            "cancellation_policy",
11239            recorded.cancellation_policy.as_str(),
11240            current.cancellation_policy.as_str(),
11241        ),
11242    ] {
11243        if expected != actual {
11244            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11245                "child_workflow_policy_changed",
11246                Some(sequence),
11247                Some(expected.to_string()),
11248                Some(actual.to_string()),
11249                format!("child workflow {field} changed during replay"),
11250            )));
11251        }
11252    }
11253    Ok(())
11254}
11255
11256#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11257enum RecordedSnapshotValue<T> {
11258    /// Older history did not persist this field, so it cannot constrain replay.
11259    Unknown,
11260    Known(T),
11261}
11262
11263impl<T: PartialEq> RecordedSnapshotValue<T> {
11264    fn matches_current(&self, current: &Self) -> bool {
11265        match self {
11266            Self::Unknown => true,
11267            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11268        }
11269    }
11270}
11271
11272#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11273struct ActivityRetrySnapshot {
11274    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11275    max_attempts: RecordedSnapshotValue<Option<u64>>,
11276    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11277    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11278    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11279    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11280    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11281    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11282}
11283
11284impl ActivityRetrySnapshot {
11285    fn matches_current(&self, current: &Self) -> bool {
11286        self.snapshot_version
11287            .matches_current(&current.snapshot_version)
11288            && self.max_attempts.matches_current(&current.max_attempts)
11289            && self
11290                .backoff_seconds
11291                .matches_current(&current.backoff_seconds)
11292            && self
11293                .start_to_close_timeout
11294                .matches_current(&current.start_to_close_timeout)
11295            && self
11296                .schedule_to_start_timeout
11297                .matches_current(&current.schedule_to_start_timeout)
11298            && self
11299                .schedule_to_close_timeout
11300                .matches_current(&current.schedule_to_close_timeout)
11301            && self
11302                .heartbeat_timeout
11303                .matches_current(&current.heartbeat_timeout)
11304            && self
11305                .non_retryable_error_types
11306                .matches_current(&current.non_retryable_error_types)
11307    }
11308}
11309
11310fn recorded_optional_u64(
11311    object: Option<&serde_json::Map<String, Value>>,
11312    field: &str,
11313) -> RecordedSnapshotValue<Option<u64>> {
11314    match object.and_then(|object| object.get(field)) {
11315        None => RecordedSnapshotValue::Unknown,
11316        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11317        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11318    }
11319}
11320
11321fn recorded_optional_string(
11322    object: &serde_json::Map<String, Value>,
11323    field: &str,
11324) -> RecordedSnapshotValue<Option<String>> {
11325    match object.get(field) {
11326        None => RecordedSnapshotValue::Unknown,
11327        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11328        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11329    }
11330}
11331
11332fn recorded_activity_execution_mode(
11333    events: &[&HistoryEvent],
11334    sequence: u64,
11335) -> Result<RecordedSnapshotValue<Option<String>>> {
11336    let mut recorded = RecordedSnapshotValue::Unknown;
11337    for event in events {
11338        for object in [
11339            event.payload.as_object(),
11340            event.payload.get("activity").and_then(Value::as_object),
11341        ]
11342        .into_iter()
11343        .flatten()
11344        {
11345            let mode = match object.get("execution_mode") {
11346                None => None,
11347                Some(Value::Null) => Some(None),
11348                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11349                Some(_) => {
11350                    return Err(invalid_recorded_history(
11351                        "activity_execution_mode_invalid",
11352                        sequence,
11353                        "null or a non-empty execution mode",
11354                        "invalid execution_mode",
11355                        "activity history contains an invalid execution mode",
11356                    ))
11357                }
11358            };
11359            let legacy_mode = match object.get("local_activity") {
11360                None => None,
11361                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11362                Some(_) => {
11363                    return Err(invalid_recorded_history(
11364                        "activity_execution_mode_invalid",
11365                        sequence,
11366                        "boolean local_activity",
11367                        "invalid local_activity",
11368                        "activity history contains an invalid local-activity marker",
11369                    ))
11370                }
11371            };
11372            for mode in [mode, legacy_mode].into_iter().flatten() {
11373                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
11374                {
11375                    return Err(invalid_recorded_history(
11376                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
11377                        "activity lifecycle events at one workflow sequence disagree on execution mode",
11378                    ));
11379                }
11380                recorded = RecordedSnapshotValue::Known(mode);
11381            }
11382        }
11383    }
11384    Ok(recorded)
11385}
11386
11387fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
11388    let policy = policy.and_then(Value::as_object);
11389    let backoff_seconds = policy
11390        .and_then(|policy| policy.get("backoff_seconds"))
11391        .and_then(Value::as_array)
11392        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11393        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
11394    let mut non_retryable_error_types = Vec::new();
11395    for error_type in policy
11396        .and_then(|policy| policy.get("non_retryable_error_types"))
11397        .and_then(Value::as_array)
11398        .into_iter()
11399        .flatten()
11400        .filter_map(Value::as_str)
11401        .map(str::trim)
11402        .filter(|error_type| !error_type.is_empty())
11403    {
11404        if !non_retryable_error_types
11405            .iter()
11406            .any(|recorded| recorded == error_type)
11407        {
11408            non_retryable_error_types.push(error_type.to_string());
11409        }
11410    }
11411
11412    ActivityRetrySnapshot {
11413        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
11414        max_attempts: recorded_optional_u64(policy, "max_attempts"),
11415        backoff_seconds,
11416        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
11417        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
11418        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
11419        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
11420        non_retryable_error_types: if policy
11421            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
11422        {
11423            RecordedSnapshotValue::Known(non_retryable_error_types)
11424        } else {
11425            RecordedSnapshotValue::Unknown
11426        },
11427    }
11428}
11429
11430fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
11431    let policy = options.retry_policy.as_ref();
11432    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
11433        Some(Value::Null) => None,
11434        Some(value) => value_as_u64(value),
11435        None => Some(1),
11436    };
11437    let backoff_seconds = policy
11438        .and_then(|policy| policy.get("backoff_seconds"))
11439        .and_then(Value::as_array)
11440        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11441        .unwrap_or_default();
11442    let non_retryable_error_types = policy
11443        .and_then(|policy| policy.get("non_retryable_error_types"))
11444        .and_then(Value::as_array)
11445        .into_iter()
11446        .flatten()
11447        .filter_map(Value::as_str)
11448        .map(str::to_string)
11449        .collect();
11450
11451    ActivityRetrySnapshot {
11452        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
11453        max_attempts: RecordedSnapshotValue::Known(max_attempts),
11454        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
11455        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
11456        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
11457        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
11458        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
11459        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
11460    }
11461}
11462
11463fn activity_options_description(options: &RecordedActivityOptions) -> String {
11464    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
11465}
11466
11467impl RecordedCommand {
11468    fn sequence(&self) -> u64 {
11469        match self {
11470            Self::CancellationGroup { sequence, .. }
11471            | Self::CancellationScope { sequence, .. }
11472            | Self::CancellationBoundary { sequence, .. }
11473            | Self::Activity { sequence, .. }
11474            | Self::Timer { sequence, .. }
11475            | Self::ChildWorkflow { sequence, .. }
11476            | Self::SignalWait { sequence, .. }
11477            | Self::ConditionWait { sequence, .. }
11478            | Self::SearchAttributes { sequence, .. }
11479            | Self::SideEffect { sequence, .. }
11480            | Self::VersionMarker { sequence, .. }
11481            | Self::Memo { sequence, .. } => *sequence,
11482        }
11483    }
11484
11485    fn shape(&self) -> &'static str {
11486        match self {
11487            Self::CancellationScope { .. } => "cancellation scope",
11488            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
11489                "cooperative cancellation"
11490            }
11491            Self::Activity { .. } => "activity",
11492            Self::Timer { .. } => "timer",
11493            Self::ChildWorkflow { .. } => "child workflow",
11494            Self::SignalWait { .. } => "signal wait",
11495            Self::ConditionWait { .. } => "condition wait",
11496            Self::SearchAttributes { .. } => "search-attribute update",
11497            Self::SideEffect { .. } => "side effect",
11498            Self::VersionMarker { .. } => "version marker",
11499            Self::Memo { .. } => "memo upsert",
11500        }
11501    }
11502}
11503
11504fn ensure_version_supported(
11505    change_id: &str,
11506    version: i32,
11507    min_supported: i32,
11508    max_supported: i32,
11509    sequence: u64,
11510) -> Result<()> {
11511    if (min_supported..=max_supported).contains(&version) {
11512        return Ok(());
11513    }
11514    Err(Error::NonDeterministicReplay(ReplayFailure::new(
11515        "version_marker_incompatible_range",
11516        (sequence != 0).then_some(sequence),
11517        Some(format!("{min_supported}..={max_supported}")),
11518        Some(format!("{change_id}:{version}")),
11519        "recorded workflow version is outside the range supported by current code",
11520    )))
11521}
11522
11523#[derive(Clone, Debug)]
11524struct ResumeSignal {
11525    signal_name: String,
11526    arguments: Vec<AvroValue>,
11527}
11528
11529const MAX_PARALLEL_OPERATIONS: usize = 1000;
11530
11531fn parallel_group_prefix(kind: &str) -> &'static str {
11532    match kind {
11533        "activity" => "parallel-activities",
11534        "child" => "parallel-children",
11535        "timer" => "parallel-timers",
11536        _ => "parallel-calls",
11537    }
11538}
11539
11540fn parallel_group_entry(
11541    base_sequence: u64,
11542    size: usize,
11543    index: usize,
11544    kind: &str,
11545) -> ParallelGroupMetadata {
11546    ParallelGroupMetadata {
11547        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
11548        parallel_group_kind: kind.to_string(),
11549        parallel_group_base_sequence: base_sequence,
11550        parallel_group_size: size,
11551        parallel_group_index: index,
11552        parallel_group_mode: None,
11553        selection_member_key: None,
11554        selection_member_index: None,
11555        selection_member_base_sequence: None,
11556        selection_member_size: None,
11557        selection_member_kind: None,
11558    }
11559}
11560
11561struct SelectionMemberMetadata {
11562    key: SelectionKey,
11563    index: usize,
11564    base_sequence: u64,
11565    size: usize,
11566    kind: String,
11567}
11568
11569fn selection_group_entry(
11570    base_sequence: u64,
11571    size: usize,
11572    index: usize,
11573    kind: &str,
11574    member: &SelectionMemberMetadata,
11575) -> ParallelGroupMetadata {
11576    ParallelGroupMetadata {
11577        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
11578        parallel_group_kind: kind.to_string(),
11579        parallel_group_base_sequence: base_sequence,
11580        parallel_group_size: size,
11581        parallel_group_index: index,
11582        parallel_group_mode: Some("select".to_string()),
11583        selection_member_key: Some(member.key.clone()),
11584        selection_member_index: Some(member.index),
11585        selection_member_base_sequence: Some(member.base_sequence),
11586        selection_member_size: Some(member.size),
11587        selection_member_kind: Some(member.kind.clone()),
11588    }
11589}
11590
11591fn apply_parallel_group_path(
11592    command: &mut serde_json::Map<String, Value>,
11593    path: &[ParallelGroupMetadata],
11594) {
11595    let Some(inner) = path.last() else {
11596        return;
11597    };
11598    command.insert(
11599        "parallel_group_id".to_string(),
11600        json!(inner.parallel_group_id),
11601    );
11602    command.insert(
11603        "parallel_group_kind".to_string(),
11604        json!(inner.parallel_group_kind),
11605    );
11606    command.insert(
11607        "parallel_group_base_sequence".to_string(),
11608        json!(inner.parallel_group_base_sequence),
11609    );
11610    command.insert(
11611        "parallel_group_size".to_string(),
11612        json!(inner.parallel_group_size),
11613    );
11614    command.insert(
11615        "parallel_group_index".to_string(),
11616        json!(inner.parallel_group_index),
11617    );
11618    if let Some(mode) = &inner.parallel_group_mode {
11619        command.insert("parallel_group_mode".to_string(), json!(mode));
11620    }
11621    if let Some(key) = &inner.selection_member_key {
11622        command.insert("selection_member_key".to_string(), json!(key));
11623    }
11624    if let Some(index) = inner.selection_member_index {
11625        command.insert("selection_member_index".to_string(), json!(index));
11626    }
11627    if let Some(base_sequence) = inner.selection_member_base_sequence {
11628        command.insert(
11629            "selection_member_base_sequence".to_string(),
11630            json!(base_sequence),
11631        );
11632    }
11633    if let Some(size) = inner.selection_member_size {
11634        command.insert("selection_member_size".to_string(), json!(size));
11635    }
11636    if let Some(kind) = &inner.selection_member_kind {
11637        command.insert("selection_member_kind".to_string(), json!(kind));
11638    }
11639    command.insert("parallel_group_path".to_string(), json!(path));
11640}
11641
11642fn ensure_parallel_path_matches(
11643    sequence: u64,
11644    recorded: Option<&[ParallelGroupMetadata]>,
11645    expected: &[ParallelGroupMetadata],
11646) -> Result<()> {
11647    match (recorded, expected.is_empty()) {
11648        (None, true) => Ok(()),
11649        (Some(recorded), false) if recorded == expected => Ok(()),
11650        (None, false) => Err(invalid_recorded_history(
11651            "parallel_group_metadata_missing",
11652            sequence,
11653            &serde_json::to_string(expected).unwrap_or_default(),
11654            "<missing>",
11655            "recorded parallel member is missing its durable group path",
11656        )),
11657        (Some(recorded), true) => Err(invalid_recorded_history(
11658            "parallel_group_shape_mismatch",
11659            sequence,
11660            "sequential command",
11661            &serde_json::to_string(recorded).unwrap_or_default(),
11662            "recorded command belonged to a parallel group but current code schedules it sequentially",
11663        )),
11664        (Some(recorded), false) => Err(invalid_recorded_history(
11665            "parallel_group_shape_mismatch",
11666            sequence,
11667            &serde_json::to_string(recorded).unwrap_or_default(),
11668            &serde_json::to_string(expected).unwrap_or_default(),
11669            "recorded parallel-group identity or path changed during replay",
11670        )),
11671    }
11672}
11673
11674#[derive(Clone, Debug)]
11675enum ParallelShape {
11676    Leaf,
11677    Group(Vec<ParallelShape>),
11678}
11679
11680struct ParallelDescriptor {
11681    operation: ParallelOperation,
11682    offset: usize,
11683    member_path: Vec<usize>,
11684    group_path: Vec<ParallelGroupMetadata>,
11685}
11686
11687fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
11688    operations
11689        .iter()
11690        .map(|operation| match operation {
11691            ParallelOperation::Group(children) => parallel_leaf_count(children),
11692            _ => 1,
11693        })
11694        .sum()
11695}
11696
11697fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
11698    match operation {
11699        ParallelOperation::Activity { .. } => Some("activity"),
11700        ParallelOperation::ChildWorkflow { .. } => Some("child"),
11701        ParallelOperation::Timer(_) => Some("timer"),
11702        ParallelOperation::Signal(_) => Some("signal"),
11703        ParallelOperation::Condition { .. } => Some("condition"),
11704        ParallelOperation::Group(children) => parallel_group_kind(children),
11705    }
11706}
11707
11708fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
11709    let mut kind = None;
11710    for operation in operations {
11711        let Some(operation_kind) = parallel_operation_kind(operation) else {
11712            continue;
11713        };
11714        match kind {
11715            None => kind = Some(operation_kind),
11716            Some(current) if current == operation_kind => {}
11717            Some(_) => return Some("mixed"),
11718        }
11719    }
11720    kind
11721}
11722
11723fn validate_parallel_operations(
11724    operations: &[ParallelOperation],
11725    member_path: &mut Vec<usize>,
11726    root: bool,
11727) -> Result<()> {
11728    let leaves = parallel_leaf_count(operations);
11729    if leaves > MAX_PARALLEL_OPERATIONS {
11730        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11731            reason: "fan_out_limit_exceeded",
11732            member_path: member_path.clone(),
11733            message: format!(
11734                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
11735            ),
11736        }));
11737    }
11738    if !root && operations.is_empty() {
11739        return Err(Error::InvalidParallelGroup(ParallelGroupError {
11740            reason: "nested_group_empty",
11741            member_path: member_path.clone(),
11742            message: "a nested group must contain at least one durable leaf".to_string(),
11743        }));
11744    }
11745
11746    for (index, operation) in operations.iter().enumerate() {
11747        member_path.push(index);
11748        match operation {
11749            ParallelOperation::Activity {
11750                options, arguments, ..
11751            } => {
11752                options
11753                    .validate()
11754                    .map_err(|error| Error::InvalidActivityOptions(error))?;
11755                if let Err(error) = arguments {
11756                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11757                        reason: "arguments_invalid",
11758                        member_path: member_path.clone(),
11759                        message: error.to_string(),
11760                    }));
11761                }
11762            }
11763            ParallelOperation::ChildWorkflow {
11764                options, arguments, ..
11765            } => {
11766                validate_parallel_child_options(options)?;
11767                if let Err(error) = arguments {
11768                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11769                        reason: "arguments_invalid",
11770                        member_path: member_path.clone(),
11771                        message: error.to_string(),
11772                    }));
11773                }
11774            }
11775            ParallelOperation::Timer(duration)
11776                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
11777            {
11778                return Err(Error::TimerDurationOverflow);
11779            }
11780            ParallelOperation::Timer(_) => {}
11781            ParallelOperation::Signal(signal_name) => {
11782                validate_user_signal_name(signal_name)?;
11783                if signal_name.trim().is_empty() {
11784                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
11785                        reason: "signal_name_empty",
11786                        member_path: member_path.clone(),
11787                        message: "signal wait name must not be empty".to_string(),
11788                    }));
11789                }
11790            }
11791            ParallelOperation::Condition { options, .. } => {
11792                options.validate()?;
11793            }
11794            ParallelOperation::Group(children) => {
11795                validate_parallel_operations(children, member_path, false)?;
11796            }
11797        }
11798        member_path.pop();
11799    }
11800    Ok(())
11801}
11802
11803fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
11804    if options.task_queue.trim().is_empty() {
11805        return Err(Error::InvalidChildWorkflowOptions(
11806            "task_queue must not be empty".to_string(),
11807        ));
11808    }
11809    for (name, value) in [
11810        (
11811            "execution_timeout_seconds",
11812            options.execution_timeout_seconds,
11813        ),
11814        ("run_timeout_seconds", options.run_timeout_seconds),
11815    ] {
11816        if value == Some(0) {
11817            return Err(Error::InvalidChildWorkflowOptions(format!(
11818                "{name} must be at least 1"
11819            )));
11820        }
11821    }
11822    if options
11823        .retry_policy
11824        .as_ref()
11825        .is_some_and(|policy| policy.max_attempts == Some(0))
11826    {
11827        return Err(Error::InvalidChildWorkflowOptions(
11828            "retry_policy.max_attempts must be at least 1".to_string(),
11829        ));
11830    }
11831    Ok(())
11832}
11833
11834fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
11835    ParallelShape::Group(
11836        operations
11837            .iter()
11838            .map(|operation| match operation {
11839                ParallelOperation::Group(children) => parallel_shape(children),
11840                _ => ParallelShape::Leaf,
11841            })
11842            .collect(),
11843    )
11844}
11845
11846fn parallel_descriptors(
11847    operations: Vec<ParallelOperation>,
11848    base_sequence: u64,
11849) -> Result<Vec<ParallelDescriptor>> {
11850    let size = parallel_leaf_count(&operations);
11851    let kind = parallel_group_kind(&operations).unwrap_or("activity");
11852    let mut descriptors = Vec::with_capacity(size);
11853    let mut cursor = 0;
11854
11855    for (index, operation) in operations.into_iter().enumerate() {
11856        match operation {
11857            ParallelOperation::Group(children) => {
11858                let child_base = base_sequence
11859                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
11860                    .ok_or(Error::TimerDurationOverflow)?;
11861                for mut descriptor in parallel_descriptors(children, child_base)? {
11862                    let outer_index = cursor + descriptor.offset;
11863                    descriptor.group_path.insert(
11864                        0,
11865                        parallel_group_entry(base_sequence, size, outer_index, kind),
11866                    );
11867                    descriptor.member_path.insert(0, index);
11868                    descriptor.offset = outer_index;
11869                    descriptors.push(descriptor);
11870                }
11871                cursor = descriptors.len();
11872            }
11873            operation => {
11874                descriptors.push(ParallelDescriptor {
11875                    operation,
11876                    offset: cursor,
11877                    member_path: vec![index],
11878                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
11879                });
11880                cursor += 1;
11881            }
11882        }
11883    }
11884    Ok(descriptors)
11885}
11886
11887enum ParallelLeafCall {
11888    Activity(ActivityCall),
11889    ChildWorkflow(ChildWorkflowCall),
11890    Timer(TimerCall),
11891    Signal(SignalCall),
11892    Condition(ConditionWaitCall),
11893}
11894
11895fn parallel_leaf_call(
11896    ctx: &WorkflowContext,
11897    operation: ParallelOperation,
11898    parallel_group_path: Vec<ParallelGroupMetadata>,
11899) -> ParallelLeafCall {
11900    match operation {
11901        ParallelOperation::Activity {
11902            activity_type,
11903            options,
11904            arguments,
11905        } => ParallelLeafCall::Activity(ActivityCall {
11906            ctx: ctx.clone(),
11907            activity_type,
11908            options,
11909            worker_session: None,
11910            args: Some(arguments),
11911            scheduled: false,
11912            local: false,
11913            local_result: None,
11914            parallel_group_path,
11915        }),
11916        ParallelOperation::ChildWorkflow {
11917            workflow_type,
11918            options,
11919            arguments,
11920        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
11921            ctx: ctx.clone(),
11922            workflow_type,
11923            options,
11924            args: Some(arguments),
11925            scheduled: false,
11926            matched_pending: false,
11927            parallel_group_path,
11928        }),
11929        ParallelOperation::Timer(duration) => {
11930            let delay_seconds = duration
11931                .as_secs()
11932                .checked_add(u64::from(duration.subsec_nanos() > 0));
11933            ParallelLeafCall::Timer(TimerCall {
11934                ctx: ctx.clone(),
11935                delay_seconds,
11936                scheduled: false,
11937                matched_pending: false,
11938                parallel_group_path,
11939            })
11940        }
11941        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
11942            ctx: ctx.clone(),
11943            signal_name,
11944            runtime_reserved_allowed: false,
11945            opened_wait: false,
11946            matched_pending: false,
11947            parallel_group_path,
11948        }),
11949        ParallelOperation::Condition { options, predicate } => {
11950            ParallelLeafCall::Condition(ConditionWaitCall {
11951                ctx: ctx.clone(),
11952                options,
11953                predicate,
11954                occurrence_id: None,
11955                opened_wait: false,
11956                parallel_group_path,
11957            })
11958        }
11959        ParallelOperation::Group(_) => {
11960            unreachable!("parallel descriptors contain only durable leaves")
11961        }
11962    }
11963}
11964
11965impl ParallelLeafCall {
11966    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
11967        match self {
11968            Self::Activity(call) => Pin::new(call)
11969                .poll_avro_value(cx)
11970                .map_ok(ParallelAvroResult::Activity),
11971            Self::ChildWorkflow(call) => Pin::new(call)
11972                .poll_avro_value(cx)
11973                .map_ok(ParallelAvroResult::ChildWorkflow),
11974            Self::Timer(call) => Pin::new(call)
11975                .poll(cx)
11976                .map_ok(|()| ParallelAvroResult::Timer),
11977            Self::Signal(call) => Pin::new(call)
11978                .poll_avro_value(cx)
11979                .map_ok(ParallelAvroResult::Signal),
11980            Self::Condition(call) => Pin::new(call)
11981                .poll(cx)
11982                .map_ok(ParallelAvroResult::Condition),
11983        }
11984    }
11985}
11986
11987struct ParallelLeaf {
11988    call: ParallelLeafCall,
11989    sequence: u64,
11990    member_path: Vec<usize>,
11991    group_path: Vec<ParallelGroupMetadata>,
11992    result: Option<ParallelAvroResult>,
11993}
11994
11995/// Future returned by [`WorkflowContext::parallel`].
11996pub struct ParallelCall {
11997    ctx: WorkflowContext,
11998    operations: Option<Vec<ParallelOperation>>,
11999    shape: Option<ParallelShape>,
12000    leaves: Vec<ParallelLeaf>,
12001    pending_scope_delivery: bool,
12002    worker_session: Option<WorkerSessionOptions>,
12003}
12004
12005impl ParallelCall {
12006    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
12007        Self {
12008            ctx,
12009            operations: Some(operations),
12010            shape: None,
12011            leaves: Vec::new(),
12012            pending_scope_delivery: false,
12013            worker_session: None,
12014        }
12015    }
12016
12017    fn initialize(&mut self) -> Result<()> {
12018        if let Some(session) = &self.worker_session {
12019            session.to_wire()?;
12020        }
12021        let operations = self.operations.take().unwrap_or_default();
12022        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
12023        self.shape = Some(parallel_shape(&operations));
12024        if operations.is_empty() {
12025            return Ok(());
12026        }
12027
12028        let base_sequence = {
12029            let state = self
12030                .ctx
12031                .state
12032                .lock()
12033                .map_err(|_| Error::WorkflowStatePoisoned)?;
12034            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12035                recorded.sequence()
12036            } else {
12037                let last = state
12038                    .recorded_commands
12039                    .last()
12040                    .map(RecordedCommand::sequence)
12041                    .unwrap_or(0);
12042                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12043                    .and_then(|sequence| sequence.checked_add(1))
12044                    .ok_or_else(|| {
12045                        Error::InvalidParallelGroup(ParallelGroupError {
12046                            reason: "sequence_overflow",
12047                            member_path: Vec::new(),
12048                            message: "parallel group sequence identity overflowed u64".to_string(),
12049                        })
12050                    })?
12051            }
12052        };
12053
12054        let descriptors = parallel_descriptors(operations, base_sequence)?;
12055        {
12056            let mut state = self
12057                .ctx
12058                .state
12059                .lock()
12060                .map_err(|_| Error::WorkflowStatePoisoned)?;
12061            let cursor = state.command_cursor;
12062            self.ctx.validate_scope_membership(&mut state, cursor)?;
12063            if state.prepare_parallel_scope_cancellation(&descriptors)? {
12064                self.pending_scope_delivery = true;
12065                return Ok(());
12066            }
12067            state.expand_cancellation_group(&descriptors)?;
12068            state.prepare_group_cancellation(&descriptors)?;
12069        }
12070        self.leaves = descriptors
12071            .into_iter()
12072            .map(|descriptor| {
12073                let mut call = parallel_leaf_call(
12074                    &self.ctx,
12075                    descriptor.operation,
12076                    descriptor.group_path.clone(),
12077                );
12078                if let (Some(session), ParallelLeafCall::Activity(activity)) =
12079                    (&self.worker_session, &mut call)
12080                {
12081                    activity.worker_session = Some(session.clone());
12082                }
12083                ParallelLeaf {
12084                    call,
12085                    sequence: base_sequence + descriptor.offset as u64,
12086                    member_path: descriptor.member_path,
12087                    group_path: descriptor.group_path,
12088                    result: None,
12089                }
12090            })
12091            .collect();
12092        Ok(())
12093    }
12094
12095    fn poll_avro_value(
12096        mut self: Pin<&mut Self>,
12097        cx: &mut TaskContext<'_>,
12098    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
12099        if self.operations.is_some() {
12100            if let Err(error) = self.initialize() {
12101                return Poll::Ready(Err(error));
12102            }
12103        }
12104        if self.pending_scope_delivery {
12105            return Poll::Pending;
12106        }
12107        if self.leaves.is_empty() {
12108            return Poll::Ready(Ok(Vec::new()));
12109        }
12110
12111        let mut failures = Vec::new();
12112        let mut pending = false;
12113        for (index, leaf) in self.leaves.iter_mut().enumerate() {
12114            if leaf.result.is_some() {
12115                continue;
12116            }
12117            match leaf.call.poll_avro_value(cx) {
12118                Poll::Ready(Ok(result)) => leaf.result = Some(result),
12119                Poll::Ready(Err(error)) => failures.push((index, error)),
12120                Poll::Pending => pending = true,
12121            }
12122        }
12123
12124        if !failures.is_empty() {
12125            if let Some(position) = failures
12126                .iter()
12127                .position(|(_, error)| workflow_task_integrity_error(error))
12128            {
12129                return Poll::Ready(Err(failures.remove(position).1));
12130            }
12131            if self
12132                .ctx
12133                .state
12134                .lock()
12135                .map_err(|_| Error::WorkflowStatePoisoned)?
12136                .cancellation_delivery_intent
12137                .is_some()
12138            {
12139                return Poll::Pending;
12140            }
12141            if let Some(position) = failures
12142                .iter()
12143                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12144            {
12145                return Poll::Ready(Err(failures.remove(position).1));
12146            }
12147            failures.sort_by_key(|(index, _)| *index);
12148            let (failed_index, cause) = failures.remove(0);
12149            let failed = &self.leaves[failed_index];
12150            let completed = self
12151                .leaves
12152                .iter()
12153                .filter_map(|leaf| {
12154                    leaf.result
12155                        .clone()
12156                        .and_then(|result| result.into_json_result().ok())
12157                        .map(|result| ParallelCompletion {
12158                            member_path: leaf.member_path.clone(),
12159                            result,
12160                        })
12161                })
12162                .collect();
12163            let group_id = failed
12164                .group_path
12165                .first()
12166                .map(|entry| entry.parallel_group_id.clone())
12167                .unwrap_or_default();
12168            let sequences = self
12169                .leaves
12170                .iter()
12171                .map(|leaf| leaf.sequence)
12172                .collect::<Vec<_>>();
12173            self.ctx
12174                .state
12175                .lock()
12176                .map_err(|_| Error::WorkflowStatePoisoned)?
12177                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12178            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12179                group_id,
12180                member_path: failed.member_path.clone(),
12181                group_path: failed.group_path.clone(),
12182                completed,
12183                cause: Box::new(cause),
12184            })));
12185        }
12186        if pending
12187            || self
12188                .ctx
12189                .state
12190                .lock()
12191                .map_err(|_| Error::WorkflowStatePoisoned)?
12192                .cancellation_delivery_intent
12193                .is_some()
12194        {
12195            return Poll::Pending;
12196        }
12197
12198        let mut flat_results = self
12199            .leaves
12200            .iter_mut()
12201            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12202            .collect::<Vec<_>>()
12203            .into_iter();
12204        let results = parallel_results_for_shape(
12205            self.shape.as_ref().expect("initialized parallel shape"),
12206            &mut flat_results,
12207        );
12208        let sequences = self
12209            .leaves
12210            .iter()
12211            .map(|leaf| leaf.sequence)
12212            .collect::<Vec<_>>();
12213        self.ctx
12214            .state
12215            .lock()
12216            .map_err(|_| Error::WorkflowStatePoisoned)?
12217            .advance_cancellation_sequences(&sequences, None);
12218        Poll::Ready(Ok(match results {
12219            ParallelAvroResult::Group(results) => results,
12220            ParallelAvroResult::Activity(_)
12221            | ParallelAvroResult::ChildWorkflow(_)
12222            | ParallelAvroResult::Timer
12223            | ParallelAvroResult::Signal(_)
12224            | ParallelAvroResult::Condition(_) => {
12225                unreachable!("root parallel shape is a group")
12226            }
12227        }))
12228    }
12229}
12230
12231fn parallel_results_for_shape(
12232    shape: &ParallelShape,
12233    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12234) -> ParallelAvroResult {
12235    match shape {
12236        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12237        ParallelShape::Group(children) => ParallelAvroResult::Group(
12238            children
12239                .iter()
12240                .map(|child| parallel_results_for_shape(child, flat_results))
12241                .collect(),
12242        ),
12243    }
12244}
12245
12246impl Future for ParallelCall {
12247    type Output = Result<Vec<ParallelResult>>;
12248
12249    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12250        self.poll_avro_value(cx)
12251            .map_ok(|results| {
12252                results
12253                    .into_iter()
12254                    .map(ParallelAvroResult::into_json_result)
12255                    .collect::<Result<Vec<_>>>()
12256            })
12257            .map_ok(|result| result)
12258            .flatten_result()
12259    }
12260}
12261
12262#[derive(Clone, Debug)]
12263struct SelectionMemberPlan {
12264    key: SelectionKey,
12265    index: usize,
12266    base_sequence: u64,
12267    size: usize,
12268    kind: String,
12269    shape: ParallelShape,
12270    leaf_start: usize,
12271}
12272
12273fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12274    match operation {
12275        ParallelOperation::Activity { .. } => "activity",
12276        ParallelOperation::ChildWorkflow { .. } => "child",
12277        ParallelOperation::Timer(_) => "timer",
12278        ParallelOperation::Signal(_) => "signal",
12279        ParallelOperation::Condition { .. } => "condition",
12280        ParallelOperation::Group(_) => "group",
12281    }
12282}
12283
12284fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12285    match operation {
12286        ParallelOperation::Group(children) => parallel_shape(children),
12287        _ => ParallelShape::Leaf,
12288    }
12289}
12290
12291fn selection_descriptors(
12292    operations: Vec<(SelectionKey, ParallelOperation)>,
12293    base_sequence: u64,
12294) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12295    if operations.is_empty() {
12296        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12297            reason: "selection_empty",
12298            member_path: Vec::new(),
12299            message: "durable selection requires at least one operation".to_string(),
12300        }));
12301    }
12302    let operation_refs = operations
12303        .iter()
12304        .map(|(_, operation)| operation)
12305        .collect::<Vec<_>>();
12306    let total_size = operation_refs
12307        .iter()
12308        .map(|operation| match operation {
12309            ParallelOperation::Group(children) => parallel_leaf_count(children),
12310            _ => 1,
12311        })
12312        .sum::<usize>();
12313    if total_size > MAX_PARALLEL_OPERATIONS {
12314        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12315            reason: "fan_out_limit_exceeded",
12316            member_path: Vec::new(),
12317            message: format!(
12318                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12319            ),
12320        }));
12321    }
12322    let group_kind = {
12323        let mut kind = None;
12324        for operation in &operation_refs {
12325            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12326            match kind {
12327                None => kind = Some(operation_kind),
12328                Some(current) if current == operation_kind => {}
12329                Some(_) => {
12330                    kind = Some("mixed");
12331                    break;
12332                }
12333            }
12334        }
12335        kind.unwrap_or("mixed")
12336    };
12337
12338    let mut descriptors = Vec::with_capacity(total_size);
12339    let mut members = Vec::with_capacity(operations.len());
12340    let mut cursor = 0usize;
12341    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12342    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12343        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12344            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12345                reason: "selection_key_invalid",
12346                member_path: vec![member_index],
12347                message: "selection member keys must be non-empty strings or non-negative integers"
12348                    .to_string(),
12349            }));
12350        }
12351        if seen_keys.contains(&key) {
12352            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12353                reason: "selection_key_duplicate",
12354                member_path: vec![member_index],
12355                message: format!("selection member key {key:?} is duplicated"),
12356            }));
12357        }
12358        seen_keys.push(key.clone());
12359        let member_size = match &operation {
12360            ParallelOperation::Group(children) => parallel_leaf_count(children),
12361            _ => 1,
12362        };
12363        if member_size == 0 {
12364            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12365                reason: "selection_member_empty",
12366                member_path: vec![member_index],
12367                message: "a selection member must contain at least one durable leaf".to_string(),
12368            }));
12369        }
12370        let member_base = base_sequence
12371            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12372            .ok_or(Error::TimerDurationOverflow)?;
12373        let member_kind = selection_operation_kind(&operation).to_string();
12374        let member_shape = selection_operation_shape(&operation);
12375        let leaf_start = descriptors.len();
12376        match operation {
12377            ParallelOperation::Group(children) => {
12378                validate_parallel_operations(&children, &mut vec![member_index], false)?;
12379                for mut descriptor in parallel_descriptors(children, member_base)? {
12380                    let flat_index = cursor + descriptor.offset;
12381                    descriptor.group_path.insert(
12382                        0,
12383                        selection_group_entry(
12384                            base_sequence,
12385                            total_size,
12386                            flat_index,
12387                            group_kind,
12388                            &SelectionMemberMetadata {
12389                                key: key.clone(),
12390                                index: member_index,
12391                                base_sequence: member_base,
12392                                size: member_size,
12393                                kind: member_kind.clone(),
12394                            },
12395                        ),
12396                    );
12397                    descriptor.member_path.insert(0, member_index);
12398                    descriptor.offset = flat_index;
12399                    descriptors.push(descriptor);
12400                }
12401            }
12402            operation => {
12403                validate_parallel_operations(
12404                    std::slice::from_ref(&operation),
12405                    &mut Vec::new(),
12406                    true,
12407                )?;
12408                descriptors.push(ParallelDescriptor {
12409                    operation,
12410                    offset: cursor,
12411                    member_path: vec![member_index],
12412                    group_path: vec![selection_group_entry(
12413                        base_sequence,
12414                        total_size,
12415                        cursor,
12416                        group_kind,
12417                        &SelectionMemberMetadata {
12418                            key: key.clone(),
12419                            index: member_index,
12420                            base_sequence: member_base,
12421                            size: member_size,
12422                            kind: member_kind.clone(),
12423                        },
12424                    )],
12425                });
12426            }
12427        }
12428        members.push(SelectionMemberPlan {
12429            key,
12430            index: member_index,
12431            base_sequence: member_base,
12432            size: member_size,
12433            kind: member_kind,
12434            shape: member_shape,
12435            leaf_start,
12436        });
12437        cursor += member_size;
12438    }
12439    Ok((descriptors, members))
12440}
12441
12442struct SelectionLeaf {
12443    call: ParallelLeafCall,
12444    outcome: Option<Result<ParallelAvroResult>>,
12445}
12446
12447/// Stable reference to one member of a durable selection group.
12448#[derive(Clone)]
12449pub struct DurableOperationHandle {
12450    ctx: WorkflowContext,
12451    pub key: SelectionKey,
12452    pub index: usize,
12453    pub kind: String,
12454    pub identity: String,
12455    pub base_sequence: u64,
12456    pub size: usize,
12457    pub selection_group_id: String,
12458    shape: ParallelShape,
12459}
12460
12461impl std::fmt::Debug for DurableOperationHandle {
12462    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12463        formatter
12464            .debug_struct("DurableOperationHandle")
12465            .field("key", &self.key)
12466            .field("index", &self.index)
12467            .field("kind", &self.kind)
12468            .field("identity", &self.identity)
12469            .field("base_sequence", &self.base_sequence)
12470            .field("size", &self.size)
12471            .field("selection_group_id", &self.selection_group_id)
12472            .finish()
12473    }
12474}
12475
12476impl DurableOperationHandle {
12477    /// Await this member after another member has already won the selection.
12478    pub fn await_result(&self) -> DurableOperationAwaitCall {
12479        DurableOperationAwaitCall {
12480            handle: self.clone(),
12481        }
12482    }
12483
12484    /// Request cancellation without affecting siblings. The future resolves
12485    /// to unit; only `SelectionOperationCancelled` history proves cancellation
12486    /// beat a concurrently committed terminal result.
12487    pub fn cancel(&self) -> CancelDurableOperationCall {
12488        CancelDurableOperationCall {
12489            handle: self.clone(),
12490            emitted: false,
12491        }
12492    }
12493}
12494
12495/// The one winner committed for a durable selection group.
12496#[derive(Debug)]
12497pub struct SelectionResult {
12498    pub key: SelectionKey,
12499    pub index: usize,
12500    pub kind: String,
12501    pub identity: String,
12502    pub value: Option<ParallelResult>,
12503    pub failure: Option<Error>,
12504    pub winner: DurableOperationHandle,
12505    pub handles: Vec<DurableOperationHandle>,
12506}
12507
12508impl SelectionResult {
12509    pub fn succeeded(&self) -> bool {
12510        self.failure.is_none()
12511    }
12512
12513    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
12514        self.handles.iter().find(|handle| &handle.key == key)
12515    }
12516
12517    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
12518        self.handles
12519            .iter()
12520            .filter(|handle| handle.index != self.index)
12521            .collect()
12522    }
12523
12524    pub fn into_result(self) -> Result<ParallelResult> {
12525        match (self.value, self.failure) {
12526            (Some(value), None) => Ok(value),
12527            (_, Some(error)) => Err(error),
12528            _ => Err(Error::WorkerLoop(
12529                "selection result contained neither a value nor a failure".to_string(),
12530            )),
12531        }
12532    }
12533}
12534
12535/// Future returned by [`WorkflowContext::select`].
12536pub struct SelectCall {
12537    ctx: WorkflowContext,
12538    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
12539    members: Vec<SelectionMemberPlan>,
12540    leaves: Vec<SelectionLeaf>,
12541    group_id: Option<String>,
12542}
12543
12544impl SelectCall {
12545    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
12546        Self {
12547            ctx,
12548            operations: Some(operations),
12549            members: Vec::new(),
12550            leaves: Vec::new(),
12551            group_id: None,
12552        }
12553    }
12554
12555    fn initialize(&mut self) -> Result<()> {
12556        let operations = self.operations.take().unwrap_or_default();
12557        let base_sequence = {
12558            let state = self
12559                .ctx
12560                .state
12561                .lock()
12562                .map_err(|_| Error::WorkflowStatePoisoned)?;
12563            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
12564                state.recorded_commands.get(state.command_cursor)
12565            {
12566                *sequence
12567            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
12568            {
12569                marker.selection_group_base_sequence
12570            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12571                recorded.sequence()
12572            } else {
12573                let last = state
12574                    .recorded_commands
12575                    .last()
12576                    .map(RecordedCommand::sequence)
12577                    .unwrap_or(0);
12578                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12579                    .and_then(|sequence| sequence.checked_add(1))
12580                    .ok_or(Error::TimerDurationOverflow)?
12581            }
12582        };
12583        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
12584        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
12585        {
12586            let mut state = self
12587                .ctx
12588                .state
12589                .lock()
12590                .map_err(|_| Error::WorkflowStatePoisoned)?;
12591            state.expand_cancellation_group(&descriptors)?;
12592            state.prepare_group_cancellation(&descriptors)?;
12593        }
12594        self.leaves = descriptors
12595            .into_iter()
12596            .map(|descriptor| SelectionLeaf {
12597                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
12598                outcome: None,
12599            })
12600            .collect();
12601        self.members = members;
12602        self.group_id = Some(group_id);
12603        Ok(())
12604    }
12605}
12606
12607impl Future for SelectCall {
12608    type Output = Result<SelectionResult>;
12609
12610    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12611        if self.operations.is_some() {
12612            if let Err(error) = self.initialize() {
12613                return Poll::Ready(Err(error));
12614            }
12615        }
12616
12617        for leaf in &mut self.leaves {
12618            if leaf.outcome.is_some() {
12619                continue;
12620            }
12621            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
12622                if outcome
12623                    .as_ref()
12624                    .err()
12625                    .is_some_and(workflow_task_integrity_error)
12626                {
12627                    return Poll::Ready(outcome.map(|_| unreachable!()));
12628                }
12629                leaf.outcome = Some(outcome);
12630            }
12631        }
12632
12633        if self
12634            .ctx
12635            .state
12636            .lock()
12637            .map_err(|_| Error::WorkflowStatePoisoned)?
12638            .cancellation_delivery_intent
12639            .is_some()
12640        {
12641            return Poll::Pending;
12642        }
12643
12644        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
12645            matches!(
12646                leaf.outcome,
12647                Some(Err(Error::CooperativeCancellationRequested(_)))
12648            )
12649        }) {
12650            return Poll::Ready(
12651                leaf.outcome
12652                    .take()
12653                    .expect("matched cancellation")
12654                    .map(|_| unreachable!()),
12655            );
12656        }
12657
12658        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
12659        let selection_member_range = self
12660            .members
12661            .first()
12662            .map(|member| member.base_sequence)
12663            .zip(self.leaves.len().try_into().ok())
12664            .map(|(base_sequence, size): (u64, u64)| {
12665                base_sequence..base_sequence.saturating_add(size)
12666            });
12667        let marker = {
12668            let mut state = match self.ctx.state.lock() {
12669                Ok(state) => state,
12670                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12671            };
12672            let marker = state
12673                .selection_markers
12674                .get(state.selection_marker_cursor)
12675                .cloned();
12676            if marker.is_none()
12677                && all_members_terminal
12678                && selection_member_range.as_ref().is_some_and(|member_range| {
12679                    state
12680                        .recorded_commands
12681                        .iter()
12682                        .any(|command| member_range.contains(&command.sequence()))
12683                })
12684            {
12685                // Terminal member history can be committed before the server's
12686                // SelectionResolved marker becomes visible to this task. That
12687                // marker is the durable barrier the selection is still waiting
12688                // on, so an otherwise commandless replay remains legitimately
12689                // pending instead of failing as an untracked yield.
12690                state.matched_recorded_pending = true;
12691            }
12692            marker
12693        };
12694        let Some(marker) = marker else {
12695            return Poll::Pending;
12696        };
12697        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
12698            || marker.selection_group_size != self.leaves.len()
12699            || self.members.first().map(|member| member.base_sequence)
12700                != Some(marker.selection_group_base_sequence)
12701        {
12702            return Poll::Ready(Err(invalid_recorded_history(
12703                "selection_group_shape_mismatch",
12704                marker.selection_group_base_sequence,
12705                self.group_id
12706                    .as_deref()
12707                    .unwrap_or("initialized selection group"),
12708                &marker.selection_group_id,
12709                "recorded selection group differs from current workflow code",
12710            )));
12711        }
12712        let Some(member_position) = self.members.iter().position(|member| {
12713            member.key == marker.member_key
12714                && member.index == marker.member_index
12715                && member.base_sequence == marker.member_base_sequence
12716                && member.size == marker.member_size
12717                && member.kind == marker.operation_kind
12718        }) else {
12719            return Poll::Ready(Err(invalid_recorded_history(
12720                "selection_member_shape_mismatch",
12721                marker.member_base_sequence,
12722                "winner member matching current workflow code",
12723                &format!("{:?}", marker.member_key),
12724                "recorded selection winner differs from the authored member identity",
12725            )));
12726        };
12727        let member = self.members[member_position].clone();
12728        let (handles, resolution_sequence) = {
12729            let mut state = match self.ctx.state.lock() {
12730                Ok(state) => state,
12731                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
12732            };
12733            let identities = self
12734                .members
12735                .iter()
12736                .map(|candidate| {
12737                    selection_operation_identity(
12738                        &state,
12739                        &candidate.kind,
12740                        candidate.base_sequence,
12741                        candidate.size,
12742                    )
12743                })
12744                .collect::<Vec<_>>();
12745            if let Some((position, missing)) = identities
12746                .iter()
12747                .enumerate()
12748                .find(|(_, identity)| identity.is_empty())
12749                .map(|(position, identity)| (position, identity.clone()))
12750            {
12751                let candidate = &self.members[position];
12752                return Poll::Ready(Err(invalid_recorded_history(
12753                    "selection_operation_identity_missing",
12754                    candidate.base_sequence,
12755                    &format!(
12756                        "durable {} resource identity from scheduled/open history",
12757                        candidate.kind
12758                    ),
12759                    &missing,
12760                    "selection member history is missing its canonical durable identity",
12761                )));
12762            }
12763            let expected_winner_identity = &identities[member_position];
12764            let resolution_sequence = match validated_selection_resolution_sequence(
12765                &state,
12766                &marker,
12767                &member,
12768                expected_winner_identity,
12769            ) {
12770                Ok(sequence) => sequence,
12771                Err(error) => return Poll::Ready(Err(error)),
12772            };
12773            let handles = self
12774                .members
12775                .iter()
12776                .zip(identities)
12777                .map(|(member, identity)| DurableOperationHandle {
12778                    ctx: self.ctx.clone(),
12779                    key: member.key.clone(),
12780                    index: member.index,
12781                    kind: member.kind.clone(),
12782                    identity,
12783                    base_sequence: member.base_sequence,
12784                    size: member.size,
12785                    selection_group_id: marker.selection_group_id.clone(),
12786                    shape: member.shape.clone(),
12787                })
12788                .collect::<Vec<_>>();
12789            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
12790                return Poll::Ready(Err(error));
12791            }
12792            state.selection_marker_cursor += 1;
12793            (handles, resolution_sequence)
12794        };
12795
12796        let mut winner_failure = None;
12797        let mut flat_results = Vec::with_capacity(member.size);
12798        if marker.outcome == "failed" {
12799            let resolution_offset = match resolution_sequence
12800                .checked_sub(member.base_sequence)
12801                .and_then(|offset| usize::try_from(offset).ok())
12802            {
12803                Some(offset) if offset < member.size => offset,
12804                _ => {
12805                    return Poll::Ready(Err(invalid_recorded_history(
12806                        "selection_resolution_event_mismatch",
12807                        member.base_sequence,
12808                        "failure event within selected member bounds",
12809                        &resolution_sequence.to_string(),
12810                        "selection failure event is outside the authored member",
12811                    )))
12812                }
12813            };
12814            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
12815            match leaf.outcome.take() {
12816                Some(Err(error)) => winner_failure = Some(error),
12817                _ => {
12818                    return Poll::Ready(Err(invalid_recorded_history(
12819                        "selection_winner_outcome_mismatch",
12820                        member.base_sequence,
12821                        "exact failed terminal history referenced by SelectionResolved",
12822                        "missing or successful resolution event",
12823                        "selection winner marker disagrees with terminal operation history",
12824                    )))
12825                }
12826            }
12827        } else {
12828            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
12829                match leaf.outcome.take() {
12830                    Some(Ok(result)) => flat_results.push(result),
12831                    Some(Err(_)) => {
12832                        return Poll::Ready(Err(invalid_recorded_history(
12833                            "selection_winner_outcome_mismatch",
12834                            member.base_sequence,
12835                            "fully completed nested selection member",
12836                            "failed durable leaf",
12837                            "completed selection winner contains a failed leaf",
12838                        )))
12839                    }
12840                    None => {
12841                        return Poll::Ready(Err(invalid_recorded_history(
12842                            "selection_winner_unresolved",
12843                            member.base_sequence,
12844                            "terminal history for every completed winner leaf",
12845                            "pending member history",
12846                            "completed SelectionResolved member has an unfinished durable barrier",
12847                        )))
12848                    }
12849                }
12850            }
12851        }
12852        let value = if winner_failure.is_none() {
12853            let mut flat_results = flat_results.into_iter();
12854            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
12855            match value.into_json_result() {
12856                Ok(value) => Some(value),
12857                Err(error) => return Poll::Ready(Err(error)),
12858            }
12859        } else {
12860            None
12861        };
12862        let winner = handles[member_position].clone();
12863        self.ctx
12864            .state
12865            .lock()
12866            .map_err(|_| Error::WorkflowStatePoisoned)?
12867            .advance_cancellation_selection(&marker.selection_group_id);
12868        Poll::Ready(Ok(SelectionResult {
12869            key: winner.key.clone(),
12870            index: winner.index,
12871            kind: winner.kind.clone(),
12872            identity: winner.identity.clone(),
12873            value,
12874            failure: winner_failure,
12875            winner,
12876            handles,
12877        }))
12878    }
12879}
12880
12881fn selection_operation_identity(
12882    state: &WorkflowState,
12883    kind: &str,
12884    base_sequence: u64,
12885    size: usize,
12886) -> String {
12887    if kind == "group" {
12888        return format!("group:{base_sequence}:{size}");
12889    }
12890    let fields: &[&str] = match kind {
12891        "activity" => &["activity_execution_id"],
12892        "child" => &["child_workflow_run_id"],
12893        "timer" => &["timer_id"],
12894        "signal" => &["signal_wait_id"],
12895        "condition" => &["condition_wait_id"],
12896        _ => &[],
12897    };
12898    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
12899        for event in state
12900            .history_events
12901            .iter()
12902            .filter(|event| durable_event_sequence(event) == Some(sequence))
12903        {
12904            for field in fields {
12905                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
12906                    if !identity.is_empty() {
12907                        return identity.to_string();
12908                    }
12909                }
12910            }
12911        }
12912    }
12913    String::new()
12914}
12915
12916fn validated_selection_resolution_sequence(
12917    state: &WorkflowState,
12918    marker: &SelectionMarker,
12919    member: &SelectionMemberPlan,
12920    expected_identity: &str,
12921) -> Result<u64> {
12922    if expected_identity.is_empty() {
12923        return Err(invalid_recorded_history(
12924            "selection_operation_identity_missing",
12925            member.base_sequence,
12926            &format!(
12927                "durable {} resource identity from scheduled/open history",
12928                member.kind
12929            ),
12930            "missing operation identity",
12931            "selection member history is missing its canonical durable identity",
12932        ));
12933    }
12934    if marker.operation_identity != expected_identity {
12935        return Err(invalid_recorded_history(
12936            "selection_operation_identity_mismatch",
12937            member.base_sequence,
12938            expected_identity,
12939            &marker.operation_identity,
12940            "selection winner identity does not match durable scheduled/open history",
12941        ));
12942    }
12943
12944    let failure_types = [
12945        "ActivityFailed",
12946        "ActivityCancelled",
12947        "ActivityTimedOut",
12948        "ChildRunFailed",
12949        "ChildRunCancelled",
12950        "ChildRunTerminated",
12951    ];
12952    let success_types = [
12953        "ActivityCompleted",
12954        "ChildRunCompleted",
12955        "TimerFired",
12956        "SignalApplied",
12957        "ConditionWaitSatisfied",
12958        "ConditionWaitTimedOut",
12959    ];
12960    let terminal_types: &[&str] = if marker.outcome == "failed" {
12961        &failure_types
12962    } else {
12963        &success_types
12964    };
12965    let mut candidates = Vec::new();
12966    let member_commands = (member.base_sequence
12967        ..member.base_sequence.saturating_add(member.size as u64))
12968        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
12969        .map(|command| (command.sequence(), command))
12970        .collect::<BTreeMap<_, _>>();
12971    let mut resolved_conditions = BTreeSet::new();
12972    for event in state.history_events.iter() {
12973        let Some(sequence) = durable_event_sequence(event) else {
12974            continue;
12975        };
12976        let Some(command) = member_commands.get(&sequence) else {
12977            continue;
12978        };
12979        if !terminal_types.contains(&event.event_type.as_str()) {
12980            continue;
12981        }
12982        if matches!(command, RecordedCommand::ConditionWait { .. }) {
12983            if !matches!(
12984                event.event_type.as_str(),
12985                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
12986            ) && !(event.event_type == "TimerFired"
12987                && event.payload.get("timer_kind").and_then(Value::as_str)
12988                    == Some("condition_timeout"))
12989            {
12990                continue;
12991            }
12992            if !resolved_conditions.insert(sequence) {
12993                continue;
12994            }
12995        }
12996        let event_id = event
12997            .raw
12998            .get("id")
12999            .or_else(|| event.raw.get("event_id"))
13000            .and_then(Value::as_str)
13001            .filter(|value| !value.is_empty())
13002            .ok_or_else(|| {
13003                invalid_recorded_history(
13004                    "selection_resolution_event_id_missing",
13005                    member.base_sequence,
13006                    "terminal selection history with a durable event id",
13007                    &event.payload.to_string(),
13008                    "selection terminal history cannot be bound to its winner marker",
13009                )
13010            })?;
13011        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
13012    }
13013    let resolution = if marker.outcome == "failed" {
13014        candidates.first()
13015    } else {
13016        candidates.last()
13017    };
13018    let Some((event_id, event_type, sequence)) = resolution else {
13019        return Err(invalid_recorded_history(
13020            "selection_resolution_event_missing",
13021            member.base_sequence,
13022            "terminal history for the selected member",
13023            &format!("{:?}", marker.member_key),
13024            "selection winner marker has no matching durable terminal event",
13025        ));
13026    };
13027    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
13028        return Err(invalid_recorded_history(
13029            "selection_resolution_event_mismatch",
13030            member.base_sequence,
13031            &format!("{event_type}:{event_id}"),
13032            &format!(
13033                "{}:{}",
13034                marker.resolution_event_type, marker.resolution_event_id
13035            ),
13036            "selection winner marker does not reference the event that made its member terminal",
13037        ));
13038    }
13039    Ok(*sequence)
13040}
13041
13042fn selection_member_recorded_command(
13043    state: &WorkflowState,
13044    authored_sequence: u64,
13045) -> Option<&RecordedCommand> {
13046    let original = state
13047        .recorded_commands
13048        .iter()
13049        .find(|command| command.sequence() == authored_sequence)?;
13050    let RecordedCommand::ConditionWait {
13051        occurrence_id,
13052        parallel_group_path: Some(_),
13053        ..
13054    } = original
13055    else {
13056        return Some(original);
13057    };
13058    // Decoding proves each physical reopen has the same authored identity and
13059    // group path after a satisfied predecessor. Only its latest wait can make
13060    // this logical member terminal.
13061    state
13062        .recorded_commands
13063        .iter()
13064        .filter(|command| {
13065            matches!(command, RecordedCommand::ConditionWait {
13066                occurrence_id: candidate, ..
13067            } if candidate == occurrence_id)
13068        })
13069        .max_by_key(|command| command.sequence())
13070}
13071
13072fn recorded_selection_member_outcome(
13073    state: &WorkflowState,
13074    handle: &DurableOperationHandle,
13075) -> Result<Option<ParallelResult>> {
13076    for event in state.history_events.iter() {
13077        let Some(sequence) = durable_event_sequence(event) else {
13078            continue;
13079        };
13080        if sequence < handle.base_sequence
13081            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
13082            || !matches!(
13083                event.event_type.as_str(),
13084                "ActivityFailed"
13085                    | "ActivityCancelled"
13086                    | "ActivityTimedOut"
13087                    | "ChildRunFailed"
13088                    | "ChildRunCancelled"
13089                    | "ChildRunTerminated"
13090            )
13091        {
13092            continue;
13093        }
13094        let Some(command) = state
13095            .recorded_commands
13096            .iter()
13097            .find(|command| command.sequence() == sequence)
13098        else {
13099            continue;
13100        };
13101        match command {
13102            RecordedCommand::Activity {
13103                outcome: Some(Err(failure)),
13104                ..
13105            } => return Err(Error::ActivityFailed(failure.clone())),
13106            RecordedCommand::ChildWorkflow {
13107                outcome: Some(Err(failure)),
13108                ..
13109            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
13110            _ => {}
13111        }
13112    }
13113
13114    let mut results = Vec::with_capacity(handle.size);
13115    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13116        let Some(command) = selection_member_recorded_command(state, sequence) else {
13117            return Ok(None);
13118        };
13119        let result = match command {
13120            RecordedCommand::Activity { outcome, .. } => match outcome {
13121                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
13122                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
13123                None => return Ok(None),
13124            },
13125            RecordedCommand::Timer { fired, .. } => {
13126                if !fired {
13127                    return Ok(None);
13128                }
13129                ParallelAvroResult::Timer
13130            }
13131            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13132                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13133                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13134                None => return Ok(None),
13135            },
13136            RecordedCommand::SignalWait { value, .. } => match value {
13137                Some(value) => ParallelAvroResult::Signal(value.clone()),
13138                None => return Ok(None),
13139            },
13140            RecordedCommand::ConditionWait { result, .. } => match result {
13141                Some(result) => ParallelAvroResult::Condition(*result),
13142                None => return Ok(None),
13143            },
13144            other => {
13145                return Err(command_mismatch(
13146                    other,
13147                    format!("selected {} member", handle.kind),
13148                ))
13149            }
13150        };
13151        results.push(result);
13152    }
13153    let mut results = results.into_iter();
13154    parallel_results_for_shape(&handle.shape, &mut results)
13155        .into_json_result()
13156        .map(Some)
13157}
13158
13159fn recorded_selection_member_is_terminal(
13160    state: &WorkflowState,
13161    handle: &DurableOperationHandle,
13162) -> bool {
13163    let mut completed = 0usize;
13164    let mut all_completed = true;
13165    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13166        let Some(command) = selection_member_recorded_command(state, sequence) else {
13167            all_completed = false;
13168            continue;
13169        };
13170        let terminal = match command {
13171            RecordedCommand::Activity {
13172                outcome: Some(Err(_)),
13173                ..
13174            }
13175            | RecordedCommand::ChildWorkflow {
13176                outcome: Some(Err(_)),
13177                ..
13178            } => return true,
13179            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13180            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13181            RecordedCommand::Timer { fired, .. } => *fired,
13182            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13183            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13184            RecordedCommand::SearchAttributes { .. }
13185            | RecordedCommand::CancellationScope { .. }
13186            | RecordedCommand::SideEffect { .. }
13187            | RecordedCommand::VersionMarker { .. }
13188            | RecordedCommand::Memo { .. }
13189            | RecordedCommand::CancellationBoundary { .. }
13190            | RecordedCommand::CancellationGroup { .. } => false,
13191        };
13192        if !terminal {
13193            all_completed = false;
13194            continue;
13195        }
13196        completed += 1;
13197    }
13198    all_completed && completed == handle.size
13199}
13200
13201fn selection_cancellation_for_handle(
13202    state: &WorkflowState,
13203    handle: &DurableOperationHandle,
13204) -> Result<bool> {
13205    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13206        recorded.selection_group_id == handle.selection_group_id
13207            && recorded.member_base_sequence == handle.base_sequence
13208    }) else {
13209        return Ok(false);
13210    };
13211    validate_selection_cancellation_marker(marker, handle)?;
13212    Ok(true)
13213}
13214
13215fn validate_selection_cancellations_for_handles(
13216    state: &WorkflowState,
13217    handles: &[DurableOperationHandle],
13218) -> Result<()> {
13219    let Some(group_id) = handles
13220        .first()
13221        .map(|handle| handle.selection_group_id.as_str())
13222    else {
13223        return Ok(());
13224    };
13225    for marker in state
13226        .cancelled_selection_members
13227        .iter()
13228        .filter(|marker| marker.selection_group_id == group_id)
13229    {
13230        let Some(handle) = handles
13231            .iter()
13232            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13233        else {
13234            return Err(invalid_recorded_history(
13235                "selection_cancellation_member_mismatch",
13236                marker.member_base_sequence,
13237                "SelectionOperationCancelled matching an authored selection handle",
13238                &format!("{marker:?}"),
13239                "selection cancellation member base does not name an authored member",
13240            ));
13241        };
13242        validate_selection_cancellation_marker(marker, handle)?;
13243    }
13244    Ok(())
13245}
13246
13247fn validate_selection_cancellation_marker(
13248    marker: &SelectionCancellation,
13249    handle: &DurableOperationHandle,
13250) -> Result<()> {
13251    if marker.selection_group_id != handle.selection_group_id
13252        || marker.member_key != handle.key
13253        || marker.member_index != handle.index
13254        || marker.member_base_sequence != handle.base_sequence
13255        || marker.member_size != handle.size
13256        || marker.operation_kind != handle.kind
13257        || marker.operation_identity != handle.identity
13258    {
13259        return Err(invalid_recorded_history(
13260            "selection_cancellation_member_mismatch",
13261            handle.base_sequence,
13262            "SelectionOperationCancelled matching the authored selection handle",
13263            &format!("{marker:?}"),
13264            "selection cancellation history targets different authored member metadata",
13265        ));
13266    }
13267    Ok(())
13268}
13269
13270/// Future returned by [`DurableOperationHandle::await_result`].
13271pub struct DurableOperationAwaitCall {
13272    handle: DurableOperationHandle,
13273}
13274
13275impl Future for DurableOperationAwaitCall {
13276    type Output = Result<ParallelResult>;
13277
13278    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13279        let mut state = match self.handle.ctx.state.lock() {
13280            Ok(state) => state,
13281            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13282        };
13283        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13284            return Poll::Ready(Err(error));
13285        }
13286        match state.prepare_selection_handle_cancellation(&self.handle) {
13287            Ok(true) => return Poll::Pending,
13288            Ok(false) => {}
13289            Err(error) => return Poll::Ready(Err(error)),
13290        }
13291        match selection_cancellation_for_handle(&state, &self.handle) {
13292            Err(error) => return Poll::Ready(Err(error)),
13293            Ok(false) => {}
13294            Ok(true) => {
13295                state.advance_cancellation_receipt(
13296                    &self.handle.selection_group_id,
13297                    self.handle.base_sequence,
13298                );
13299                return Poll::Ready(Err(Error::DurableOperationCancelled(
13300                    DurableOperationCancelled {
13301                        selection_group_id: self.handle.selection_group_id.clone(),
13302                        member_key: self.handle.key.clone(),
13303                        member_index: self.handle.index,
13304                        operation_kind: self.handle.kind.clone(),
13305                        operation_identity: self.handle.identity.clone(),
13306                    },
13307                )));
13308            }
13309        }
13310        match recorded_selection_member_outcome(&state, &self.handle) {
13311            Ok(Some(result)) => {
13312                state.advance_cancellation_handle(&self.handle, false);
13313                Poll::Ready(Ok(result))
13314            }
13315            Ok(None) => Poll::Pending,
13316            Err(error) => {
13317                if !workflow_task_integrity_error(&error) {
13318                    state.advance_cancellation_handle(&self.handle, true);
13319                }
13320                Poll::Ready(Err(error))
13321            }
13322        }
13323    }
13324}
13325
13326fn validate_selection_delivery_handle(
13327    state: &WorkflowState,
13328    handle: &DurableOperationHandle,
13329) -> Result<()> {
13330    let path = state
13331        .recorded_commands
13332        .iter()
13333        .find(|command| command.sequence() == handle.base_sequence)
13334        .and_then(|command| match command {
13335            RecordedCommand::Activity {
13336                parallel_group_path,
13337                ..
13338            }
13339            | RecordedCommand::ChildWorkflow {
13340                parallel_group_path,
13341                ..
13342            }
13343            | RecordedCommand::Timer {
13344                parallel_group_path,
13345                ..
13346            }
13347            | RecordedCommand::SignalWait {
13348                parallel_group_path,
13349                ..
13350            }
13351            | RecordedCommand::ConditionWait {
13352                parallel_group_path,
13353                ..
13354            } => parallel_group_path.as_ref(),
13355            _ => None,
13356        })
13357        .and_then(|path| path.first());
13358    let matches = path.is_some_and(|entry| {
13359        entry.parallel_group_mode.as_deref() == Some("select")
13360            && entry.parallel_group_id == handle.selection_group_id
13361            && entry.selection_member_key.as_ref() == Some(&handle.key)
13362            && entry.selection_member_index == Some(handle.index)
13363            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13364            && entry.selection_member_size == Some(handle.size)
13365            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13366    });
13367    if !matches
13368        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13369            != handle.identity
13370    {
13371        return Err(invalid_recorded_history(
13372            "cooperative_cancellation_call_mismatch",
13373            handle.base_sequence,
13374            "selection handle matching its authored durable identity",
13375            &format!("{handle:?}"),
13376            "selection handle identity or member metadata changed before cancellation replay",
13377        ));
13378    }
13379    Ok(())
13380}
13381
13382/// Future returned by [`DurableOperationHandle::cancel`].
13383pub struct CancelDurableOperationCall {
13384    handle: DurableOperationHandle,
13385    emitted: bool,
13386}
13387
13388impl Future for CancelDurableOperationCall {
13389    type Output = Result<()>;
13390
13391    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13392        let ctx = self.handle.ctx.clone();
13393        let mut state = match ctx.state.lock() {
13394            Ok(state) => state,
13395            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13396        };
13397        match selection_cancellation_for_handle(&state, &self.handle) {
13398            Err(error) => return Poll::Ready(Err(error)),
13399            Ok(true) => {
13400                state.advance_cancellation_receipt(
13401                    &self.handle.selection_group_id,
13402                    self.handle.base_sequence,
13403                );
13404                return Poll::Ready(Ok(()));
13405            }
13406            Ok(false) => {}
13407        }
13408        if recorded_selection_member_is_terminal(&state, &self.handle) {
13409            return Poll::Ready(Ok(()));
13410        }
13411        if !self.emitted {
13412            state.commands.push(json!({
13413                "type": "cancel_selection_operation",
13414                "selection_group_id": self.handle.selection_group_id,
13415                "member_key": self.handle.key,
13416                "member_index": self.handle.index,
13417                "member_base_sequence": self.handle.base_sequence,
13418                "member_size": self.handle.size,
13419                "operation_kind": self.handle.kind,
13420                "operation_identity": self.handle.identity,
13421            }));
13422            self.emitted = true;
13423        }
13424        // The cancellation command is only a request. Do not expose workflow
13425        // state after cancel until committed SelectionOperationCancelled
13426        // history proves that the request won the race with member completion.
13427        Poll::Pending
13428    }
13429}
13430
13431trait PollNestedResultExt<T> {
13432    fn flatten_result(self) -> Poll<Result<T>>;
13433}
13434
13435impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
13436    fn flatten_result(self) -> Poll<Result<T>> {
13437        match self {
13438            Poll::Ready(Ok(result)) => Poll::Ready(result),
13439            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13440            Poll::Pending => Poll::Pending,
13441        }
13442    }
13443}
13444
13445struct SagaCompensation {
13446    activity_type: String,
13447    options: ActivityOptions,
13448    arguments: AvroValue,
13449    registration_order: usize,
13450}
13451
13452/// Workflow-local deterministic saga compensation helper.
13453///
13454/// Register each compensation only after its forward step succeeds. Passing
13455/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
13456/// reverse registration order after any failure, including cooperative
13457/// cancellation. Each compensation is an ordinary durable activity, so replay,
13458/// duplicate delivery, and worker restart use existing history semantics.
13459pub struct Saga {
13460    ctx: WorkflowContext,
13461    compensations: Vec<SagaCompensation>,
13462}
13463
13464impl Saga {
13465    fn new(ctx: WorkflowContext) -> Self {
13466        Self {
13467            ctx,
13468            compensations: Vec::new(),
13469        }
13470    }
13471
13472    pub fn add_compensation<T: Serialize>(
13473        &mut self,
13474        activity_type: impl Into<String>,
13475        args: T,
13476    ) -> Result<&mut Self> {
13477        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
13478    }
13479
13480    pub fn add_compensation_with_options<T: Serialize>(
13481        &mut self,
13482        activity_type: impl Into<String>,
13483        options: ActivityOptions,
13484        args: T,
13485    ) -> Result<&mut Self> {
13486        let activity_type = activity_type.into();
13487        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
13488            return Err(Error::Codec(
13489                "saga compensation activity type must be non-empty without surrounding whitespace"
13490                    .to_string(),
13491            ));
13492        }
13493        options.validate().map_err(Error::InvalidActivityOptions)?;
13494        let arguments = AvroValue::from_serialize(&args)?;
13495        let registration_order = self.compensations.len() + 1;
13496        self.compensations.push(SagaCompensation {
13497            activity_type,
13498            options,
13499            arguments,
13500            registration_order,
13501        });
13502        Ok(self)
13503    }
13504
13505    /// Compensate `initiating_failure` and return the failure that must remain.
13506    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
13507        let _shield = match self.ctx.cancellation_shield() {
13508            Ok(shield) => shield,
13509            Err(error) => return error,
13510        };
13511        while let Some(compensation) = self.compensations.pop() {
13512            if let Err(compensation_failure) = self
13513                .ctx
13514                .activity_with_options(
13515                    compensation.activity_type.clone(),
13516                    compensation.options,
13517                    compensation.arguments,
13518                )
13519                .await
13520            {
13521                if workflow_task_integrity_error(&compensation_failure) {
13522                    return compensation_failure;
13523                }
13524                return Error::SagaCompensationFailed(SagaCompensationFailure {
13525                    initiating_failure: Box::new(initiating_failure),
13526                    compensation_failure: Box::new(compensation_failure),
13527                    compensation_activity_type: compensation.activity_type,
13528                    compensation_registration_order: compensation.registration_order,
13529                });
13530            }
13531        }
13532        initiating_failure
13533    }
13534
13535    /// Return a successful forward value or compensate and preserve its failure.
13536    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
13537        match outcome {
13538            Ok(value) => Ok(value),
13539            Err(error) => Err(self.compensate(error).await),
13540        }
13541    }
13542}
13543
13544pub struct ActivityCall {
13545    ctx: WorkflowContext,
13546    activity_type: String,
13547    options: ActivityOptions,
13548    worker_session: Option<WorkerSessionOptions>,
13549    args: Option<Result<AvroValue>>,
13550    scheduled: bool,
13551    local: bool,
13552    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
13553    parallel_group_path: Vec<ParallelGroupMetadata>,
13554}
13555
13556impl ActivityCall {
13557    fn poll_avro_value(
13558        mut self: Pin<&mut Self>,
13559        _cx: &mut TaskContext<'_>,
13560    ) -> Poll<Result<AvroValue>> {
13561        let ctx = self.ctx.clone();
13562        let mut state = match ctx.state.lock() {
13563            Ok(state) => state,
13564            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13565        };
13566
13567        if let Some(result) = &self.local_result {
13568            return match result.lock() {
13569                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
13570                    Poll::Ready(result.map_err(Error::ActivityFailed))
13571                }),
13572                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13573            };
13574        }
13575        if self.scheduled {
13576            return Poll::Pending;
13577        }
13578
13579        let options = match self.options.validate() {
13580            Ok(options) => options,
13581            Err(error) => {
13582                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
13583            }
13584        };
13585        if self.local {
13586            if self.worker_session.is_some() {
13587                return Poll::Ready(Err(Error::WorkerLoop(
13588                    "local activities cannot use worker-session routing".into(),
13589                )));
13590            }
13591            if let Err(error) = local_activity::validate(&options) {
13592                return Poll::Ready(Err(error));
13593            }
13594        }
13595        let session = match self
13596            .worker_session
13597            .as_ref()
13598            .map(WorkerSessionOptions::to_wire)
13599            .transpose()
13600        {
13601            Ok(value) => value,
13602            Err(error) => return Poll::Ready(Err(error)),
13603        };
13604        let session_queue = session
13605            .as_ref()
13606            .and_then(|session| session["queue"].as_str());
13607        let task_queue = options
13608            .task_queue
13609            .clone()
13610            .or_else(|| session_queue.map(str::to_owned))
13611            .unwrap_or_else(|| state.task_queue.clone());
13612        if session_queue.is_some_and(|queue| queue != task_queue) {
13613            return Poll::Ready(Err(Error::WorkerLoop(
13614                "worker-session queue must match the activity task queue".into(),
13615            )));
13616        }
13617        let current_recorded_options = RecordedActivityOptions {
13618            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
13619            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
13620            retry_policy: current_activity_retry_snapshot(&options),
13621            worker_session: session,
13622        };
13623
13624        let cursor = state.command_cursor;
13625        let call_kind = if self.local {
13626            CancellationCallKind::LocalActivity
13627        } else {
13628            CancellationCallKind::Activity
13629        };
13630        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13631            return Poll::Ready(Err(error));
13632        }
13633        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
13634            Ok(recorded) => recorded,
13635            Err(error) => return Poll::Ready(Err(error)),
13636        };
13637        if let Some(recorded) = recorded {
13638            let sequence = recorded.sequence();
13639            match recorded {
13640                RecordedCommand::Activity {
13641                    activity_type,
13642                    cancellation_policy,
13643                    options: recorded_options,
13644                    outcome,
13645                    parallel_group_path,
13646                    ..
13647                } => {
13648                    let current_policy = options
13649                        .cancellation_policy
13650                        .unwrap_or(CancellationPolicy::TryCancel)
13651                        .as_str();
13652                    if cancellation_policy != current_policy {
13653                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13654                            ReplayFailure::new(
13655                                "activity_cancellation_policy_changed",
13656                                Some(sequence),
13657                                Some(cancellation_policy),
13658                                Some(current_policy.to_string()),
13659                                "Activity cancellation policy changed during replay",
13660                            ),
13661                        )));
13662                    }
13663                    if let Err(error) = ensure_parallel_path_matches(
13664                        sequence,
13665                        parallel_group_path.as_deref(),
13666                        &self.parallel_group_path,
13667                    ) {
13668                        return Poll::Ready(Err(error));
13669                    }
13670                    if let Some(recorded_type) = activity_type {
13671                        if recorded_type != self.activity_type {
13672                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13673                                ReplayFailure::new(
13674                                    "recorded_command_detail_mismatch",
13675                                    Some(sequence),
13676                                    Some(format!("activity:{recorded_type}")),
13677                                    Some(format!("activity:{}", self.activity_type)),
13678                                    "recorded activity type differs from the current workflow command",
13679                                ),
13680                            )));
13681                        }
13682                    }
13683                    if let Some(recorded_options) = recorded_options {
13684                        if recorded_options.worker_session
13685                            != current_recorded_options.worker_session
13686                        {
13687                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
13688                                "activity_worker_session_mismatch", Some(sequence),
13689                                Some(activity_options_description(&recorded_options)),
13690                                Some(activity_options_description(&current_recorded_options)),
13691                                "recorded worker-session routing differs from the current activity",
13692                            ))));
13693                        }
13694                        if !recorded_options
13695                            .task_queue
13696                            .matches_current(&current_recorded_options.task_queue)
13697                        {
13698                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13699                                ReplayFailure::new(
13700                                    "activity_task_queue_mismatch",
13701                                    Some(sequence),
13702                                    Some(activity_options_description(&recorded_options)),
13703                                    Some(activity_options_description(&current_recorded_options)),
13704                                    "recorded activity task queue differs from the current workflow command",
13705                                ),
13706                            )));
13707                        }
13708                        if (self.local
13709                            && matches!(
13710                                recorded_options.execution_mode,
13711                                RecordedSnapshotValue::Unknown
13712                            ))
13713                            || !recorded_options
13714                                .execution_mode
13715                                .matches_current(&current_recorded_options.execution_mode)
13716                        {
13717                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13718                                ReplayFailure::new(
13719                                    "activity_execution_mode_mismatch",
13720                                    Some(sequence),
13721                                    Some(activity_options_description(&recorded_options)),
13722                                    Some(activity_options_description(&current_recorded_options)),
13723                                    "recorded activity execution mode differs from the current workflow command",
13724                                ),
13725                            )));
13726                        }
13727                        if !recorded_options
13728                            .retry_policy
13729                            .matches_current(&current_recorded_options.retry_policy)
13730                        {
13731                            return Poll::Ready(Err(Error::NonDeterministicReplay(
13732                                ReplayFailure::new(
13733                                    "activity_retry_policy_mismatch",
13734                                    Some(sequence),
13735                                    Some(activity_options_description(&recorded_options)),
13736                                    Some(activity_options_description(&current_recorded_options)),
13737                                    "recorded activity retry policy differs from the current workflow command",
13738                                ),
13739                            )));
13740                        }
13741                    }
13742                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
13743                        return Poll::Ready(Err(error));
13744                    }
13745                    match state.prepare_scalar_cancellation(
13746                        cursor,
13747                        call_kind,
13748                        &self.parallel_group_path,
13749                    ) {
13750                        Ok(true) => {
13751                            self.scheduled = true;
13752                            return Poll::Pending;
13753                        }
13754                        Ok(false) => {}
13755                        Err(error) => return Poll::Ready(Err(error)),
13756                    }
13757                    state.command_cursor += 1;
13758                    if let Some(outcome) = outcome {
13759                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13760                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
13761                    }
13762                    state.matched_recorded_pending = true;
13763                    self.scheduled = true;
13764                    return Poll::Pending;
13765                }
13766                other => {
13767                    return Poll::Ready(Err(command_mismatch(
13768                        &other,
13769                        format!("activity:{}", self.activity_type),
13770                    )));
13771                }
13772            }
13773        }
13774
13775        if !self.scheduled {
13776            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
13777                Ok(args) => args,
13778                Err(error) => return Poll::Ready(Err(error)),
13779            };
13780            let arguments = normalize_avro_arguments(args);
13781            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
13782                Ok(envelope) => envelope,
13783                Err(error) => return Poll::Ready(Err(error)),
13784            };
13785
13786            let mut command = serde_json::Map::from_iter([
13787                (
13788                    "type".to_string(),
13789                    json!(if self.local {
13790                        "record_local_activity"
13791                    } else {
13792                        "schedule_activity"
13793                    }),
13794                ),
13795                (
13796                    "activity_type".to_string(),
13797                    json!(self.activity_type.clone()),
13798                ),
13799                ("queue".to_string(), json!(task_queue)),
13800                ("arguments".to_string(), envelope),
13801            ]);
13802            for (field, value) in [
13803                ("start_to_close_timeout", options.start_to_close_timeout),
13804                (
13805                    "schedule_to_start_timeout",
13806                    options.schedule_to_start_timeout,
13807                ),
13808                (
13809                    "schedule_to_close_timeout",
13810                    options.schedule_to_close_timeout,
13811                ),
13812                ("heartbeat_timeout", options.heartbeat_timeout),
13813            ] {
13814                if let Some(value) = value {
13815                    command.insert(field.to_string(), json!(value));
13816                }
13817            }
13818            if let Some(retry_policy) = &options.retry_policy {
13819                command.insert("retry_policy".to_string(), retry_policy.clone());
13820            }
13821            if let Some(policy) = options.cancellation_policy {
13822                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
13823            }
13824            if let Some(session) = current_recorded_options.worker_session {
13825                command.insert("worker_session".into(), session);
13826            }
13827            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13828            ctx.apply_scope_membership(&mut command);
13829            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
13830                Ok(true) => {
13831                    self.scheduled = true;
13832                    return Poll::Pending;
13833                }
13834                Ok(false) => {}
13835                Err(error) => return Poll::Ready(Err(error)),
13836            }
13837            if self.local {
13838                command.remove("queue");
13839                command.insert("execution_mode".into(), json!("local"));
13840                let result = Arc::new(Mutex::new(None));
13841                let command_index = state.commands.len();
13842                state.local_activity_requests.push(local_activity::Request {
13843                    command_index,
13844                    options,
13845                    arguments,
13846                    result: result.clone(),
13847                });
13848                self.local_result = Some(result);
13849            }
13850            state.commands.push(Value::Object(command));
13851            self.scheduled = true;
13852        }
13853
13854        Poll::Pending
13855    }
13856}
13857
13858impl Future for ActivityCall {
13859    type Output = Result<Value>;
13860
13861    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13862        match self.poll_avro_value(cx) {
13863            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
13864            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13865            Poll::Pending => Poll::Pending,
13866        }
13867    }
13868}
13869
13870/// Future returned by [`WorkflowContext::sleep`].
13871pub struct TimerCall {
13872    ctx: WorkflowContext,
13873    delay_seconds: Option<u64>,
13874    scheduled: bool,
13875    matched_pending: bool,
13876    parallel_group_path: Vec<ParallelGroupMetadata>,
13877}
13878
13879impl Future for TimerCall {
13880    type Output = Result<()>;
13881
13882    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13883        if self.matched_pending {
13884            return Poll::Pending;
13885        }
13886
13887        let ctx = self.ctx.clone();
13888        let Some(requested_delay) = self.delay_seconds else {
13889            return Poll::Ready(Err(Error::TimerDurationOverflow));
13890        };
13891        let mut state = match ctx.state.lock() {
13892            Ok(state) => state,
13893            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13894        };
13895
13896        let cursor = state.command_cursor;
13897        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
13898            return Poll::Ready(Err(error));
13899        }
13900        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
13901        {
13902            Ok(recorded) => recorded,
13903            Err(error) => return Poll::Ready(Err(error)),
13904        };
13905        if let Some(recorded) = recorded {
13906            match recorded {
13907                RecordedCommand::Timer {
13908                    sequence,
13909                    delay_seconds,
13910                    fired,
13911                    parallel_group_path,
13912                    ..
13913                } => {
13914                    if let Err(error) =
13915                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
13916                    {
13917                        return Poll::Ready(Err(error));
13918                    }
13919                    if let Err(error) = ensure_parallel_path_matches(
13920                        sequence,
13921                        parallel_group_path.as_deref(),
13922                        &self.parallel_group_path,
13923                    ) {
13924                        return Poll::Ready(Err(error));
13925                    }
13926                    if delay_seconds != requested_delay {
13927                        return Poll::Ready(Err(Error::NonDeterministicReplay(
13928                            ReplayFailure::new(
13929                                "timer_delay_mismatch",
13930                                Some(sequence),
13931                                Some(format!("timer:{delay_seconds}s")),
13932                                Some(format!("timer:{requested_delay}s")),
13933                                "recorded timer delay differs from the current workflow command",
13934                            ),
13935                        )));
13936                    }
13937                    if let Err(error) =
13938                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
13939                    {
13940                        return Poll::Ready(Err(error));
13941                    }
13942                    match state.prepare_scalar_cancellation(
13943                        cursor,
13944                        CancellationCallKind::Timer,
13945                        &self.parallel_group_path,
13946                    ) {
13947                        Ok(true) => {
13948                            self.scheduled = true;
13949                            self.matched_pending = true;
13950                            return Poll::Pending;
13951                        }
13952                        Ok(false) => {}
13953                        Err(error) => return Poll::Ready(Err(error)),
13954                    }
13955                    state.command_cursor += 1;
13956                    if fired {
13957                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
13958                        return Poll::Ready(Ok(()));
13959                    }
13960                    state.matched_recorded_pending = true;
13961                    self.scheduled = true;
13962                    self.matched_pending = true;
13963                    return Poll::Pending;
13964                }
13965                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
13966            }
13967        }
13968
13969        if !self.scheduled {
13970            let mut command = serde_json::Map::from_iter([
13971                ("type".to_string(), json!("start_timer")),
13972                ("delay_seconds".to_string(), json!(requested_delay)),
13973            ]);
13974            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
13975                Ok(Some(proof)) => {
13976                    command.insert("cancellation_cleanup".into(), proof);
13977                }
13978                Ok(None) => {}
13979                Err(error) => return Poll::Ready(Err(error)),
13980            }
13981            apply_parallel_group_path(&mut command, &self.parallel_group_path);
13982            ctx.apply_scope_membership(&mut command);
13983            match state.prepare_scalar_cancellation(
13984                cursor,
13985                CancellationCallKind::Timer,
13986                &self.parallel_group_path,
13987            ) {
13988                Ok(true) => {
13989                    self.scheduled = true;
13990                    self.matched_pending = true;
13991                    return Poll::Pending;
13992                }
13993                Ok(false) => {}
13994                Err(error) => return Poll::Ready(Err(error)),
13995            }
13996            state.commands.push(Value::Object(command));
13997            self.scheduled = true;
13998        }
13999
14000        Poll::Pending
14001    }
14002}
14003
14004/// Future returned by [`WorkflowContext::wait_condition`].
14005pub struct ConditionWaitCall {
14006    ctx: WorkflowContext,
14007    options: ConditionWaitOptions,
14008    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
14009    occurrence_id: Option<String>,
14010    opened_wait: bool,
14011    parallel_group_path: Vec<ParallelGroupMetadata>,
14012}
14013
14014impl Future for ConditionWaitCall {
14015    type Output = Result<ConditionWaitResult>;
14016
14017    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14018        if self.opened_wait {
14019            return Poll::Pending;
14020        }
14021
14022        let options = match self.options.validate() {
14023            Ok(options) => options,
14024            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
14025        };
14026        let ctx = self.ctx.clone();
14027        let occurrence_id = match self.occurrence_id.as_ref() {
14028            Some(occurrence_id) => occurrence_id.clone(),
14029            None => {
14030                let mut state = match ctx.state.lock() {
14031                    Ok(state) => state,
14032                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14033                };
14034                let ordinal = state.condition_wait_occurrence_counter;
14035                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
14036                    Some(next) => next,
14037                    None => {
14038                        return Poll::Ready(Err(Error::WorkerLoop(
14039                            "condition wait occurrence counter overflowed".to_string(),
14040                        )))
14041                    }
14042                };
14043                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
14044                drop(state);
14045                self.occurrence_id = Some(occurrence_id.clone());
14046                occurrence_id
14047            }
14048        };
14049
14050        let recorded_result = {
14051            let mut state = match ctx.state.lock() {
14052                Ok(state) => state,
14053                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14054            };
14055            let initial_cursor = state.command_cursor;
14056            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
14057                return Poll::Ready(Err(error));
14058            }
14059            let recorded = match state
14060                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
14061            {
14062                Ok(recorded) => recorded,
14063                Err(error) => return Poll::Ready(Err(error)),
14064            };
14065            let Some(recorded) = recorded else {
14066                drop(state);
14067                return self.poll_new_condition(options);
14068            };
14069            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
14070                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
14071            }
14072
14073            let mut cursor = state.command_cursor;
14074            let mut result = None;
14075            let mut pending_delivery = false;
14076            loop {
14077                if cursor > initial_cursor
14078                    && matches!(
14079                        state.recorded_commands.get(cursor),
14080                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
14081                    )
14082                {
14083                    break;
14084                }
14085                let recorded = match state
14086                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
14087                {
14088                    Ok(recorded) => recorded,
14089                    Err(error) => return Poll::Ready(Err(error)),
14090                };
14091                let Some(RecordedCommand::ConditionWait {
14092                    sequence,
14093                    occurrence_id: ref recorded_occurrence_id,
14094                    ref condition_key,
14095                    ref predicate_identity,
14096                    timeout_seconds,
14097                    result: recorded_result,
14098                    ref parallel_group_path,
14099                    ..
14100                }) = recorded
14101                else {
14102                    break;
14103                };
14104
14105                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
14106                    break;
14107                }
14108                if let Err(error) = ensure_parallel_path_matches(
14109                    sequence,
14110                    parallel_group_path.as_deref(),
14111                    &self.parallel_group_path,
14112                ) {
14113                    return Poll::Ready(Err(error));
14114                }
14115                if let Err(error) = validate_recorded_condition_wait(
14116                    sequence,
14117                    recorded_occurrence_id,
14118                    condition_key.as_deref(),
14119                    predicate_identity,
14120                    timeout_seconds,
14121                    &occurrence_id,
14122                    &options,
14123                ) {
14124                    return Poll::Ready(Err(error));
14125                }
14126                if result == Some(ConditionWaitResult::TimedOut) {
14127                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14128                        "condition_wait_reopened_after_timeout",
14129                        Some(sequence),
14130                        Some("timed-out condition is terminal".to_string()),
14131                        Some("another physical wait-open".to_string()),
14132                        "condition history reopened one logical wait after its durable timeout",
14133                    ))));
14134                }
14135                if let Err(error) =
14136                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14137                {
14138                    return Poll::Ready(Err(error));
14139                }
14140                match state.prepare_scalar_cancellation(
14141                    cursor,
14142                    CancellationCallKind::Condition,
14143                    &self.parallel_group_path,
14144                ) {
14145                    Ok(pending) => pending_delivery |= pending,
14146                    Err(error) => return Poll::Ready(Err(error)),
14147                }
14148                result = recorded_result;
14149                if result.is_some() {
14150                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14151                }
14152                cursor += 1;
14153            }
14154            state.command_cursor = cursor;
14155            if pending_delivery {
14156                self.opened_wait = true;
14157                return Poll::Pending;
14158            }
14159            result
14160        };
14161
14162        if let Some(result) = recorded_result {
14163            return Poll::Ready(Ok(result));
14164        }
14165
14166        self.poll_open_condition(options, true)
14167    }
14168}
14169
14170impl ConditionWaitCall {
14171    fn poll_new_condition(
14172        self: Pin<&mut Self>,
14173        options: ValidatedConditionWaitOptions,
14174    ) -> Poll<Result<ConditionWaitResult>> {
14175        self.poll_open_condition(options, false)
14176    }
14177
14178    fn poll_open_condition(
14179        mut self: Pin<&mut Self>,
14180        options: ValidatedConditionWaitOptions,
14181        recorded_wait: bool,
14182    ) -> Poll<Result<ConditionWaitResult>> {
14183        {
14184            let ctx = self.ctx.clone();
14185            let mut state = match ctx.state.lock() {
14186                Ok(state) => state,
14187                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14188            };
14189            let cursor = state.command_cursor;
14190            match state.prepare_scalar_cancellation(
14191                cursor,
14192                CancellationCallKind::Condition,
14193                &self.parallel_group_path,
14194            ) {
14195                Ok(true) => {
14196                    self.opened_wait = true;
14197                    return Poll::Pending;
14198                }
14199                Ok(false) => {}
14200                Err(error) => return Poll::Ready(Err(error)),
14201            }
14202        }
14203        let selection_member = self
14204            .parallel_group_path
14205            .first()
14206            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14207        match (self.predicate)() {
14208            Ok(true) if !selection_member || recorded_wait => {
14209                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14210            }
14211            Ok(_) => {}
14212            Err(error) => return Poll::Ready(Err(error)),
14213        }
14214        if options.timeout_seconds == Some(0) && !selection_member {
14215            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14216        }
14217
14218        let ctx = self.ctx.clone();
14219        let mut state = match ctx.state.lock() {
14220            Ok(state) => state,
14221            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14222        };
14223        let mut command = serde_json::Map::from_iter([
14224            ("type".to_string(), json!("open_condition_wait")),
14225            (
14226                "condition_wait_occurrence_id".to_string(),
14227                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14228            ),
14229            ("condition_key".to_string(), json!(options.condition_key)),
14230            (
14231                "condition_definition_fingerprint".to_string(),
14232                json!(options.predicate_identity),
14233            ),
14234        ]);
14235        if let Some(timeout_seconds) = options.timeout_seconds {
14236            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14237        }
14238        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14239        ctx.apply_scope_membership(&mut command);
14240        state.commands.push(Value::Object(command));
14241        drop(state);
14242        self.opened_wait = true;
14243        Poll::Pending
14244    }
14245}
14246
14247fn validate_recorded_condition_wait(
14248    sequence: u64,
14249    recorded_occurrence_id: &str,
14250    recorded_key: Option<&str>,
14251    recorded_predicate_identity: &str,
14252    recorded_timeout_seconds: Option<u64>,
14253    current_occurrence_id: &str,
14254    current: &ValidatedConditionWaitOptions,
14255) -> Result<()> {
14256    if recorded_occurrence_id != current_occurrence_id {
14257        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14258            "condition_wait_occurrence_mismatch",
14259            Some(sequence),
14260            Some(recorded_occurrence_id.to_string()),
14261            Some(current_occurrence_id.to_string()),
14262            "recorded condition occurrence differs from the current authored wait position",
14263        )));
14264    }
14265    if recorded_key != Some(current.condition_key.as_str()) {
14266        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14267            "condition_wait_key_mismatch",
14268            Some(sequence),
14269            recorded_key.map(str::to_string),
14270            Some(current.condition_key.clone()),
14271            "recorded condition identity differs from the current workflow wait",
14272        )));
14273    }
14274    if recorded_predicate_identity != current.predicate_identity {
14275        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14276            "condition_wait_predicate_mismatch",
14277            Some(sequence),
14278            Some(recorded_predicate_identity.to_string()),
14279            Some(current.predicate_identity.clone()),
14280            "recorded condition predicate behavior differs from current workflow code",
14281        )));
14282    }
14283    if recorded_timeout_seconds != current.timeout_seconds {
14284        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14285            "condition_wait_timeout_mismatch",
14286            Some(sequence),
14287            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14288            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14289            "recorded condition timeout differs from the current workflow wait",
14290        )));
14291    }
14292    Ok(())
14293}
14294
14295/// Future returned by [`WorkflowContext::start_child_workflow`].
14296pub struct ChildWorkflowCall {
14297    ctx: WorkflowContext,
14298    workflow_type: String,
14299    options: ChildWorkflowOptions,
14300    args: Option<Result<AvroValue>>,
14301    scheduled: bool,
14302    matched_pending: bool,
14303    parallel_group_path: Vec<ParallelGroupMetadata>,
14304}
14305
14306impl ChildWorkflowCall {
14307    fn poll_avro_value(
14308        mut self: Pin<&mut Self>,
14309        _cx: &mut TaskContext<'_>,
14310    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14311        if self.matched_pending {
14312            return Poll::Pending;
14313        }
14314
14315        let ctx = self.ctx.clone();
14316        let mut state = match ctx.state.lock() {
14317            Ok(state) => state,
14318            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14319        };
14320
14321        let cursor = state.command_cursor;
14322        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14323            return Poll::Ready(Err(error));
14324        }
14325        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14326        {
14327            Ok(recorded) => recorded,
14328            Err(error) => return Poll::Ready(Err(error)),
14329        };
14330        if let Some(recorded) = recorded {
14331            let sequence = recorded.sequence();
14332            match recorded {
14333                RecordedCommand::ChildWorkflow {
14334                    workflow_type,
14335                    policies,
14336                    outcome,
14337                    parallel_group_path,
14338                    ..
14339                } => {
14340                    if let Err(error) = ensure_parallel_path_matches(
14341                        sequence,
14342                        parallel_group_path.as_deref(),
14343                        &self.parallel_group_path,
14344                    ) {
14345                        return Poll::Ready(Err(error));
14346                    }
14347                    if let Some(recorded_type) = workflow_type {
14348                        if recorded_type != self.workflow_type {
14349                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14350                                ReplayFailure::new(
14351                                    "recorded_command_detail_mismatch",
14352                                    Some(sequence),
14353                                    Some(format!("child workflow:{recorded_type}")),
14354                                    Some(format!("child workflow:{}", self.workflow_type)),
14355                                    "recorded child workflow type differs from the current workflow command",
14356                                ),
14357                            )));
14358                        }
14359                    }
14360                    if let Err(error) =
14361                        ensure_child_policies_match(sequence, &policies, &self.options)
14362                    {
14363                        return Poll::Ready(Err(error));
14364                    }
14365                    if let Err(error) =
14366                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14367                    {
14368                        return Poll::Ready(Err(error));
14369                    }
14370                    match state.prepare_scalar_cancellation(
14371                        cursor,
14372                        CancellationCallKind::Child,
14373                        &self.parallel_group_path,
14374                    ) {
14375                        Ok(true) => {
14376                            self.scheduled = true;
14377                            self.matched_pending = true;
14378                            return Poll::Pending;
14379                        }
14380                        Ok(false) => {}
14381                        Err(error) => return Poll::Ready(Err(error)),
14382                    }
14383                    state.command_cursor += 1;
14384                    if let Some(outcome) = outcome {
14385                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14386                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
14387                    }
14388                    state.matched_recorded_pending = true;
14389                    self.scheduled = true;
14390                    self.matched_pending = true;
14391                    return Poll::Pending;
14392                }
14393                other => {
14394                    return Poll::Ready(Err(command_mismatch(
14395                        &other,
14396                        format!("child workflow:{}", self.workflow_type),
14397                    )));
14398                }
14399            }
14400        }
14401
14402        if !self.scheduled {
14403            if self.options.task_queue.trim().is_empty() {
14404                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14405                    "task_queue must not be empty".to_string(),
14406                )));
14407            }
14408            for (name, value) in [
14409                (
14410                    "execution_timeout_seconds",
14411                    self.options.execution_timeout_seconds,
14412                ),
14413                ("run_timeout_seconds", self.options.run_timeout_seconds),
14414            ] {
14415                if value == Some(0) {
14416                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
14417                        "{name} must be at least 1"
14418                    ))));
14419                }
14420            }
14421
14422            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14423                Ok(args) => args,
14424                Err(error) => return Poll::Ready(Err(error)),
14425            };
14426            let arguments = match encode_typed_envelope(
14427                &normalize_avro_arguments(args),
14428                &state.payload_codec,
14429            ) {
14430                Ok(arguments) => arguments,
14431                Err(error) => return Poll::Ready(Err(error)),
14432            };
14433            let mut command = json!({
14434                "type": "start_child_workflow",
14435                "workflow_type": self.workflow_type,
14436                "queue": self.options.task_queue,
14437                "parent_close_policy": self.options.parent_close_policy.as_str(),
14438                "arguments": arguments,
14439            });
14440            let object = command
14441                .as_object_mut()
14442                .expect("child workflow command is always an object");
14443            if self.options.cancellation_policy != CancellationPolicy::Abandon {
14444                object.insert(
14445                    "cancellation_policy".to_string(),
14446                    json!(self.options.cancellation_policy.as_str()),
14447                );
14448            }
14449            if let Some(policy) = &self.options.retry_policy {
14450                let mut retry_policy = serde_json::Map::new();
14451                if let Some(max_attempts) = policy.max_attempts {
14452                    if max_attempts == 0 {
14453                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14454                            "retry_policy.max_attempts must be at least 1".to_string(),
14455                        )));
14456                    }
14457                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
14458                }
14459                if !policy.backoff_seconds.is_empty() {
14460                    retry_policy
14461                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
14462                }
14463                if !policy.non_retryable_error_types.is_empty() {
14464                    retry_policy.insert(
14465                        "non_retryable_error_types".to_string(),
14466                        json!(policy.non_retryable_error_types),
14467                    );
14468                }
14469                if retry_policy.is_empty() {
14470                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14471                        "retry_policy must configure at least one field".to_string(),
14472                    )));
14473                }
14474                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
14475            }
14476            if let Some(seconds) = self.options.execution_timeout_seconds {
14477                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
14478            }
14479            if let Some(seconds) = self.options.run_timeout_seconds {
14480                object.insert("run_timeout_seconds".to_string(), json!(seconds));
14481            }
14482            apply_parallel_group_path(object, &self.parallel_group_path);
14483            ctx.apply_scope_membership(object);
14484            match state.prepare_scalar_cancellation(
14485                cursor,
14486                CancellationCallKind::Child,
14487                &self.parallel_group_path,
14488            ) {
14489                Ok(true) => {
14490                    self.scheduled = true;
14491                    self.matched_pending = true;
14492                    return Poll::Pending;
14493                }
14494                Ok(false) => {}
14495                Err(error) => return Poll::Ready(Err(error)),
14496            }
14497            state.commands.push(command);
14498            self.scheduled = true;
14499        }
14500
14501        Poll::Pending
14502    }
14503}
14504
14505impl Future for ChildWorkflowCall {
14506    type Output = Result<ChildWorkflowResult>;
14507
14508    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14509        match self.poll_avro_value(cx) {
14510            Poll::Ready(Ok(result)) => match result.result.into_json() {
14511                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
14512                    parent: result.parent,
14513                    child: result.child,
14514                    child_workflow_type: result.child_workflow_type,
14515                    result: projected,
14516                })),
14517                Err(error) => Poll::Ready(Err(error)),
14518            },
14519            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14520            Poll::Pending => Poll::Pending,
14521        }
14522    }
14523}
14524
14525fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
14526    Error::NonDeterministicReplay(ReplayFailure::new(
14527        "recorded_command_mismatch",
14528        Some(recorded.sequence()),
14529        Some(recorded.shape().to_string()),
14530        Some(actual.into()),
14531        "current workflow command does not match the recorded durable command sequence",
14532    ))
14533}
14534
14535pub struct SignalCall {
14536    ctx: WorkflowContext,
14537    signal_name: String,
14538    runtime_reserved_allowed: bool,
14539    opened_wait: bool,
14540    matched_pending: bool,
14541    parallel_group_path: Vec<ParallelGroupMetadata>,
14542}
14543
14544impl SignalCall {
14545    fn poll_avro_value(
14546        mut self: Pin<&mut Self>,
14547        _cx: &mut TaskContext<'_>,
14548    ) -> Poll<Result<Vec<AvroValue>>> {
14549        if self.matched_pending {
14550            return Poll::Pending;
14551        }
14552        if !self.runtime_reserved_allowed {
14553            if let Err(error) = validate_user_signal_name(&self.signal_name) {
14554                return Poll::Ready(Err(error));
14555            }
14556        }
14557
14558        let ctx = self.ctx.clone();
14559        let mut state = match ctx.state.lock() {
14560            Ok(state) => state,
14561            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14562        };
14563
14564        let cursor = state.command_cursor;
14565        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14566            return Poll::Ready(Err(error));
14567        }
14568        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
14569        {
14570            Ok(recorded) => recorded,
14571            Err(error) => return Poll::Ready(Err(error)),
14572        };
14573        if let Some(recorded) = recorded {
14574            match recorded {
14575                RecordedCommand::SignalWait {
14576                    sequence,
14577                    signal_name,
14578                    value,
14579                    parallel_group_path,
14580                } => {
14581                    if let Err(error) = ensure_parallel_path_matches(
14582                        sequence,
14583                        parallel_group_path.as_deref(),
14584                        &self.parallel_group_path,
14585                    ) {
14586                        return Poll::Ready(Err(error));
14587                    }
14588                    if signal_name != self.signal_name {
14589                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14590                            ReplayFailure::new(
14591                                "recorded_command_detail_mismatch",
14592                                Some(sequence),
14593                                Some(format!("signal wait:{signal_name}")),
14594                                Some(format!("signal wait:{}", self.signal_name)),
14595                                "recorded signal name differs from the current workflow command",
14596                            ),
14597                        )));
14598                    }
14599
14600                    if let Err(error) =
14601                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
14602                    {
14603                        return Poll::Ready(Err(error));
14604                    }
14605                    match state.prepare_scalar_cancellation(
14606                        cursor,
14607                        CancellationCallKind::Signal,
14608                        &self.parallel_group_path,
14609                    ) {
14610                        Ok(true) => {
14611                            self.opened_wait = true;
14612                            self.matched_pending = true;
14613                            return Poll::Pending;
14614                        }
14615                        Ok(false) => {}
14616                        Err(error) => return Poll::Ready(Err(error)),
14617                    }
14618                    state.command_cursor += 1;
14619                    if let Some(value) = value {
14620                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14621                        return Poll::Ready(Ok(value));
14622                    }
14623                    if state
14624                        .resume_signal
14625                        .as_ref()
14626                        .is_some_and(|signal| signal.signal_name == self.signal_name)
14627                    {
14628                        let signal = state
14629                            .resume_signal
14630                            .take()
14631                            .expect("matching resume signal is present");
14632                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
14633                        return Poll::Ready(Ok(signal.arguments));
14634                    }
14635
14636                    state.matched_recorded_pending = true;
14637                    self.opened_wait = true;
14638                    self.matched_pending = true;
14639                    return Poll::Pending;
14640                }
14641                other => {
14642                    return Poll::Ready(Err(command_mismatch(
14643                        &other,
14644                        format!("signal wait:{}", self.signal_name),
14645                    )));
14646                }
14647            }
14648        }
14649
14650        match state.prepare_scalar_cancellation(
14651            cursor,
14652            CancellationCallKind::Signal,
14653            &self.parallel_group_path,
14654        ) {
14655            Ok(true) => {
14656                self.opened_wait = true;
14657                self.matched_pending = true;
14658                return Poll::Pending;
14659            }
14660            Ok(false) => {}
14661            Err(error) => return Poll::Ready(Err(error)),
14662        }
14663
14664        if state
14665            .resume_signal
14666            .as_ref()
14667            .is_some_and(|signal| signal.signal_name == self.signal_name)
14668        {
14669            let signal = state
14670                .resume_signal
14671                .take()
14672                .expect("matching resume signal is present");
14673            state.unavailable_cancellation_boundary(&self.parallel_group_path);
14674            return Poll::Ready(Ok(signal.arguments));
14675        }
14676
14677        if !self.opened_wait {
14678            let mut command = serde_json::Map::from_iter([
14679                ("type".to_string(), json!("open_signal_wait")),
14680                ("signal_name".to_string(), json!(self.signal_name)),
14681            ]);
14682            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14683            ctx.apply_scope_membership(&mut command);
14684            state.commands.push(Value::Object(command));
14685            self.opened_wait = true;
14686        }
14687
14688        Poll::Pending
14689    }
14690}
14691
14692impl Future for SignalCall {
14693    type Output = Result<Vec<Value>>;
14694
14695    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14696        match self.poll_avro_value(cx) {
14697            Poll::Ready(Ok(values)) => Poll::Ready(
14698                values
14699                    .into_iter()
14700                    .map(AvroValue::into_json)
14701                    .collect::<Result<Vec<_>>>(),
14702            ),
14703            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14704            Poll::Pending => Poll::Pending,
14705        }
14706    }
14707}
14708
14709#[derive(Clone, Debug)]
14710pub struct ActivityContext {
14711    client: Client,
14712    pub task_id: String,
14713    pub activity_attempt_id: String,
14714    pub lease_owner: String,
14715    pub activity_type: String,
14716    pub attempt_number: u64,
14717    pub task_queue: String,
14718    pub worker_id: String,
14719    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
14720    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
14721    worker_session: Option<WorkerSession>,
14722}
14723
14724impl ActivityContext {
14725    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
14726        if let Some(heartbeats) = &self.local_heartbeats {
14727            return heartbeats
14728                .lock()
14729                .map_err(|_| Error::WorkflowStatePoisoned)?
14730                .record(details);
14731        }
14732        if let Some(guard) = &self.claim_guard {
14733            return guard.heartbeat(self, details).await;
14734        }
14735        if let Some(session) = &self.worker_session {
14736            if !session.active() {
14737                return Err(Error::ActivityExecutionAbandoned(
14738                    "worker-session lease or TTL is no longer active".into(),
14739                ));
14740            }
14741            let result = self
14742                .client
14743                .heartbeat_activity_task_value(
14744                    &self.task_id,
14745                    &self.activity_attempt_id,
14746                    &self.lease_owner,
14747                    details,
14748                )
14749                .await;
14750            return worker_session::settle_activity_heartbeat(
14751                session,
14752                result,
14753                &self.task_id,
14754                &self.activity_attempt_id,
14755                &self.lease_owner,
14756            );
14757        }
14758        self.client
14759            .heartbeat_activity_task(
14760                &self.task_id,
14761                &self.activity_attempt_id,
14762                &self.lease_owner,
14763                details,
14764            )
14765            .await
14766    }
14767}
14768
14769fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
14770    validate_payload_codec(codec)?;
14771    match value {
14772        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
14773            value, codec,
14774        )?)),
14775        None => Ok(AvroValue::Array(Vec::new())),
14776    }
14777}
14778
14779fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
14780    let Some(signal_name) = task
14781        .signal_name
14782        .as_deref()
14783        .filter(|value| !value.is_empty())
14784    else {
14785        return Ok(None);
14786    };
14787    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
14788    let AvroValue::Array(arguments) = decoded else {
14789        unreachable!("normalize_avro_arguments always returns an array");
14790    };
14791
14792    Ok(Some(ResumeSignal {
14793        signal_name: signal_name.to_string(),
14794        arguments,
14795    }))
14796}
14797
14798fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
14799    validate_payload_codec(&task.payload_codec)?;
14800    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
14801    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
14802    for event in &task.history_events {
14803        validate_history_event_payloads(event, &task.payload_codec)?;
14804    }
14805    Ok(())
14806}
14807
14808fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
14809    validate_payload_codec(&task.payload_codec)?;
14810    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
14811}
14812
14813fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
14814    validate_payload_codec(&task.payload_codec)?;
14815    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
14816    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
14817    for event in &task.history_events {
14818        validate_history_event_payloads(event, &task.payload_codec)?;
14819    }
14820
14821    let Some(export) = task.history_export.as_ref() else {
14822        return Ok(());
14823    };
14824    let export_codec = match export.get("payloads") {
14825        Some(payloads) => declared_payload_codec(payloads, "codec")?,
14826        None => None,
14827    }
14828    .unwrap_or(&task.payload_codec);
14829    validate_payload_codec(export_codec)?;
14830
14831    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
14832        for event in events {
14833            let event_type = event
14834                .get("event_type")
14835                .or_else(|| event.get("type"))
14836                .and_then(Value::as_str)
14837                .unwrap_or_default();
14838            if let Some(payload) = event.get("payload") {
14839                validate_history_payloads(event_type, payload, export_codec)?;
14840            }
14841        }
14842    }
14843    for signal in export
14844        .get("signals")
14845        .and_then(Value::as_array)
14846        .into_iter()
14847        .flatten()
14848    {
14849        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
14850        validate_payload_codec(codec)?;
14851        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
14852    }
14853    for activity in export
14854        .get("activities")
14855        .and_then(Value::as_array)
14856        .into_iter()
14857        .flatten()
14858    {
14859        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
14860        validate_payload_codec(codec)?;
14861        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
14862        validate_optional_inbound_payload(activity.get("result"), codec)?;
14863    }
14864    Ok(())
14865}
14866
14867fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
14868    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
14869}
14870
14871fn validate_history_payloads(
14872    event_type: &str,
14873    payload: &Value,
14874    fallback_codec: &str,
14875) -> Result<()> {
14876    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
14877    validate_payload_codec(codec)?;
14878    for field in history_payload_fields(event_type) {
14879        validate_optional_inbound_payload(payload.get(*field), codec)?;
14880    }
14881    Ok(())
14882}
14883
14884const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
14885
14886fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
14887    match event_type {
14888        "ActivityCompleted" => &["result"],
14889        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
14890        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
14891        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
14892        "ChildRunCompleted" => &["result", "output"],
14893        "WorkflowCompleted" => &["output"],
14894        "ServiceCallStarted"
14895        | "ServiceCallCompleted"
14896        | "ServiceCallFailed"
14897        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
14898        _ => &[],
14899    }
14900}
14901
14902fn signal_history_payload(payload: &Value) -> Option<&Value> {
14903    SIGNAL_HISTORY_PAYLOAD_FIELDS
14904        .iter()
14905        .find_map(|field| payload.get(*field))
14906}
14907
14908fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
14909    match value.get(field) {
14910        None => Ok(None),
14911        Some(Value::String(codec)) => Ok(Some(codec)),
14912        Some(_) => Err(invalid_payload_envelope()),
14913    }
14914}
14915
14916fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
14917    validate_payload_codec(codec)?;
14918    if let Some(value) = value.filter(|value| !value.is_null()) {
14919        decode_wire_avro_value(value, codec)?;
14920    }
14921    Ok(())
14922}
14923
14924fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
14925    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
14926        invalid_recorded_history(
14927            "parallel_group_metadata_invalid",
14928            sequence,
14929            "non-empty parallel_group_id",
14930            &payload.to_string(),
14931            "parallel-group history is missing its stable identity",
14932        )
14933    })?;
14934    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
14935        invalid_recorded_history(
14936            "parallel_group_metadata_invalid",
14937            sequence,
14938            "activity, child, timer, signal, condition, or mixed group kind",
14939            &payload.to_string(),
14940            "parallel-group history is missing its group kind",
14941        )
14942    })?;
14943    if !matches!(
14944        kind.as_str(),
14945        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
14946    ) {
14947        return Err(invalid_recorded_history(
14948            "parallel_group_metadata_invalid",
14949            sequence,
14950            "activity, child, timer, signal, condition, or mixed group kind",
14951            &kind,
14952            "parallel-group history contains an unsupported group kind",
14953        ));
14954    }
14955    let base_sequence = payload
14956        .get("parallel_group_base_sequence")
14957        .and_then(value_as_u64)
14958        .filter(|value| *value > 0)
14959        .ok_or_else(|| {
14960            invalid_recorded_history(
14961                "parallel_group_metadata_invalid",
14962                sequence,
14963                "positive parallel_group_base_sequence",
14964                &payload.to_string(),
14965                "parallel-group history contains an invalid base sequence",
14966            )
14967        })?;
14968    let size = payload
14969        .get("parallel_group_size")
14970        .and_then(value_as_u64)
14971        .and_then(|value| usize::try_from(value).ok())
14972        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
14973        .ok_or_else(|| {
14974            invalid_recorded_history(
14975                "parallel_group_metadata_invalid",
14976                sequence,
14977                "bounded positive parallel_group_size",
14978                &payload.to_string(),
14979                "parallel-group history contains an invalid group size",
14980            )
14981        })?;
14982    let index = payload
14983        .get("parallel_group_index")
14984        .and_then(value_as_u64)
14985        .and_then(|value| usize::try_from(value).ok())
14986        .filter(|value| *value < size)
14987        .ok_or_else(|| {
14988            invalid_recorded_history(
14989                "parallel_group_metadata_invalid",
14990                sequence,
14991                "parallel_group_index within group bounds",
14992                &payload.to_string(),
14993                "parallel-group history contains an invalid member index",
14994            )
14995        })?;
14996    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
14997        return Err(invalid_recorded_history(
14998            "parallel_group_metadata_invalid",
14999            sequence,
15000            "base sequence plus member index equals workflow sequence",
15001            &payload.to_string(),
15002            "parallel-group path does not preserve durable workflow position",
15003        ));
15004    }
15005    let mode = payload
15006        .get("parallel_group_mode")
15007        .and_then(Value::as_str)
15008        .unwrap_or("all");
15009    if !matches!(mode, "all" | "select") {
15010        return Err(invalid_recorded_history(
15011            "parallel_group_metadata_invalid",
15012            sequence,
15013            "parallel group mode all or select",
15014            mode,
15015            "parallel-group history contains an unsupported group mode",
15016        ));
15017    }
15018    let expected_id = if mode == "select" {
15019        format!("select-calls:{base_sequence}:{size}")
15020    } else {
15021        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
15022    };
15023    if group_id != expected_id {
15024        return Err(invalid_recorded_history(
15025            "parallel_group_metadata_invalid",
15026            sequence,
15027            &expected_id,
15028            &group_id,
15029            "parallel-group history contains an incompatible stable group ID",
15030        ));
15031    }
15032    let selection_member_key = if mode == "select" {
15033        Some(selection_key_from_value(
15034            payload.get("selection_member_key"),
15035            sequence,
15036        )?)
15037    } else {
15038        None
15039    };
15040    let selection_member_index = if mode == "select" {
15041        Some(required_parallel_usize(
15042            payload,
15043            "selection_member_index",
15044            sequence,
15045        )?)
15046    } else {
15047        None
15048    };
15049    let selection_member_base_sequence = if mode == "select" {
15050        Some(
15051            payload
15052                .get("selection_member_base_sequence")
15053                .and_then(value_as_u64)
15054                .filter(|value| *value >= base_sequence)
15055                .ok_or_else(|| {
15056                    invalid_recorded_history(
15057                        "parallel_group_metadata_invalid",
15058                        sequence,
15059                        "selection member base within its group",
15060                        &payload.to_string(),
15061                        "selection history contains an invalid member base sequence",
15062                    )
15063                })?,
15064        )
15065    } else {
15066        None
15067    };
15068    let selection_member_size = if mode == "select" {
15069        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
15070        if member_size == 0 {
15071            return Err(invalid_recorded_history(
15072                "parallel_group_metadata_invalid",
15073                sequence,
15074                "positive selection member size",
15075                &payload.to_string(),
15076                "selection history contains an invalid member size",
15077            ));
15078        }
15079        Some(member_size)
15080    } else {
15081        None
15082    };
15083    let selection_member_kind = if mode == "select" {
15084        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
15085            invalid_recorded_history(
15086                "parallel_group_metadata_invalid",
15087                sequence,
15088                "selection member operation kind",
15089                &payload.to_string(),
15090                "selection history is missing its authored member kind",
15091            )
15092        })?;
15093        if !matches!(
15094            kind.as_str(),
15095            "activity" | "child" | "timer" | "signal" | "condition" | "group"
15096        ) {
15097            return Err(invalid_recorded_history(
15098                "parallel_group_metadata_invalid",
15099                sequence,
15100                "activity, child, timer, signal, condition, or group selection member kind",
15101                &kind,
15102                "selection history contains an unsupported member kind",
15103            ));
15104        }
15105        Some(kind)
15106    } else {
15107        None
15108    };
15109    if let (Some(member_base), Some(member_size)) =
15110        (selection_member_base_sequence, selection_member_size)
15111    {
15112        let member_end = member_base
15113            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
15114            .ok_or_else(|| {
15115                invalid_recorded_history(
15116                    "parallel_group_metadata_invalid",
15117                    sequence,
15118                    "bounded selection member range",
15119                    &payload.to_string(),
15120                    "selection member range overflowed",
15121                )
15122            })?;
15123        let group_end = base_sequence
15124            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
15125            .unwrap_or(u64::MAX);
15126        if sequence < member_base || sequence >= member_end || member_end > group_end {
15127            return Err(invalid_recorded_history(
15128                "parallel_group_metadata_invalid",
15129                sequence,
15130                "workflow sequence within one bounded selection member",
15131                &payload.to_string(),
15132                "selection member range does not contain its durable leaf",
15133            ));
15134        }
15135    }
15136    Ok(ParallelGroupMetadata {
15137        parallel_group_id: group_id,
15138        parallel_group_kind: kind,
15139        parallel_group_base_sequence: base_sequence,
15140        parallel_group_size: size,
15141        parallel_group_index: index,
15142        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15143        selection_member_key,
15144        selection_member_index,
15145        selection_member_base_sequence,
15146        selection_member_size,
15147        selection_member_kind,
15148    })
15149}
15150
15151fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15152    payload
15153        .get(field)
15154        .and_then(value_as_u64)
15155        .and_then(|value| usize::try_from(value).ok())
15156        .ok_or_else(|| {
15157            invalid_recorded_history(
15158                "parallel_group_metadata_invalid",
15159                sequence,
15160                &format!("non-negative integer {field}"),
15161                &payload.to_string(),
15162                "selection history contains invalid member metadata",
15163            )
15164        })
15165}
15166
15167fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15168    match value {
15169        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15170        Some(value) => value_as_u64(value)
15171            .and_then(|value| usize::try_from(value).ok())
15172            .map(SelectionKey::Index)
15173            .ok_or_else(|| {
15174                invalid_recorded_history(
15175                    "selection_member_key_invalid",
15176                    sequence,
15177                    "non-empty string or non-negative integer member key",
15178                    &value.to_string(),
15179                    "selection history contains an invalid member key",
15180                )
15181            }),
15182        None => Err(invalid_recorded_history(
15183            "selection_member_key_missing",
15184            sequence,
15185            "selection_member_key",
15186            "<missing>",
15187            "selection history is missing its stable member key",
15188        )),
15189    }
15190}
15191
15192fn recorded_parallel_group_path(
15193    events: &[&HistoryEvent],
15194    sequence: u64,
15195) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15196    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15197    for event in events {
15198        let payload = &event.payload;
15199        let has_metadata = payload.get("parallel_group_path").is_some()
15200            || payload.get("parallel_group_id").is_some()
15201            || payload.get("parallel_group_kind").is_some()
15202            || payload.get("parallel_group_base_sequence").is_some()
15203            || payload.get("parallel_group_size").is_some()
15204            || payload.get("parallel_group_index").is_some()
15205            || payload.get("parallel_group_mode").is_some()
15206            || payload.get("selection_member_key").is_some();
15207        if !has_metadata {
15208            continue;
15209        }
15210
15211        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15212        let path = match payload.get("parallel_group_path") {
15213            None => vec![top_level.clone()],
15214            Some(Value::Array(entries)) if !entries.is_empty() => entries
15215                .iter()
15216                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15217                .collect::<Result<Vec<_>>>()?,
15218            Some(value) => {
15219                return Err(invalid_recorded_history(
15220                    "parallel_group_metadata_invalid",
15221                    sequence,
15222                    "non-empty parallel_group_path list",
15223                    &value.to_string(),
15224                    "parallel-group history contains an invalid group path",
15225                ));
15226            }
15227        };
15228        if path.last() != Some(&top_level) {
15229            return Err(invalid_recorded_history(
15230                "parallel_group_metadata_invalid",
15231                sequence,
15232                &serde_json::to_string(&path.last()).unwrap_or_default(),
15233                &serde_json::to_string(&top_level).unwrap_or_default(),
15234                "parallel-group top-level fields do not match the innermost path entry",
15235            ));
15236        }
15237        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15238            return Err(invalid_recorded_history(
15239                "parallel_group_history_conflict",
15240                sequence,
15241                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15242                &serde_json::to_string(&path).unwrap_or_default(),
15243                "parallel-group metadata changed between scheduling and resolution history",
15244            ));
15245        }
15246        recorded = Some(path);
15247    }
15248    Ok(recorded)
15249}
15250
15251fn recorded_commands(
15252    events: &[HistoryEvent],
15253    fallback_codec: &str,
15254    parent: WorkflowIdentity,
15255) -> Result<Vec<RecordedCommand>> {
15256    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15257    let mut last_new_sequence = None;
15258
15259    for event in events {
15260        let is_activity = matches!(
15261            event.event_type.as_str(),
15262            "ActivityScheduled"
15263                | "ActivityStarted"
15264                | "ActivityHeartbeatRecorded"
15265                | "ActivityRetryScheduled"
15266                | "ActivityCompleted"
15267                | "ActivityFailed"
15268                | "ActivityCancelled"
15269                | "ActivityTimedOut"
15270        );
15271        let is_workflow_timer = matches!(
15272            event.event_type.as_str(),
15273            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15274        ) && !is_internal_timer_event(event);
15275        let is_child_workflow = matches!(
15276            event.event_type.as_str(),
15277            "ChildWorkflowScheduled"
15278                | "ChildRunStarted"
15279                | "ChildRunCompleted"
15280                | "ChildRunFailed"
15281                | "ChildRunCancelled"
15282                | "ChildRunTerminated"
15283        );
15284        let is_signal_wait = is_recorded_signal_wait_event(event);
15285        let is_condition_wait = is_recorded_condition_wait_event(event);
15286        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15287        let is_side_effect = event.event_type == "SideEffectRecorded";
15288        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15289        let is_memo = event.event_type == "MemoUpserted";
15290        if !is_activity
15291            && !is_workflow_timer
15292            && !is_child_workflow
15293            && !is_signal_wait
15294            && !is_condition_wait
15295            && !is_search_attributes
15296            && !is_side_effect
15297            && !is_version_marker
15298            && !is_memo
15299        {
15300            continue;
15301        }
15302
15303        let sequence = durable_event_sequence(event).ok_or_else(|| {
15304            Error::NonDeterministicReplay(ReplayFailure::new(
15305                "durable_command_sequence_missing",
15306                None,
15307                Some("positive workflow sequence".to_string()),
15308                Some(event.event_type.clone()),
15309                "durable command history event has no workflow sequence",
15310            ))
15311        })?;
15312        if sequence == 0 {
15313            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15314                "durable_command_sequence_invalid",
15315                Some(sequence),
15316                Some("positive workflow sequence".to_string()),
15317                Some(sequence.to_string()),
15318                "durable command history uses an invalid workflow sequence",
15319            )));
15320        }
15321        if !events_by_sequence.contains_key(&sequence) {
15322            if let Some(previous) = last_new_sequence {
15323                if sequence < previous {
15324                    return Err(invalid_recorded_history(
15325                        "durable_command_sequence_mismatch",
15326                        sequence,
15327                        &format!("workflow sequence greater than {previous}"),
15328                        &sequence.to_string(),
15329                        "durable commands are not strictly ordered by their recorded workflow sequence",
15330                    ));
15331                }
15332            }
15333            last_new_sequence = Some(sequence);
15334        }
15335        events_by_sequence.entry(sequence).or_default().push(event);
15336    }
15337
15338    let commands: Vec<RecordedCommand> = events_by_sequence
15339        .into_iter()
15340        .map(|(sequence, sequence_events)| {
15341            let activity_events: Vec<_> = sequence_events
15342                .iter()
15343                .copied()
15344                .filter(|event| event.event_type.starts_with("Activity"))
15345                .collect();
15346            let timer_events: Vec<_> = sequence_events
15347                .iter()
15348                .copied()
15349                .filter(|event| event.event_type.starts_with("Timer"))
15350                .collect();
15351            let child_events: Vec<_> = sequence_events
15352                .iter()
15353                .copied()
15354                .filter(|event| {
15355                    event.event_type == "ChildWorkflowScheduled"
15356                        || event.event_type.starts_with("ChildRun")
15357                })
15358                .collect();
15359            let signal_wait_events: Vec<_> = sequence_events
15360                .iter()
15361                .copied()
15362                .filter(|event| is_recorded_signal_wait_event(event))
15363                .collect();
15364            let condition_wait_events: Vec<_> = sequence_events
15365                .iter()
15366                .copied()
15367                .filter(|event| is_recorded_condition_wait_event(event))
15368                .collect();
15369            let search_attribute_events: Vec<_> = sequence_events
15370                .iter()
15371                .copied()
15372                .filter(|event| event.event_type == "SearchAttributesUpserted")
15373                .collect();
15374            let side_effect_events: Vec<_> = sequence_events
15375                .iter()
15376                .copied()
15377                .filter(|event| event.event_type == "SideEffectRecorded")
15378                .collect();
15379            let version_marker_events: Vec<_> = sequence_events
15380                .iter()
15381                .copied()
15382                .filter(|event| event.event_type == "VersionMarkerRecorded")
15383                .collect();
15384            let memo_events: Vec<_> = sequence_events
15385                .iter()
15386                .copied()
15387                .filter(|event| event.event_type == "MemoUpserted")
15388                .collect();
15389
15390            let command_kind_count = usize::from(!activity_events.is_empty())
15391                + usize::from(!timer_events.is_empty())
15392                + usize::from(!child_events.is_empty())
15393                + usize::from(!signal_wait_events.is_empty())
15394                + usize::from(!condition_wait_events.is_empty())
15395                + usize::from(!search_attribute_events.is_empty())
15396                + usize::from(!side_effect_events.is_empty())
15397                + usize::from(!version_marker_events.is_empty())
15398                + usize::from(!memo_events.is_empty());
15399            if command_kind_count > 1 {
15400                let actual = [
15401                    (!activity_events.is_empty()).then_some("activity"),
15402                    (!timer_events.is_empty()).then_some("timer"),
15403                    (!child_events.is_empty()).then_some("child workflow"),
15404                    (!signal_wait_events.is_empty()).then_some("signal wait"),
15405                    (!condition_wait_events.is_empty()).then_some("condition wait"),
15406                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
15407                    (!side_effect_events.is_empty()).then_some("side effect"),
15408                    (!version_marker_events.is_empty()).then_some("version marker"),
15409                    (!memo_events.is_empty()).then_some("memo upsert"),
15410                ]
15411                .into_iter()
15412                .flatten()
15413                .collect::<Vec<_>>()
15414                .join(" and ");
15415                return Err(invalid_recorded_history(
15416                    "durable_command_sequence_collision",
15417                    sequence,
15418                    "one durable command kind",
15419                    &actual,
15420                    "one workflow sequence records more than one durable command kind",
15421                ));
15422            }
15423
15424            if !activity_events.is_empty() {
15425                let parallel_group_path =
15426                    recorded_parallel_group_path(&activity_events, sequence)?;
15427                let scheduled_count = activity_events
15428                    .iter()
15429                    .filter(|event| event.event_type == "ActivityScheduled")
15430                    .count();
15431                if scheduled_count > 1 {
15432                    return Err(invalid_recorded_history(
15433                        "duplicate_activity_schedule",
15434                        sequence,
15435                        "at most one ActivityScheduled event",
15436                        "multiple ActivityScheduled events",
15437                        "activity history schedules more than one command at one workflow sequence",
15438                    ));
15439                }
15440                let activity_type = activity_events.iter().find_map(|event| {
15441                    event
15442                        .payload
15443                        .get("activity_type")
15444                        .or_else(|| event.payload.get("activity_name"))
15445                        .and_then(Value::as_str)
15446                        .map(str::to_string)
15447                });
15448                if activity_events.iter().filter_map(|event| {
15449                    event
15450                        .payload
15451                        .get("activity_type")
15452                        .or_else(|| event.payload.get("activity_name"))
15453                        .and_then(Value::as_str)
15454                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
15455                    return Err(invalid_recorded_history(
15456                        "activity_identity_mismatch",
15457                        sequence,
15458                        activity_type.as_deref().unwrap_or("one activity identity"),
15459                        "conflicting activity identities",
15460                        "activity lifecycle events at one workflow sequence disagree on identity",
15461                    ));
15462                }
15463                let terminal: Vec<_> = activity_events
15464                    .iter()
15465                    .copied()
15466                    .filter(|event| {
15467                        matches!(
15468                            event.event_type.as_str(),
15469                            "ActivityCompleted"
15470                                | "ActivityFailed"
15471                                | "ActivityCancelled"
15472                                | "ActivityTimedOut"
15473                        )
15474                    })
15475                    .collect();
15476                let duplicate_delivery = terminal.first().is_some_and(|first| {
15477                    terminal.iter().all(|event| {
15478                        event.event_type == first.event_type && event.payload == first.payload
15479                    })
15480                });
15481                if terminal.len() > 1 && !duplicate_delivery {
15482                    return Err(invalid_recorded_history(
15483                        "duplicate_activity_terminal_event",
15484                        sequence,
15485                        "at most one terminal activity event",
15486                        "multiple terminal activity events",
15487                        "activity history settles one command more than once",
15488                    ));
15489                }
15490                let outcome = terminal
15491                    .first()
15492                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
15493                    .transpose()?;
15494                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
15495                let activity_snapshot = activity_events
15496                    .iter()
15497                    .find(|event| event.event_type == "ActivityScheduled")
15498                    .and_then(|event| event.payload.get("activity"))
15499                    .and_then(Value::as_object);
15500                let options = Some(match activity_snapshot {
15501                    Some(activity) => RecordedActivityOptions {
15502                        task_queue: recorded_optional_string(activity, "queue"),
15503                        execution_mode,
15504                        retry_policy: recorded_activity_retry_snapshot(
15505                            activity.get("retry_policy"),
15506                        ),
15507                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15508                    },
15509                    None => RecordedActivityOptions {
15510                        task_queue: RecordedSnapshotValue::Unknown,
15511                        execution_mode,
15512                        retry_policy: recorded_activity_retry_snapshot(None),
15513                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15514                    },
15515                });
15516                return Ok(RecordedCommand::Activity {
15517                    sequence,
15518                    activity_type,
15519                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
15520                    options,
15521                    outcome,
15522                    parallel_group_path,
15523                });
15524            }
15525
15526            if !child_events.is_empty() {
15527                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
15528                let scheduled: Vec<_> = child_events
15529                    .iter()
15530                    .copied()
15531                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
15532                    .collect();
15533                if scheduled.len() != 1 {
15534                    return Err(invalid_recorded_history(
15535                        "child_workflow_schedule_missing_or_duplicate",
15536                        sequence,
15537                        "one ChildWorkflowScheduled event",
15538                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
15539                        "child workflow replay requires exactly one recorded schedule event",
15540                    ));
15541                }
15542                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
15543                let workflow_type = child_events.iter().find_map(|event| {
15544                    event
15545                        .payload
15546                        .get("child_workflow_type")
15547                        .or_else(|| event.payload.get("workflow_type"))
15548                        .and_then(Value::as_str)
15549                        .filter(|value| !value.is_empty())
15550                        .map(str::to_string)
15551                });
15552                if child_events
15553                    .iter()
15554                    .filter_map(|event| {
15555                        event
15556                            .payload
15557                            .get("child_workflow_type")
15558                            .or_else(|| event.payload.get("workflow_type"))
15559                            .and_then(Value::as_str)
15560                    })
15561                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
15562                {
15563                    return Err(invalid_recorded_history(
15564                        "child_workflow_identity_mismatch",
15565                        sequence,
15566                        workflow_type
15567                            .as_deref()
15568                            .unwrap_or("one child workflow type"),
15569                        "conflicting child workflow types",
15570                        "child workflow lifecycle events at one sequence disagree on type",
15571                    ));
15572                }
15573                let mut outcomes = child_workflow_outcomes(
15574                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
15575                    fallback_codec,
15576                    parent.clone(),
15577                )?;
15578                let terminal_events = child_events
15579                    .iter()
15580                    .copied()
15581                    .filter(|event| event.event_type.starts_with("ChildRun"))
15582                    .collect::<Vec<_>>();
15583                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
15584                    terminal_events.iter().all(|event| {
15585                        event.event_type == first.event_type && event.payload == first.payload
15586                    })
15587                });
15588                if outcomes.len() > 1 && !duplicate_delivery {
15589                    return Err(invalid_recorded_history(
15590                        "duplicate_child_workflow_terminal_event",
15591                        sequence,
15592                        "at most one terminal child event",
15593                        "multiple terminal child events",
15594                        "child workflow history settles one command more than once",
15595                    ));
15596                }
15597                return Ok(RecordedCommand::ChildWorkflow {
15598                    sequence,
15599                    workflow_type,
15600                    policies,
15601                    outcome: outcomes.pop(),
15602                    parallel_group_path,
15603                });
15604            }
15605
15606            if !signal_wait_events.is_empty() {
15607                let opened: Vec<_> = signal_wait_events
15608                    .iter()
15609                    .copied()
15610                    .filter(|event| event.event_type == "SignalWaitOpened")
15611                    .collect();
15612                if opened.len() != 1 {
15613                    return Err(invalid_recorded_history(
15614                        "signal_wait_open_missing_or_duplicate",
15615                        sequence,
15616                        "one SignalWaitOpened event",
15617                        &format!("{} SignalWaitOpened events", opened.len()),
15618                        "signal replay requires exactly one canonical wait-open event",
15619                    ));
15620                }
15621
15622                let applied: Vec<_> = signal_wait_events
15623                    .iter()
15624                    .copied()
15625                    .filter(|event| event.event_type == "SignalApplied")
15626                    .collect();
15627                if applied.len() > 1 {
15628                    return Err(invalid_recorded_history(
15629                        "duplicate_signal_wait_apply",
15630                        sequence,
15631                        "at most one SignalApplied event",
15632                        "multiple SignalApplied events",
15633                        "signal history applies one durable wait more than once",
15634                    ));
15635                }
15636
15637                let signal_names = signal_wait_events
15638                    .iter()
15639                    .map(|event| required_signal_wait_name(event, sequence))
15640                    .collect::<Result<Vec<_>>>()?;
15641                let signal_name = signal_names
15642                    .first()
15643                    .expect("signal wait events are not empty")
15644                    .clone();
15645                if signal_names.iter().any(|candidate| candidate != &signal_name) {
15646                    return Err(invalid_recorded_history(
15647                        "signal_wait_identity_mismatch",
15648                        sequence,
15649                        &signal_name,
15650                        "conflicting signal names",
15651                        "signal wait lifecycle events at one workflow sequence disagree on identity",
15652                    ));
15653                }
15654                let value = applied
15655                    .first()
15656                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
15657                    .transpose()?;
15658                return Ok(RecordedCommand::SignalWait {
15659                    sequence,
15660                    signal_name,
15661                    value,
15662                    parallel_group_path: recorded_parallel_group_path(
15663                        &signal_wait_events,
15664                        sequence,
15665                    )?,
15666                });
15667            }
15668
15669            if !condition_wait_events.is_empty() {
15670                return recorded_condition_wait(
15671                    sequence,
15672                    &condition_wait_events,
15673                    events,
15674                );
15675            }
15676
15677            if !search_attribute_events.is_empty() {
15678                if search_attribute_events.len() != 1 {
15679                    return Err(invalid_recorded_history(
15680                        "duplicate_search_attribute_update",
15681                        sequence,
15682                        "one SearchAttributesUpserted event",
15683                        &format!(
15684                            "{} SearchAttributesUpserted events",
15685                            search_attribute_events.len()
15686                        ),
15687                        "search-attribute history records one workflow command more than once",
15688                    ));
15689                }
15690                let payload = &search_attribute_events[0].payload;
15691                let attributes = payload
15692                    .get("attributes")
15693                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
15694                    .cloned()
15695                    .ok_or_else(|| {
15696                        invalid_recorded_history(
15697                            "search_attribute_update_missing",
15698                            sequence,
15699                            "non-empty attributes object",
15700                            "missing or invalid attributes",
15701                            "search-attribute history is missing its recorded mutation",
15702                        )
15703                    })?;
15704                let attribute_types =
15705                    recorded_search_attribute_types(payload, &attributes, sequence)?;
15706                return Ok(RecordedCommand::SearchAttributes {
15707                    sequence,
15708                    attributes,
15709                    attribute_types,
15710                });
15711            }
15712
15713            if !side_effect_events.is_empty() {
15714                if side_effect_events.len() != 1 {
15715                    return Err(invalid_recorded_history(
15716                        "duplicate_side_effect_record",
15717                        sequence,
15718                        "one SideEffectRecorded event",
15719                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
15720                        "side-effect history records one workflow command more than once",
15721                    ));
15722                }
15723                let event = side_effect_events[0];
15724                let result = event.payload.get("result").ok_or_else(|| {
15725                    invalid_recorded_history(
15726                        "side_effect_result_missing",
15727                        sequence,
15728                        "recorded result payload",
15729                        "missing result",
15730                        "side-effect history is missing its recorded value",
15731                    )
15732                })?;
15733                let has_published_envelope = result.as_str().is_some()
15734                    || result.as_object().is_some_and(|envelope| {
15735                        envelope.get("codec").and_then(Value::as_str).is_some()
15736                            && envelope.get("blob").and_then(Value::as_str).is_some()
15737                    });
15738                if !has_published_envelope {
15739                    return Err(invalid_recorded_history(
15740                        "side_effect_payload_malformed",
15741                        sequence,
15742                        "payload blob or {codec, blob} envelope",
15743                        &result.to_string(),
15744                        "side-effect history result does not use a published payload envelope",
15745                    ));
15746                }
15747                let codec = event
15748                    .payload
15749                    .get("payload_codec")
15750                    .and_then(Value::as_str)
15751                    .unwrap_or(fallback_codec);
15752                let value = decode_wire_avro_value(result, codec).map_err(|error| {
15753                    if error.to_string().contains("unsupported_payload_codec") {
15754                        return error;
15755                    }
15756
15757                    invalid_recorded_history(
15758                        "side_effect_payload_incompatible",
15759                        sequence,
15760                        &format!("valid {codec} payload envelope"),
15761                        &error.to_string(),
15762                        "side-effect history payload cannot be decoded with its recorded codec",
15763                    )
15764                })?;
15765                return Ok(RecordedCommand::SideEffect { sequence, value });
15766            }
15767
15768            if !version_marker_events.is_empty() {
15769                if version_marker_events.len() != 1 {
15770                    return Err(invalid_recorded_history(
15771                        "duplicate_version_marker_record",
15772                        sequence,
15773                        "one VersionMarkerRecorded event",
15774                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
15775                        "version-marker history records one workflow command more than once",
15776                    ));
15777                }
15778                let payload = &version_marker_events[0].payload;
15779                let change_id = payload
15780                    .get("change_id")
15781                    .and_then(Value::as_str)
15782                    .filter(|value| !value.is_empty())
15783                    .map(str::to_string)
15784                    .ok_or_else(|| {
15785                        invalid_recorded_history(
15786                            "version_marker_field_missing",
15787                            sequence,
15788                            "non-empty change_id",
15789                            "missing or invalid change_id",
15790                            "version-marker history is missing its stable change ID",
15791                        )
15792                    })?;
15793                let version = required_version_i32(payload, "version", sequence)?;
15794                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
15795                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
15796                if min_supported > max_supported || version < min_supported || version > max_supported {
15797                    return Err(invalid_recorded_history(
15798                        "version_marker_history_range_invalid",
15799                        sequence,
15800                        "min_supported <= version <= max_supported",
15801                        &format!("{min_supported} <= {version} <= {max_supported}"),
15802                        "recorded version marker contains an internally incompatible range",
15803                    ));
15804                }
15805                return Ok(RecordedCommand::VersionMarker {
15806                    sequence,
15807                    change_id,
15808                    version,
15809                });
15810            }
15811
15812            if !memo_events.is_empty() {
15813                if memo_events.len() != 1 {
15814                    return Err(invalid_recorded_history(
15815                        "duplicate_memo_upsert_record",
15816                        sequence,
15817                        "one MemoUpserted event",
15818                        &format!("{} MemoUpserted events", memo_events.len()),
15819                        "memo history records one workflow update more than once",
15820                    ));
15821                }
15822                let payload = &memo_events[0].payload;
15823                let entries = payload.get("entries").cloned().ok_or_else(|| {
15824                    invalid_recorded_history(
15825                        "memo_entries_missing",
15826                        sequence,
15827                        "memo entries object",
15828                        "missing entries",
15829                        "MemoUpserted history is missing replay identity entries",
15830                    )
15831                })?;
15832                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
15833                    invalid_recorded_history(
15834                        "memo_entries_invalid",
15835                        sequence,
15836                        "valid canonical memo entries",
15837                        &error.to_string(),
15838                        "MemoUpserted history contains invalid replay identity entries",
15839                    )
15840                })?;
15841                let merged = payload.get("merged").cloned().ok_or_else(|| {
15842                    invalid_recorded_history(
15843                        "memo_merged_projection_missing",
15844                        sequence,
15845                        "merged memo projection",
15846                        "missing merged",
15847                        "MemoUpserted history is missing its merged projection",
15848                    )
15849                })?;
15850                decode_memo_history_map(&merged, false).map_err(|error| {
15851                    invalid_recorded_history(
15852                        "memo_merged_projection_invalid",
15853                        sequence,
15854                        "valid merged memo projection",
15855                        &error.to_string(),
15856                        "MemoUpserted history contains an invalid merged projection",
15857                    )
15858                })?;
15859
15860                return Ok(RecordedCommand::Memo { sequence, entries });
15861            }
15862            let scheduled: Vec<_> = timer_events
15863                .iter()
15864                .copied()
15865                .filter(|event| event.event_type == "TimerScheduled")
15866                .collect();
15867            let fired: Vec<_> = timer_events
15868                .iter()
15869                .copied()
15870                .filter(|event| event.event_type == "TimerFired")
15871                .collect();
15872            if scheduled.len() != 1 {
15873                return Err(invalid_recorded_history(
15874                    "timer_schedule_missing_or_duplicate",
15875                    sequence,
15876                    "one TimerScheduled event",
15877                    &format!("{} TimerScheduled events", scheduled.len()),
15878                    "timer replay requires exactly one recorded schedule event",
15879                ));
15880            }
15881            if fired.len() > 1 {
15882                return Err(invalid_recorded_history(
15883                    "duplicate_timer_fire",
15884                    sequence,
15885                    "at most one TimerFired event",
15886                    "multiple TimerFired events",
15887                    "timer history contains more than one fire event for a workflow sequence",
15888                ));
15889            }
15890
15891            let scheduled = scheduled[0];
15892            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
15893            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
15894            if let Some(fired) = fired.first() {
15895                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
15896                if fired_timer_id != timer_id {
15897                    return Err(invalid_recorded_history(
15898                        "timer_identity_mismatch",
15899                        sequence,
15900                        &timer_id,
15901                        &fired_timer_id,
15902                        "TimerFired does not correspond to the recorded TimerScheduled event",
15903                    ));
15904                }
15905                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
15906                if fired_delay != delay_seconds {
15907                    return Err(invalid_recorded_history(
15908                        "timer_history_delay_mismatch",
15909                        sequence,
15910                        &delay_seconds.to_string(),
15911                        &fired_delay.to_string(),
15912                        "TimerScheduled and TimerFired record different delays",
15913                    ));
15914                }
15915            }
15916
15917            Ok(RecordedCommand::Timer {
15918                sequence,
15919                delay_seconds,
15920                fired: !fired.is_empty(),
15921                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
15922            })
15923        })
15924        .collect::<Result<_>>()?;
15925
15926    let mut marker_decisions = HashMap::new();
15927    for command in &commands {
15928        if let RecordedCommand::VersionMarker {
15929            sequence,
15930            change_id,
15931            version,
15932        } = command
15933        {
15934            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
15935                if version != first_version {
15936                    return Err(invalid_recorded_history(
15937                        "version_marker_conflict",
15938                        *sequence,
15939                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
15940                        &format!("version {version} at sequence {sequence}"),
15941                        "workflow history contains conflicting decisions for one stable change ID",
15942                    ));
15943                }
15944            } else {
15945                marker_decisions.insert(change_id.clone(), (*version, *sequence));
15946            }
15947        }
15948    }
15949
15950    Ok(commands)
15951}
15952
15953fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
15954    payload
15955        .get(field)
15956        .and_then(Value::as_i64)
15957        .and_then(|value| i32::try_from(value).ok())
15958        .ok_or_else(|| {
15959            invalid_recorded_history(
15960                "version_marker_field_missing",
15961                sequence,
15962                &format!("integer {field}"),
15963                "missing or out-of-range integer",
15964                "version-marker history is missing a required integer field",
15965            )
15966        })
15967}
15968
15969fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
15970    event
15971        .payload
15972        .get("sequence")
15973        .or_else(|| event.payload.get("workflow_sequence"))
15974        .or_else(|| event.raw.get("sequence"))
15975        .or_else(|| event.raw.get("workflow_sequence"))
15976        .and_then(value_as_u64)
15977}
15978
15979fn is_internal_timer_event(event: &HistoryEvent) -> bool {
15980    matches!(
15981        event
15982            .payload
15983            .get("timer_kind")
15984            .or_else(|| event.raw.get("timer_kind"))
15985            .and_then(Value::as_str),
15986        Some("condition_timeout" | "signal_timeout")
15987    )
15988}
15989
15990fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
15991    matches!(
15992        event.event_type.as_str(),
15993        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15994    )
15995}
15996
15997fn recorded_condition_wait(
15998    sequence: u64,
15999    condition_events: &[&HistoryEvent],
16000    all_events: &[HistoryEvent],
16001) -> Result<RecordedCommand> {
16002    let opened = condition_events
16003        .iter()
16004        .copied()
16005        .filter(|event| event.event_type == "ConditionWaitOpened")
16006        .collect::<Vec<_>>();
16007    if opened.len() != 1 {
16008        return Err(invalid_recorded_history(
16009            "condition_wait_open_missing_or_duplicate",
16010            sequence,
16011            "one ConditionWaitOpened event",
16012            &format!("{} ConditionWaitOpened events", opened.len()),
16013            "condition replay requires exactly one canonical wait-open event",
16014        ));
16015    }
16016    let terminal = condition_events
16017        .iter()
16018        .copied()
16019        .filter(|event| {
16020            matches!(
16021                event.event_type.as_str(),
16022                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16023            )
16024        })
16025        .collect::<Vec<_>>();
16026    if terminal.len() > 1 {
16027        return Err(invalid_recorded_history(
16028            "duplicate_condition_wait_terminal_event",
16029            sequence,
16030            "at most one condition terminal event",
16031            "multiple condition terminal events",
16032            "condition history settles one durable wait more than once",
16033        ));
16034    }
16035
16036    let opened = opened[0];
16037    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
16038    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
16039    for event in condition_events
16040        .iter()
16041        .copied()
16042        .filter(|event| !std::ptr::eq(*event, opened))
16043    {
16044        let event_wait_id = required_condition_wait_id(event, sequence)?;
16045        if event_wait_id != condition_wait_id {
16046            return Err(invalid_recorded_history(
16047                "condition_wait_id_mismatch",
16048                sequence,
16049                &condition_wait_id,
16050                &event_wait_id,
16051                "condition lifecycle events at one sequence disagree on wait identity",
16052            ));
16053        }
16054        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
16055        if event_occurrence_id != occurrence_id {
16056            return Err(invalid_recorded_history(
16057                "condition_wait_occurrence_history_mismatch",
16058                sequence,
16059                &occurrence_id,
16060                &event_occurrence_id,
16061                "condition lifecycle events at one sequence disagree on authored occurrence identity",
16062            ));
16063        }
16064    }
16065
16066    let condition_key = optional_non_empty_history_string(opened, "condition_key");
16067    let predicate_identity = opened
16068        .payload
16069        .get("condition_definition_fingerprint")
16070        .and_then(Value::as_str)
16071        .filter(|value| !value.is_empty())
16072        .map(str::to_string)
16073        .ok_or_else(|| {
16074            invalid_recorded_history(
16075                "condition_wait_predicate_fingerprint_missing",
16076                sequence,
16077                "non-empty condition_definition_fingerprint",
16078                &opened.event_type,
16079                "canonical condition history is missing its predicate identity",
16080            )
16081        })?;
16082    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
16083    for event in condition_events
16084        .iter()
16085        .copied()
16086        .filter(|event| !std::ptr::eq(*event, opened))
16087    {
16088        for (field, opened_value) in [
16089            ("condition_key", condition_key.as_deref()),
16090            (
16091                "condition_definition_fingerprint",
16092                Some(predicate_identity.as_str()),
16093            ),
16094        ] {
16095            if let Some(value) = optional_non_empty_history_string(event, field) {
16096                if opened_value.is_some_and(|opened_value| opened_value != value) {
16097                    return Err(invalid_recorded_history(
16098                        "condition_wait_definition_history_mismatch",
16099                        sequence,
16100                        opened_value.unwrap_or_default(),
16101                        &value,
16102                        "condition lifecycle events disagree on the recorded definition",
16103                    ));
16104                }
16105            }
16106        }
16107        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
16108            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
16109                return Err(invalid_recorded_history(
16110                    "condition_wait_definition_history_mismatch",
16111                    sequence,
16112                    &format!("{}s", timeout_seconds.unwrap_or_default()),
16113                    &format!("{event_timeout}s"),
16114                    "condition lifecycle events disagree on the recorded timeout",
16115                ));
16116            }
16117        }
16118    }
16119
16120    let timeout_timer_events = all_events
16121        .iter()
16122        .filter(|event| {
16123            matches!(
16124                event.event_type.as_str(),
16125                "TimerScheduled" | "TimerCancelled" | "TimerFired"
16126            ) && event.payload.get("timer_kind").and_then(Value::as_str)
16127                == Some("condition_timeout")
16128                && event
16129                    .payload
16130                    .get("condition_wait_id")
16131                    .and_then(Value::as_str)
16132                    == Some(condition_wait_id.as_str())
16133        })
16134        .collect::<Vec<_>>();
16135    let scheduled = timeout_timer_events
16136        .iter()
16137        .copied()
16138        .filter(|event| event.event_type == "TimerScheduled")
16139        .collect::<Vec<_>>();
16140    let fired = timeout_timer_events
16141        .iter()
16142        .copied()
16143        .filter(|event| event.event_type == "TimerFired")
16144        .collect::<Vec<_>>();
16145    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16146        return Err(invalid_recorded_history(
16147            "condition_wait_timeout_history_invalid",
16148            sequence,
16149            "one timeout schedule and at most one fire",
16150            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16151            "condition timeout history has a missing or duplicate lifecycle event",
16152        ));
16153    }
16154    if let Some(scheduled) = scheduled.first() {
16155        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16156        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16157        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16158            return Err(invalid_recorded_history(
16159                "condition_wait_timeout_delay_mismatch",
16160                sequence,
16161                &format!("{}s", timeout_seconds.unwrap_or_default()),
16162                &format!("{delay_seconds}s"),
16163                "condition timeout timer differs from the wait definition",
16164            ));
16165        }
16166        if let Some(fired) = fired.first() {
16167            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16168            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16169            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16170                return Err(invalid_recorded_history(
16171                    "condition_wait_timeout_identity_mismatch",
16172                    sequence,
16173                    &format!("{timer_id}:{delay_seconds}s"),
16174                    &format!("{fired_timer_id}:{fired_delay}s"),
16175                    "condition timeout fire does not match its durable schedule",
16176                ));
16177            }
16178        }
16179    }
16180
16181    let result = terminal.first().map(|event| {
16182        if event.event_type == "ConditionWaitTimedOut" {
16183            ConditionWaitResult::TimedOut
16184        } else {
16185            ConditionWaitResult::Satisfied
16186        }
16187    });
16188    let result = if !fired.is_empty() {
16189        if result == Some(ConditionWaitResult::Satisfied) {
16190            return Err(invalid_recorded_history(
16191                "condition_wait_terminal_conflict",
16192                sequence,
16193                "one satisfied or timed-out outcome",
16194                "satisfied event and fired timeout",
16195                "condition history records conflicting terminal outcomes",
16196            ));
16197        }
16198        Some(ConditionWaitResult::TimedOut)
16199    } else {
16200        result
16201    };
16202
16203    Ok(RecordedCommand::ConditionWait {
16204        sequence,
16205        occurrence_id,
16206        condition_key,
16207        predicate_identity,
16208        timeout_seconds,
16209        result,
16210        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16211    })
16212}
16213
16214fn recorded_condition_group_path(
16215    condition_events: &[&HistoryEvent],
16216    all_events: &[HistoryEvent],
16217    sequence: u64,
16218) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16219    let opened = condition_events
16220        .iter()
16221        .copied()
16222        .find(|event| event.event_type == "ConditionWaitOpened")
16223        .expect("canonical condition opener is validated first");
16224    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16225    let previous_events = all_events
16226        .iter()
16227        .take_while(|event| !std::ptr::eq(*event, opened))
16228        .collect::<Vec<_>>();
16229    let originals = previous_events
16230        .iter()
16231        .copied()
16232        .filter(|event| event.event_type == "ConditionWaitOpened")
16233        .filter(|event| {
16234            event
16235                .payload
16236                .get("condition_wait_occurrence_id")
16237                .and_then(Value::as_str)
16238                == Some(occurrence.as_str())
16239        })
16240        .collect::<Vec<_>>();
16241    let Some(original) = originals.first().copied() else {
16242        return recorded_parallel_group_path(condition_events, sequence);
16243    };
16244    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16245    if authored_sequence == sequence {
16246        return recorded_parallel_group_path(condition_events, sequence);
16247    }
16248    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16249    if original_path.is_none() {
16250        return recorded_parallel_group_path(condition_events, sequence);
16251    }
16252    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16253    let identity_matches = [
16254        "condition_key",
16255        "condition_definition_fingerprint",
16256        "timeout_seconds",
16257    ]
16258    .iter()
16259    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16260    let previous = originals
16261        .iter()
16262        .copied()
16263        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16264        .max_by_key(|event| durable_event_sequence(event));
16265    let previously_satisfied = previous.is_some_and(|previous| {
16266        previous_events.iter().any(|event| {
16267            event.event_type == "ConditionWaitSatisfied"
16268                && event.payload.get("condition_wait_id")
16269                    == previous.payload.get("condition_wait_id")
16270                && event.payload.get("condition_wait_occurrence_id")
16271                    == previous.payload.get("condition_wait_occurrence_id")
16272                && durable_event_sequence(event) == durable_event_sequence(previous)
16273        })
16274    });
16275    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16276        return Err(invalid_recorded_history(
16277            "condition_wait_group_reopen_mismatch",
16278            sequence,
16279            "same authored condition and group path after a satisfied physical wait",
16280            &opened.payload.to_string(),
16281            "grouped condition reopen has no matching recorded predecessor",
16282        ));
16283    }
16284    Ok(reopened_path)
16285}
16286
16287fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16288    event
16289        .payload
16290        .get("condition_wait_occurrence_id")
16291        .and_then(Value::as_str)
16292        .filter(|value| !value.is_empty())
16293        .map(str::to_string)
16294        .ok_or_else(|| {
16295            invalid_recorded_history(
16296                "condition_wait_occurrence_id_missing",
16297                sequence,
16298                "non-empty condition_wait_occurrence_id",
16299                &event.event_type,
16300                "condition history is missing authored occurrence identity",
16301            )
16302        })
16303}
16304
16305fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16306    event
16307        .payload
16308        .get("condition_wait_id")
16309        .and_then(Value::as_str)
16310        .filter(|value| !value.is_empty())
16311        .map(str::to_string)
16312        .ok_or_else(|| {
16313            invalid_recorded_history(
16314                "condition_wait_id_missing",
16315                sequence,
16316                "non-empty condition_wait_id",
16317                &event.event_type,
16318                "canonical condition history is missing its durable wait identity",
16319            )
16320        })
16321}
16322
16323fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16324    event
16325        .payload
16326        .get(field)
16327        .and_then(Value::as_str)
16328        .filter(|value| !value.is_empty())
16329        .map(str::to_string)
16330}
16331
16332fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16333    match event.payload.get(field) {
16334        None | Some(Value::Null) => Ok(None),
16335        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16336            invalid_recorded_history(
16337                "condition_wait_definition_invalid",
16338                sequence,
16339                &format!("non-negative integer {field}"),
16340                &value.to_string(),
16341                "condition history contains an invalid numeric definition field",
16342            )
16343        }),
16344    }
16345}
16346
16347fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16348    event
16349        .payload
16350        .get("signal_name")
16351        .or_else(|| event.raw.get("signal_name"))
16352        .and_then(Value::as_str)
16353        .filter(|value| !value.is_empty())
16354        .map(str::to_string)
16355        .ok_or_else(|| {
16356            invalid_recorded_history(
16357                "signal_wait_name_missing",
16358                sequence,
16359                "non-empty signal_name",
16360                &event.event_type,
16361                "canonical signal-wait history is missing its signal identity",
16362            )
16363        })
16364}
16365
16366fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16367    // Applying a buffered control-plane signal has no authored call sequence.
16368    // Its outer sequence orders history events and must not become a wait.
16369    if event.event_type == "SignalApplied"
16370        && event
16371            .payload
16372            .get("signal_wait_id")
16373            .and_then(Value::as_str)
16374            .is_some_and(|id| id.starts_with("signal-command:"))
16375        && event.payload.get("sequence").is_none()
16376        && event.payload.get("workflow_sequence").is_none()
16377    {
16378        return false;
16379    }
16380    matches!(
16381        event.event_type.as_str(),
16382        "SignalWaitOpened" | "SignalApplied"
16383    )
16384}
16385
16386fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
16387    event
16388        .payload
16389        .get(field)
16390        .and_then(Value::as_str)
16391        .filter(|value| !value.is_empty())
16392        .map(str::to_string)
16393        .ok_or_else(|| {
16394            invalid_recorded_history(
16395                "timer_history_field_missing",
16396                sequence,
16397                field,
16398                &event.event_type,
16399                "timer history is missing a required identity field",
16400            )
16401        })
16402}
16403
16404fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
16405    event
16406        .payload
16407        .get(field)
16408        .and_then(value_as_u64)
16409        .ok_or_else(|| {
16410            invalid_recorded_history(
16411                "timer_history_field_missing",
16412                sequence,
16413                field,
16414                &event.event_type,
16415                "timer history is missing a required numeric field",
16416            )
16417        })
16418}
16419
16420fn recorded_search_attribute_types(
16421    payload: &Value,
16422    attributes: &Value,
16423    sequence: u64,
16424) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
16425    let Some(raw_types) = payload.get("attribute_types") else {
16426        // This is the explicit compatibility rule for histories recorded
16427        // before typed identity was persisted. Values still constrain replay;
16428        // the unknown type snapshot does not assert a typed match.
16429        return Ok(RecordedSnapshotValue::Unknown);
16430    };
16431    let Some(raw_types) = raw_types.as_object() else {
16432        return Err(invalid_recorded_history(
16433            "search_attribute_types_malformed",
16434            sequence,
16435            "canonical attribute type map",
16436            &raw_types.to_string(),
16437            "search-attribute history contains malformed type identity",
16438        ));
16439    };
16440    let attribute_keys = attributes
16441        .as_object()
16442        .expect("recorded search attributes were validated as an object");
16443    let mut types = BTreeMap::new();
16444    for (key, value) in raw_types {
16445        let Some(attribute_type) = value.as_str() else {
16446            return Err(invalid_recorded_history(
16447                "search_attribute_types_malformed",
16448                sequence,
16449                "canonical string type name",
16450                &value.to_string(),
16451                "search-attribute history contains a non-string type identity",
16452            ));
16453        };
16454        if !attribute_keys.contains_key(key)
16455            || !matches!(
16456                attribute_type,
16457                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
16458            )
16459        {
16460            return Err(invalid_recorded_history(
16461                "search_attribute_types_malformed",
16462                sequence,
16463                "canonical types for keys present in attributes",
16464                &format!("{key}:{attribute_type}"),
16465                "search-attribute history contains unsupported or orphaned type identity",
16466            ));
16467        }
16468        types.insert(key.clone(), attribute_type.to_string());
16469    }
16470    Ok(RecordedSnapshotValue::Known(types))
16471}
16472
16473fn invalid_recorded_history(
16474    reason: &str,
16475    sequence: u64,
16476    expected: &str,
16477    actual: &str,
16478    message: &str,
16479) -> Error {
16480    Error::NonDeterministicReplay(ReplayFailure::new(
16481        reason,
16482        Some(sequence),
16483        Some(expected.to_string()),
16484        Some(actual.to_string()),
16485        message,
16486    ))
16487}
16488
16489type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
16490
16491fn activity_outcome(
16492    event: &HistoryEvent,
16493    fallback_codec: &str,
16494    recorded_activity_type: Option<String>,
16495) -> Result<ActivityOutcome> {
16496    if event.event_type == "ActivityCompleted" {
16497        let codec = event
16498            .payload
16499            .get("payload_codec")
16500            .and_then(Value::as_str)
16501            .unwrap_or(fallback_codec);
16502        return Ok(Ok(decode_wire_avro_value(
16503            event.payload.get("result").unwrap_or(&Value::Null),
16504            codec,
16505        )?));
16506    }
16507
16508    let payload = &event.payload;
16509    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
16510        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
16511        "ActivityCancelled" => (
16512            ActivityFailureKind::Cancelled,
16513            "cancelled",
16514            "activity was cancelled",
16515        ),
16516        "ActivityTimedOut" => (
16517            ActivityFailureKind::TimedOut,
16518            "timeout",
16519            "activity timed out",
16520        ),
16521        _ => unreachable!("activity_outcome is called only for terminal activity events"),
16522    };
16523    let exception = payload
16524        .get("exception")
16525        .filter(|value| !value.is_null())
16526        .cloned();
16527    let failure_category = payload_string(payload, "failure_category");
16528    let timeout_kind = payload_string(payload, "timeout_kind");
16529    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
16530        ActivityFailureKind::Failed => failure_category
16531            .clone()
16532            .unwrap_or_else(|| fallback_reason.to_string()),
16533        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
16534        ActivityFailureKind::TimedOut => timeout_kind
16535            .clone()
16536            .unwrap_or_else(|| fallback_reason.to_string()),
16537    });
16538    let message = payload_string(payload, "message")
16539        .or_else(|| {
16540            exception
16541                .as_ref()
16542                .and_then(|value| payload_string(value, "message"))
16543        })
16544        .unwrap_or_else(|| fallback_message.to_string());
16545
16546    Ok(Err(ActivityFailure {
16547        kind,
16548        reason,
16549        message,
16550        activity_execution_id: payload_string(payload, "activity_execution_id"),
16551        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
16552        activity_type: payload_string(payload, "activity_type")
16553            .or_else(|| payload_string(payload, "activity_name"))
16554            .or(recorded_activity_type),
16555        activity_class: payload_string(payload, "activity_class"),
16556        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
16557        failure_id: payload_string(payload, "failure_id"),
16558        failure_category,
16559        timeout_kind,
16560        non_retryable: payload
16561            .get("non_retryable")
16562            .and_then(Value::as_bool)
16563            .unwrap_or(false),
16564        exception_type: payload_string(payload, "exception_type").or_else(|| {
16565            exception
16566                .as_ref()
16567                .and_then(|value| payload_string(value, "type"))
16568        }),
16569        exception_class: payload_string(payload, "exception_class").or_else(|| {
16570            exception
16571                .as_ref()
16572                .and_then(|value| payload_string(value, "class"))
16573        }),
16574        code: payload
16575            .get("code")
16576            .filter(|value| !value.is_null())
16577            .cloned(),
16578        exception,
16579    }))
16580}
16581
16582type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
16583
16584fn child_workflow_outcomes(
16585    events: &[HistoryEvent],
16586    fallback_codec: &str,
16587    parent: WorkflowIdentity,
16588) -> Result<Vec<ChildWorkflowOutcome>> {
16589    let mut outcomes = Vec::new();
16590
16591    for event in events {
16592        let kind = match event.event_type.as_str() {
16593            "ChildRunCompleted" => None,
16594            "ChildRunFailed" => Some((
16595                ChildWorkflowFailureKind::Failed,
16596                "child_workflow",
16597                "child workflow failed",
16598            )),
16599            "ChildRunCancelled" => Some((
16600                ChildWorkflowFailureKind::Cancelled,
16601                "cancelled",
16602                "child workflow was cancelled",
16603            )),
16604            "ChildRunTerminated" => Some((
16605                ChildWorkflowFailureKind::Terminated,
16606                "terminated",
16607                "child workflow was terminated",
16608            )),
16609            _ => continue,
16610        };
16611        let payload = &event.payload;
16612        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
16613        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
16614        let child_workflow_type = payload_string(payload, "child_workflow_type");
16615
16616        if let Some((kind, reason, fallback_message)) = kind {
16617            let exception = payload
16618                .get("exception")
16619                .filter(|value| !value.is_null())
16620                .cloned();
16621            let message = payload_string(payload, "message")
16622                .or_else(|| {
16623                    exception
16624                        .as_ref()
16625                        .and_then(|value| payload_string(value, "message"))
16626                })
16627                .unwrap_or_else(|| fallback_message.to_string());
16628            let exception_type = payload_string(payload, "exception_type").or_else(|| {
16629                exception
16630                    .as_ref()
16631                    .and_then(|value| payload_string(value, "type"))
16632            });
16633            let exception_class = payload_string(payload, "exception_class").or_else(|| {
16634                exception
16635                    .as_ref()
16636                    .and_then(|value| payload_string(value, "class"))
16637            });
16638            outcomes.push(Err(ChildWorkflowFailure {
16639                kind,
16640                reason: reason.to_string(),
16641                message,
16642                parent_workflow_id: parent.workflow_id.clone(),
16643                parent_workflow_run_id: parent.run_id.clone(),
16644                child_workflow_id,
16645                child_workflow_run_id,
16646                child_workflow_type,
16647                failure_id: payload_string(payload, "failure_id"),
16648                failure_category: payload_string(payload, "failure_category"),
16649                exception_type,
16650                exception_class,
16651                non_retryable: payload
16652                    .get("non_retryable")
16653                    .and_then(Value::as_bool)
16654                    .unwrap_or(false),
16655                code: payload
16656                    .get("code")
16657                    .filter(|value| !value.is_null())
16658                    .cloned(),
16659                exception,
16660            }));
16661            continue;
16662        }
16663
16664        let codec = payload
16665            .get("payload_codec")
16666            .and_then(Value::as_str)
16667            .unwrap_or(fallback_codec);
16668        let result = payload
16669            .get("result")
16670            .or_else(|| payload.get("output"))
16671            .unwrap_or(&Value::Null);
16672        outcomes.push(Ok(ChildWorkflowAvroResult {
16673            parent: parent.clone(),
16674            child: WorkflowIdentity {
16675                workflow_id: child_workflow_id,
16676                run_id: child_workflow_run_id,
16677            },
16678            child_workflow_type,
16679            result: decode_wire_avro_value(result, codec)?,
16680        }));
16681    }
16682
16683    Ok(outcomes)
16684}
16685
16686fn payload_string(payload: &Value, key: &str) -> Option<String> {
16687    payload
16688        .get(key)
16689        .and_then(Value::as_str)
16690        .filter(|value| !value.is_empty())
16691        .map(str::to_string)
16692}
16693
16694fn recorded_activity_failure_boundary(
16695    ctx: &WorkflowContext,
16696    error: &Error,
16697) -> Option<(u64, String)> {
16698    let Error::ActivityFailed(failure) = error else {
16699        return None;
16700    };
16701    if failure.kind != ActivityFailureKind::Failed {
16702        return None;
16703    }
16704    let activity_execution_id = failure
16705        .activity_execution_id
16706        .as_deref()
16707        .filter(|value| !value.is_empty())?;
16708    let state = ctx.state.lock().ok()?;
16709    let mut matches = state.recorded_commands.iter().filter_map(|command| {
16710        let RecordedCommand::Activity {
16711            sequence,
16712            outcome: Some(Err(recorded_failure)),
16713            ..
16714        } = command
16715        else {
16716            return None;
16717        };
16718        (*sequence > 0 && recorded_failure == failure)
16719            .then_some((*sequence, activity_execution_id.to_string()))
16720    });
16721    let boundary = matches.next()?;
16722    matches.next().is_none().then_some(boundary)
16723}
16724
16725fn workflow_failure_command(
16726    error: &Error,
16727    failed_activity_boundary: Option<(u64, String)>,
16728) -> Value {
16729    let (exception_type, exception_class, properties) = match error {
16730        Error::ActivityFailed(failure) => (
16731            match failure.kind {
16732                ActivityFailureKind::Failed => "ActivityFailed",
16733                ActivityFailureKind::Cancelled => "ActivityCancelled",
16734                ActivityFailureKind::TimedOut => "ActivityTimedOut",
16735            },
16736            "durable_workflow::ActivityFailure",
16737            json!({
16738                "reason": failure.reason,
16739                "activity_execution_id": failure.activity_execution_id,
16740                "activity_attempt_id": failure.activity_attempt_id,
16741                "activity_type": failure.activity_type,
16742                "activity_class": failure.activity_class,
16743                "attempt_number": failure.attempt_number,
16744                "failure_id": failure.failure_id,
16745                "failure_category": failure.failure_category,
16746                "timeout_kind": failure.timeout_kind,
16747                "activity_non_retryable": failure.non_retryable,
16748                "activity_exception_type": failure.exception_type,
16749                "activity_exception_class": failure.exception_class,
16750                "activity_code": failure.code,
16751                "activity_exception": failure.exception,
16752            }),
16753        ),
16754        Error::ChildWorkflowFailed(failure) => (
16755            match failure.kind {
16756                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16757                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16758                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16759            },
16760            "durable_workflow::ChildWorkflowFailure",
16761            json!({
16762                "reason": failure.reason,
16763                "parent_workflow_id": failure.parent_workflow_id,
16764                "parent_workflow_run_id": failure.parent_workflow_run_id,
16765                "child_workflow_id": failure.child_workflow_id,
16766                "child_workflow_run_id": failure.child_workflow_run_id,
16767                "child_workflow_type": failure.child_workflow_type,
16768                "failure_id": failure.failure_id,
16769                "failure_category": failure.failure_category,
16770                "child_exception_type": failure.exception_type,
16771                "child_exception_class": failure.exception_class,
16772                "child_non_retryable": failure.non_retryable,
16773                "child_code": failure.code,
16774                "child_exception": failure.exception,
16775            }),
16776        ),
16777        Error::ParallelFailed(failure) => (
16778            "ParallelFailed",
16779            "durable_workflow::ParallelFailure",
16780            json!({
16781                "parallel_group_id": failure.group_id,
16782                "parallel_member_path": failure.member_path,
16783                "parallel_group_path": failure.group_path,
16784                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
16785                "cause_type": workflow_error_type(&failure.cause),
16786                "cause_message": failure.cause.to_string(),
16787            }),
16788        ),
16789        Error::SagaCompensationFailed(failure) => (
16790            "SagaCompensationFailed",
16791            "durable_workflow::SagaCompensationFailure",
16792            json!({
16793                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
16794                "initiating_failure_message": failure.initiating_failure.to_string(),
16795                "compensation_activity_type": failure.compensation_activity_type,
16796                "compensation_registration_order": failure.compensation_registration_order,
16797                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
16798                "compensation_failure_message": failure.compensation_failure.to_string(),
16799            }),
16800        ),
16801        Error::WorkflowCancellationRequested(_) => (
16802            "WorkflowCancellationRequested",
16803            "durable_workflow::WorkflowCancellationRequested",
16804            json!({"reason": "cancelled"}),
16805        ),
16806        Error::CooperativeCancellationRequested(cancellation) => (
16807            "WorkflowCancellationRequested",
16808            "durable_workflow::CooperativeCancellationRequested",
16809            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
16810                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
16811        ),
16812        Error::CancellationScopeRequested(cancellation) => (
16813            "WorkflowCancellationRequested",
16814            "durable_workflow::CancellationScopeRequested",
16815            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
16816                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
16817                "cancellation":cancellation.context.to_value()}),
16818        ),
16819        Error::NonDeterministicReplay(_) => (
16820            "NonDeterministicReplay",
16821            "durable_workflow::Error",
16822            Value::Null,
16823        ),
16824        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
16825    };
16826    let non_retryable = match error {
16827        Error::ActivityFailed(failure) => failure.non_retryable,
16828        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16829        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16830        Error::SagaCompensationFailed(failure) => {
16831            workflow_error_non_retryable(&failure.compensation_failure)
16832        }
16833        Error::WorkflowCancellationRequested(_)
16834        | Error::CooperativeCancellationRequested(_)
16835        | Error::CancellationScopeRequested(_) => true,
16836        Error::NonDeterministicReplay(_) => true,
16837        _ => false,
16838    };
16839
16840    let mut command = json!({
16841        "type": "fail_workflow",
16842        "message": error.to_string(),
16843        "exception_type": exception_type,
16844        "exception_class": exception_class,
16845        "non_retryable": non_retryable,
16846        "exception": {
16847            "type": exception_type,
16848            "class": exception_class,
16849            "message": error.to_string(),
16850            "properties": properties,
16851        }
16852    });
16853
16854    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
16855        command["failed_step_sequence"] = json!(sequence);
16856        command["failed_activity_execution_id"] = json!(activity_execution_id);
16857    }
16858
16859    command
16860}
16861
16862fn workflow_error_type(error: &Error) -> &'static str {
16863    match error {
16864        Error::ActivityFailed(failure) => match failure.kind {
16865            ActivityFailureKind::Failed => "ActivityFailed",
16866            ActivityFailureKind::Cancelled => "ActivityCancelled",
16867            ActivityFailureKind::TimedOut => "ActivityTimedOut",
16868        },
16869        Error::ChildWorkflowFailed(failure) => match failure.kind {
16870            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
16871            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
16872            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
16873        },
16874        Error::ParallelFailed(_) => "ParallelFailed",
16875        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
16876        Error::WorkflowCancellationRequested(_)
16877        | Error::CooperativeCancellationRequested(_)
16878        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
16879        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
16880        _ => "RustWorkflowError",
16881    }
16882}
16883
16884fn workflow_error_non_retryable(error: &Error) -> bool {
16885    match error {
16886        Error::ActivityFailed(failure) => failure.non_retryable,
16887        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
16888        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
16889        Error::SagaCompensationFailed(failure) => {
16890            workflow_error_non_retryable(&failure.compensation_failure)
16891        }
16892        Error::WorkflowCancellationRequested(_)
16893        | Error::CooperativeCancellationRequested(_)
16894        | Error::CancellationScopeRequested(_)
16895        | Error::NonDeterministicReplay(_) => true,
16896        _ => false,
16897    }
16898}
16899
16900fn workflow_task_integrity_error(error: &Error) -> bool {
16901    matches!(
16902        error,
16903        Error::NonDeterministicReplay(_)
16904            | Error::Protocol(_)
16905            | Error::CancellationScopeExecutionUnavailable
16906            | Error::MissingWorkflowCommandIdentity
16907            | Error::WorkflowStatePoisoned
16908    )
16909}
16910
16911fn decode_signal_event_arguments(
16912    event: &HistoryEvent,
16913    fallback_codec: &str,
16914) -> Result<Vec<AvroValue>> {
16915    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16916    validate_payload_codec(codec)?;
16917    let raw = signal_history_payload(&event.payload);
16918    let decoded = match raw.filter(|value| !value.is_null()) {
16919        Some(value) => decode_wire_avro_value(value, codec)?,
16920        None => AvroValue::Array(Vec::new()),
16921    };
16922    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16923        unreachable!("normalize_avro_arguments always returns an array");
16924    };
16925    Ok(arguments)
16926}
16927
16928fn decode_update_event_arguments(
16929    event: &HistoryEvent,
16930    fallback_codec: &str,
16931) -> Result<Vec<AvroValue>> {
16932    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
16933    validate_payload_codec(codec)?;
16934    let decoded = match event
16935        .payload
16936        .get("arguments")
16937        .filter(|value| !value.is_null())
16938    {
16939        Some(value) => decode_wire_avro_value(value, codec)?,
16940        None => AvroValue::Array(Vec::new()),
16941    };
16942    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
16943        unreachable!("normalize_avro_arguments always returns an array");
16944    };
16945    Ok(arguments)
16946}
16947
16948fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16949    let Some(export_events) = task
16950        .history_export
16951        .as_ref()
16952        .and_then(|export| export.get("history_events"))
16953        .and_then(Value::as_array)
16954    else {
16955        return Ok(());
16956    };
16957
16958    if export_events.len() > task.history_events.len() {
16959        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
16960    }
16961
16962    Ok(())
16963}
16964
16965fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
16966    let Some(export) = task.history_export.as_ref() else {
16967        return Ok(());
16968    };
16969    let signals = export
16970        .get("signals")
16971        .and_then(Value::as_array)
16972        .cloned()
16973        .unwrap_or_default();
16974    let activities = export
16975        .get("activities")
16976        .and_then(Value::as_array)
16977        .cloned()
16978        .unwrap_or_default();
16979    let export_codec = export
16980        .get("payloads")
16981        .and_then(|payloads| payloads.get("codec"))
16982        .and_then(Value::as_str)
16983        .unwrap_or(&task.payload_codec)
16984        .to_string();
16985    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
16986
16987    for event in &mut task.history_events {
16988        if event.event_type == "ActivityCompleted" {
16989            let sequence = event
16990                .payload
16991                .get("sequence")
16992                .or_else(|| event.payload.get("workflow_sequence"))
16993                .and_then(value_as_u64);
16994            let Some(activity) = sequence.and_then(|sequence| {
16995                activities.iter().find(|activity| {
16996                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
16997                })
16998            }) else {
16999                continue;
17000            };
17001            let Some(payload) = event.payload.as_object_mut() else {
17002                continue;
17003            };
17004            if missing_payload(payload.get("result")) {
17005                if let Some(result) = activity
17006                    .get("result")
17007                    .filter(|value| !missing_payload(Some(value)))
17008                {
17009                    payload.insert("result".to_string(), result.clone());
17010                }
17011            }
17012            for field in ["payload_codec", "activity_type"] {
17013                if payload
17014                    .get(field)
17015                    .and_then(Value::as_str)
17016                    .unwrap_or_default()
17017                    .is_empty()
17018                {
17019                    if let Some(value) = activity.get(field) {
17020                        payload.insert(field.to_string(), value.clone());
17021                    }
17022                }
17023            }
17024            continue;
17025        }
17026
17027        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
17028            continue;
17029        }
17030        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17031        let command_id = event
17032            .payload
17033            .get("workflow_command_id")
17034            .or_else(|| event.raw.get("workflow_command_id"))
17035            .and_then(Value::as_str);
17036        let signal_name = event
17037            .payload
17038            .get("signal_name")
17039            .and_then(Value::as_str)
17040            .unwrap_or_default()
17041            .to_string();
17042        let matched = signals
17043            .iter()
17044            .find(|signal| {
17045                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
17046            })
17047            .or_else(|| {
17048                signals.iter().find(|signal| {
17049                    command_id.is_some()
17050                        && signal.get("command_id").and_then(Value::as_str) == command_id
17051                })
17052            })
17053            .or_else(|| {
17054                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
17055                let signal = signals
17056                    .iter()
17057                    .filter(|signal| {
17058                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
17059                    })
17060                    .nth(*offset);
17061                if signal.is_some() {
17062                    *offset += 1;
17063                }
17064                signal
17065            });
17066        let Some(signal) = matched else {
17067            continue;
17068        };
17069        let signal_codec = signal
17070            .get("payload_codec")
17071            .and_then(Value::as_str)
17072            .unwrap_or(&export_codec);
17073        let Some(payload) = event.payload.as_object_mut() else {
17074            continue;
17075        };
17076        if missing_payload(payload.get("arguments")) {
17077            if let Some(arguments) = signal
17078                .get("arguments")
17079                .filter(|value| !missing_payload(Some(value)))
17080            {
17081                let envelope = match arguments {
17082                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
17083                    other => other.clone(),
17084                };
17085                payload.insert("arguments".to_string(), envelope);
17086            }
17087        }
17088        if payload
17089            .get("payload_codec")
17090            .and_then(Value::as_str)
17091            .unwrap_or_default()
17092            .is_empty()
17093        {
17094            payload.insert("payload_codec".to_string(), json!(signal_codec));
17095        }
17096    }
17097
17098    Ok(())
17099}
17100
17101fn missing_payload(value: Option<&Value>) -> bool {
17102    match value {
17103        None | Some(Value::Null) => true,
17104        Some(Value::String(value)) => value.is_empty(),
17105        Some(_) => false,
17106    }
17107}
17108
17109fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
17110    history_signal_events(
17111        &task.history_events,
17112        task.history_export.as_ref(),
17113        &task.payload_codec,
17114    )
17115}
17116
17117fn history_signal_events(
17118    history_events: &[HistoryEvent],
17119    history_export: Option<&Value>,
17120    payload_codec: &str,
17121) -> Result<Vec<QuerySignal>> {
17122    let export_signals = history_export
17123        .and_then(|export| export.get("signals"))
17124        .and_then(Value::as_array)
17125        .cloned()
17126        .unwrap_or_default();
17127    let export_codec = history_export
17128        .and_then(|export| export.get("payloads"))
17129        .and_then(|payloads| payloads.get("codec"))
17130        .and_then(Value::as_str)
17131        .unwrap_or(payload_codec);
17132    let mut name_offsets: HashMap<String, usize> = HashMap::new();
17133    let mut signals: Vec<QuerySignal> = Vec::new();
17134    let mut signal_indices = HashMap::new();
17135    let mut command_indices = HashMap::new();
17136
17137    for event in history_events {
17138        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
17139            continue;
17140        }
17141
17142        let name = event
17143            .payload
17144            .get("signal_name")
17145            .and_then(Value::as_str)
17146            .unwrap_or_default();
17147        if name.is_empty() {
17148            continue;
17149        }
17150        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17151        let command_id = event
17152            .payload
17153            .get("workflow_command_id")
17154            .or_else(|| event.raw.get("workflow_command_id"))
17155            .and_then(Value::as_str);
17156        let matched_export = export_signals
17157            .iter()
17158            .find(|candidate| {
17159                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17160            })
17161            .or_else(|| {
17162                export_signals.iter().find(|candidate| {
17163                    command_id.is_some()
17164                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17165                })
17166            })
17167            .or_else(|| {
17168                let offset = name_offsets.entry(name.to_string()).or_default();
17169                let candidate = export_signals
17170                    .iter()
17171                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17172                    .nth(*offset);
17173                if candidate.is_some() {
17174                    *offset += 1;
17175                }
17176                candidate
17177            });
17178        let codec = event
17179            .payload
17180            .get("payload_codec")
17181            .and_then(Value::as_str)
17182            .or_else(|| {
17183                matched_export
17184                    .and_then(|signal| signal.get("payload_codec"))
17185                    .and_then(Value::as_str)
17186            })
17187            .unwrap_or(export_codec);
17188        let raw_arguments = signal_history_payload(&event.payload)
17189            .filter(|value| !value.is_null())
17190            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17191        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
17192        let workflow_sequence = event
17193            .payload
17194            .get("workflow_sequence")
17195            .and_then(value_as_u64)
17196            .or_else(|| {
17197                matched_export
17198                    .and_then(|signal| signal.get("workflow_sequence"))
17199                    .and_then(value_as_u64)
17200            });
17201
17202        let id = signal_id.or_else(|| {
17203            matched_export
17204                .and_then(|signal| signal.get("id"))
17205                .and_then(Value::as_str)
17206        });
17207        let command_id = command_id.or_else(|| {
17208            matched_export
17209                .and_then(|signal| signal.get("command_id"))
17210                .and_then(Value::as_str)
17211        });
17212        let duplicate = id
17213            .and_then(|id| signal_indices.get(id))
17214            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
17215            .copied();
17216        let index = duplicate.unwrap_or(signals.len());
17217        if let Some(index) = duplicate {
17218            let original = &mut signals[index];
17219            let same_arguments = if event.event_type == "SignalApplied" {
17220                if let Some(value) = event.payload.get("value") {
17221                    let expected = match original.avro_arguments.as_slice() {
17222                        [] => AvroValue::Boolean(true),
17223                        [value] => value.clone(),
17224                        values => AvroValue::Array(values.to_vec()),
17225                    };
17226                    let applied = decode_wire_avro_value(value, codec)?;
17227                    applied == expected
17228                        || applied == AvroValue::Array(original.avro_arguments.clone())
17229                } else {
17230                    original.avro_arguments == avro_arguments
17231                }
17232            } else {
17233                original.avro_arguments == avro_arguments
17234            };
17235            if original.name != name
17236                || !same_arguments
17237                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
17238            {
17239                return Err(Error::Codec("conflicting committed signal identity".into()));
17240            }
17241            if original.id.is_none() {
17242                original.id = id.map(str::to_string);
17243            }
17244            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
17245        } else {
17246            signals.push(QuerySignal {
17247                id: id.map(str::to_string),
17248                name: name.to_string(),
17249                arguments,
17250                avro_arguments,
17251                workflow_sequence,
17252            });
17253        }
17254        if let Some(id) = id {
17255            signal_indices.insert(id.to_string(), index);
17256        }
17257        if let Some(id) = command_id {
17258            command_indices.insert(id.to_string(), index);
17259        }
17260    }
17261
17262    if signals.is_empty() {
17263        for signal in export_signals {
17264            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17265                continue;
17266            }
17267            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17268                continue;
17269            };
17270            let codec = signal
17271                .get("payload_codec")
17272                .and_then(Value::as_str)
17273                .unwrap_or(export_codec);
17274            let (arguments, avro_arguments) =
17275                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17276            signals.push(QuerySignal {
17277                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17278                name: name.to_string(),
17279                arguments,
17280                avro_arguments,
17281                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17282            });
17283        }
17284        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17285    }
17286
17287    Ok(signals)
17288}
17289
17290fn decode_query_signal_arguments(
17291    raw: Option<&Value>,
17292    codec: &str,
17293) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17294    validate_payload_codec(codec)?;
17295    let decoded = match raw.filter(|value| !value.is_null()) {
17296        Some(value) => decode_wire_avro_value(value, codec)?,
17297        None => AvroValue::Array(Vec::new()),
17298    };
17299    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17300        unreachable!("normalize_avro_arguments always returns an array");
17301    };
17302    let arguments = avro_arguments
17303        .iter()
17304        .cloned()
17305        .map(AvroValue::into_json)
17306        .collect::<Result<Vec<_>>>()?;
17307    Ok((arguments, avro_arguments))
17308}
17309
17310fn value_as_u64(value: &Value) -> Option<u64> {
17311    value
17312        .as_u64()
17313        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17314}
17315
17316#[cfg(test)]
17317mod tests {
17318    use super::*;
17319    mod activity_cancellation_policies;
17320    mod cancellation_scope_admission;
17321    mod cancellation_scope_authoring;
17322    mod cancellation_scope_history;
17323    mod cancellation_scope_opening;
17324    mod cancellation_scope_replay;
17325    mod child_workflow_policies;
17326    mod cooperative_cancellation;
17327    mod local_activity;
17328    mod runtime_payloads;
17329    mod runtime_uploads;
17330    mod worker_session;
17331    use std::{
17332        fs,
17333        io::{Read, Write},
17334        net::{SocketAddr, TcpListener, TcpStream},
17335        process::Command as ProcessCommand,
17336        sync::atomic::AtomicUsize,
17337        thread,
17338    };
17339
17340    #[derive(Clone, Copy, Debug)]
17341    enum InvalidTaskPayloadCodec {
17342        Missing,
17343        Null,
17344        NonString,
17345    }
17346
17347    impl InvalidTaskPayloadCodec {
17348        fn label(self) -> &'static str {
17349            match self {
17350                Self::Missing => "missing",
17351                Self::Null => "null",
17352                Self::NonString => "non-string",
17353            }
17354        }
17355
17356        fn apply(self, task: &mut Value) {
17357            let task = task.as_object_mut().expect("task fixture object");
17358            match self {
17359                Self::Missing => {
17360                    task.remove("payload_codec");
17361                }
17362                Self::Null => {
17363                    task.insert("payload_codec".to_string(), Value::Null);
17364                }
17365                Self::NonString => {
17366                    task.insert("payload_codec".to_string(), json!(42));
17367                }
17368            }
17369        }
17370    }
17371
17372    fn fixture_envelope(value: Value) -> Value {
17373        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
17374    }
17375
17376    fn fixture_blob(value: Value) -> String {
17377        encode_payload(&value, DEFAULT_CODEC)
17378            .expect("encode Avro test fixture")
17379            .blob
17380    }
17381
17382    #[test]
17383    fn client_builder_rejects_the_sdk_owned_api_suffix() {
17384        for base_url in [
17385            "http://127.0.0.1:8080/api",
17386            "http://localhost:8080/api/",
17387            "https://runtime.example.test/namespaces/orders/api",
17388        ] {
17389            let error = Client::builder(base_url)
17390                .build()
17391                .expect_err("SDK-owned /api suffix must be rejected during build");
17392
17393            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
17394            assert!(
17395                error.to_string().contains("SDK appends /api automatically"),
17396                "the validation error must explain how to fix the endpoint"
17397            );
17398        }
17399    }
17400
17401    #[test]
17402    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
17403        for (base_url, expected) in [
17404            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
17405            (
17406                "http://localhost:8080/durable-workflow/",
17407                "http://localhost:8080/durable-workflow",
17408            ),
17409            (
17410                "https://runtime.example.test/namespaces/orders",
17411                "https://runtime.example.test/namespaces/orders",
17412            ),
17413            (
17414                "https://runtime.example.test/gateway/api/namespaces/orders",
17415                "https://runtime.example.test/gateway/api/namespaces/orders",
17416            ),
17417            (
17418                "https://api.example.test/runtime/orders/",
17419                "https://api.example.test/runtime/orders",
17420            ),
17421        ] {
17422            let client = Client::builder(base_url)
17423                .build()
17424                .expect("Server and Cloud runtime base URL must remain valid");
17425
17426            assert_eq!(client.base_url, expected);
17427        }
17428    }
17429
17430    #[test]
17431    fn workflow_completion_uses_the_additive_command_protocol_floor() {
17432        assert_eq!(
17433            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
17434            WORKER_PROTOCOL_VERSION
17435        );
17436        assert_eq!(
17437            workflow_completion_protocol_version(&[json!({
17438                "type": "upsert_search_attributes",
17439                "attributes": {"OrderStatus": "waiting"},
17440            })]),
17441            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
17442        );
17443        assert_eq!(
17444            workflow_completion_protocol_version(&[json!({
17445                "type": "upsert_search_attributes",
17446                "attributes": {"OrderStatus": "waiting"},
17447                "attribute_types": {"OrderStatus": "keyword"},
17448            })]),
17449            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
17450        );
17451        assert_eq!(
17452            workflow_completion_protocol_version(&[
17453                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
17454                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17455            ]),
17456            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
17457        );
17458        assert_eq!(
17459            workflow_completion_protocol_version(&[
17460                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
17461                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17462            ]),
17463            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
17464        );
17465        assert_eq!(
17466            workflow_completion_protocol_version(&[json!({
17467                "type": "open_condition_wait",
17468                "condition_wait_occurrence_id": "rust:condition-wait:0",
17469                "condition_key": "ready",
17470            })]),
17471            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17472        );
17473        assert_eq!(
17474            workflow_completion_protocol_version_with_message_streams(
17475                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
17476                true,
17477            ),
17478            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
17479        );
17480        assert_eq!(
17481            workflow_completion_protocol_version_with_message_streams(
17482                &[json!({
17483                    "type": "open_condition_wait",
17484                    "condition_wait_occurrence_id": "rust:condition-wait:0",
17485                    "condition_key": "ready",
17486                })],
17487                true,
17488            ),
17489            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17490        );
17491    }
17492
17493    #[test]
17494    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
17495        let manifest = portable_worker_affinity_capability_manifest();
17496
17497        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
17498            assert_eq!(manifest[capability]["supported"], json!(false));
17499            assert_eq!(
17500                manifest[capability]["minimum_protocol_version"],
17501                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
17502            );
17503            assert!(manifest[capability]["reason"]
17504                .as_str()
17505                .is_some_and(|reason| !reason.is_empty()));
17506        }
17507    }
17508
17509    fn typed_fidelity_probe() -> AvroValue {
17510        AvroValue::Map(BTreeMap::from([
17511            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
17512            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
17513            (
17514                "numeric".to_string(),
17515                AvroValue::Map(BTreeMap::from([
17516                    ("0".to_string(), AvroValue::String("zero".to_string())),
17517                    ("1".to_string(), AvroValue::String("one".to_string())),
17518                ])),
17519            ),
17520            (
17521                "nested".to_string(),
17522                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
17523                    "enabled".to_string(),
17524                    AvroValue::Boolean(true),
17525                )]))]),
17526            ),
17527            (
17528                "projection_collisions".to_string(),
17529                AvroValue::Array(projection_collision_probe()),
17530            ),
17531        ]))
17532    }
17533
17534    fn projection_collision_probe() -> Vec<AvroValue> {
17535        vec![
17536            AvroValue::Map(BTreeMap::from([
17537                ("$type".to_string(), AvroValue::String("bytes".to_string())),
17538                (
17539                    "base64".to_string(),
17540                    AvroValue::String("ordinary user text".to_string()),
17541                ),
17542            ])),
17543            AvroValue::Map(BTreeMap::from([
17544                ("$type".to_string(), AvroValue::String("map".to_string())),
17545                (
17546                    "entries".to_string(),
17547                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
17548                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
17549                        (
17550                            "value".to_string(),
17551                            AvroValue::String("user map".to_string()),
17552                        ),
17553                    ]))]),
17554                ),
17555            ])),
17556        ]
17557    }
17558
17559    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17560    struct TypedContract {
17561        nested: TypedNested,
17562        mode: TypedMode,
17563        optional: Option<String>,
17564        absent: Option<String>,
17565        items: Vec<i64>,
17566        labels: BTreeMap<String, String>,
17567        bytes: serde_bytes::ByteBuf,
17568        signed: i64,
17569        finite: f64,
17570    }
17571
17572    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17573    struct TypedNested {
17574        enabled: bool,
17575    }
17576
17577    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17578    enum TypedMode {
17579        Detailed { label: String },
17580    }
17581
17582    fn typed_contract() -> TypedContract {
17583        TypedContract {
17584            nested: TypedNested { enabled: true },
17585            mode: TypedMode::Detailed {
17586                label: "compiler-checked".to_string(),
17587            },
17588            optional: Some("present".to_string()),
17589            absent: None,
17590            items: vec![i64::MIN, 0, i64::MAX],
17591            labels: BTreeMap::from([
17592                ("language".to_string(), "rust".to_string()),
17593                ("wire".to_string(), "avro".to_string()),
17594            ]),
17595            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
17596            signed: -9_223_372_036_854_775_000,
17597            finite: 12.5,
17598        }
17599    }
17600
17601    #[derive(Clone, Debug, Default, PartialEq)]
17602    struct ReplayCounterState {
17603        loaded: Option<String>,
17604        count: i64,
17605        finished: bool,
17606    }
17607
17608    fn replay_counter_worker() -> Worker {
17609        let client = Client::new("http://127.0.0.1:8080").expect("client");
17610        let mut worker = Worker::new(client, "rust-workers");
17611        worker.register_replayed_workflow(
17612            "replay-counter",
17613            ReplayCounterState::default,
17614            |ctx, _input, state| async move {
17615                let loaded = ctx.activity("load-counter", json!([])).await?;
17616                state.update(|current| {
17617                    current.loaded = loaded.as_str().map(str::to_string);
17618                })?;
17619                for _ in 0..2 {
17620                    let signal = ctx.wait_signal("increment").await?;
17621                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
17622                    state.update(|current| current.count += amount)?;
17623                }
17624                state.update(|current| current.finished = true)?;
17625                state.read(|current| Ok(json!(current.count)))?
17626            },
17627        );
17628        worker.register_replayed_query::<ReplayCounterState, _, _>(
17629            "replay-counter",
17630            "current",
17631            |_ctx, state, _args| async move {
17632                Ok(json!({
17633                    "loaded": state.loaded,
17634                    "count": state.count,
17635                    "finished": state.finished,
17636                }))
17637            },
17638        );
17639        worker.register_replayed_query::<ReplayCounterState, _, _>(
17640            "replay-counter",
17641            "detached-mutation",
17642            |_ctx, state, _args| async move {
17643                let mut detached = (*state).clone();
17644                detached.count = 999;
17645                Ok(json!(detached.count))
17646            },
17647        );
17648        worker.register_replayed_query::<ReplayCounterState, _, _>(
17649            "replay-counter",
17650            "failed-mutation",
17651            |_ctx, state, _args| async move {
17652                let mut detached = (*state).clone();
17653                detached.count = 999;
17654                Err(Error::WorkerLoop("query refused".to_string()))
17655            },
17656        );
17657        worker
17658    }
17659
17660    fn replay_counter_query(
17661        query_name: &str,
17662        history_events: Value,
17663        run_status: &str,
17664    ) -> QueryTask {
17665        let arguments = fixture_envelope(json!([]));
17666        serde_json::from_value(json!({
17667            "query_task_id": format!("query-{query_name}"),
17668            "workflow_type": "replay-counter",
17669            "query_name": query_name,
17670            "payload_codec": DEFAULT_CODEC,
17671            "workflow_arguments": arguments.clone(),
17672            "query_arguments": arguments,
17673            "history_events": history_events,
17674            "run_status": run_status,
17675        }))
17676        .expect("query task")
17677    }
17678
17679    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
17680        workflow_context_with_codec(history, DEFAULT_CODEC)
17681    }
17682
17683    fn workflow_context_with_codec(
17684        history: Vec<HistoryEvent>,
17685        payload_codec: &str,
17686    ) -> WorkflowContext {
17687        WorkflowContext {
17688            cancellation_scope_id: "root".into(),
17689            state: Arc::new(Mutex::new(
17690                WorkflowState::new_with_identity(
17691                    history,
17692                    None,
17693                    None,
17694                    "rust-workers".to_string(),
17695                    payload_codec.to_string(),
17696                    None,
17697                )
17698                .expect("valid workflow history"),
17699            )),
17700        }
17701    }
17702
17703    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
17704        HistoryEvent {
17705            event_type: event_type.to_string(),
17706            payload,
17707            raw: HashMap::new(),
17708        }
17709    }
17710
17711    fn parallel_path_entry(
17712        kind: &str,
17713        base: u64,
17714        size: usize,
17715        index: usize,
17716    ) -> ParallelGroupMetadata {
17717        parallel_group_entry(base, size, index, kind)
17718    }
17719
17720    fn parallel_history_event(
17721        event_type: &str,
17722        sequence: u64,
17723        identity_field: &str,
17724        identity: &str,
17725        path: Vec<ParallelGroupMetadata>,
17726        result: Option<Value>,
17727    ) -> HistoryEvent {
17728        let mut payload = serde_json::Map::from_iter([
17729            ("sequence".to_string(), json!(sequence)),
17730            (identity_field.to_string(), json!(identity)),
17731        ]);
17732        let inner = path.last().expect("parallel history path");
17733        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
17734        payload.insert("parallel_group_path".to_string(), json!(path));
17735        if let Some(result) = result {
17736            let field = if event_type == "ChildRunCompleted" {
17737                "result"
17738            } else {
17739                "result"
17740            };
17741            payload.insert(field.to_string(), fixture_envelope(result));
17742            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
17743        }
17744        history_event(event_type, Value::Object(payload))
17745    }
17746
17747    fn nested_parallel_operations() -> Vec<ParallelOperation> {
17748        vec![
17749            ParallelOperation::activity("first", json!([])),
17750            ParallelOperation::group(vec![
17751                ParallelOperation::child_workflow(
17752                    "second",
17753                    ChildWorkflowOptions::new("child-workers"),
17754                    json!([]),
17755                ),
17756                ParallelOperation::activity("third", json!([])),
17757            ]),
17758        ]
17759    }
17760
17761    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
17762        let outer = [
17763            parallel_path_entry("mixed", 1, 3, 0),
17764            parallel_path_entry("mixed", 1, 3, 1),
17765            parallel_path_entry("mixed", 1, 3, 2),
17766        ];
17767        [
17768            vec![outer[0].clone()],
17769            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
17770            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
17771        ]
17772    }
17773
17774    #[test]
17775    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
17776        let ctx = workflow_context(Vec::new());
17777        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17778        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17779
17780        assert!(matches!(
17781            call.as_mut().poll(&mut task_context),
17782            Poll::Pending
17783        ));
17784        let commands = ctx.take_commands().expect("parallel commands");
17785        assert_eq!(
17786            commands
17787                .iter()
17788                .map(|command| command["type"].as_str().unwrap_or_default())
17789                .collect::<Vec<_>>(),
17790            [
17791                "schedule_activity",
17792                "start_child_workflow",
17793                "schedule_activity"
17794            ]
17795        );
17796        let paths = nested_parallel_paths();
17797        for (command, path) in commands.iter().zip(paths) {
17798            assert_eq!(command["parallel_group_path"], json!(path));
17799            assert_eq!(
17800                command["parallel_group_id"],
17801                json!(path.last().expect("inner group").parallel_group_id)
17802            );
17803        }
17804    }
17805
17806    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
17807        let paths = nested_parallel_paths();
17808        let third = parallel_history_event(
17809            "ActivityCompleted",
17810            3,
17811            "activity_type",
17812            "third",
17813            paths[2].clone(),
17814            Some(json!("three")),
17815        );
17816        vec![
17817            parallel_history_event(
17818                "ActivityCompleted",
17819                1,
17820                "activity_type",
17821                "first",
17822                paths[0].clone(),
17823                Some(json!("one")),
17824            ),
17825            parallel_history_event(
17826                "ChildWorkflowScheduled",
17827                2,
17828                "child_workflow_type",
17829                "second",
17830                paths[1].clone(),
17831                None,
17832            ),
17833            parallel_history_event(
17834                "ChildRunCompleted",
17835                2,
17836                "child_workflow_type",
17837                "second",
17838                paths[1].clone(),
17839                Some(json!("two")),
17840            ),
17841            third.clone(),
17842            third,
17843        ]
17844    }
17845
17846    #[test]
17847    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
17848        for _restart_or_completed_replay in 0..2 {
17849            let ctx = workflow_context(completed_nested_parallel_history());
17850            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17851            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17852            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
17853                panic!("completed nested parallel history must replay");
17854            };
17855            assert_eq!(
17856                results,
17857                vec![
17858                    ParallelResult::Activity(json!("one")),
17859                    ParallelResult::Group(vec![
17860                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
17861                            parent: WorkflowIdentity {
17862                                workflow_id: None,
17863                                run_id: None,
17864                            },
17865                            child: WorkflowIdentity {
17866                                workflow_id: None,
17867                                run_id: None,
17868                            },
17869                            child_workflow_type: Some("second".to_string()),
17870                            result: json!("two"),
17871                        }),
17872                        ParallelResult::Activity(json!("three")),
17873                    ]),
17874                ]
17875            );
17876            assert!(ctx.take_commands().expect("commands").is_empty());
17877            ctx.ensure_history_consumed().expect("history consumed");
17878        }
17879    }
17880
17881    #[test]
17882    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
17883        let paths = nested_parallel_paths();
17884        let history = vec![
17885            parallel_history_event(
17886                "ActivityCompleted",
17887                1,
17888                "activity_type",
17889                "first",
17890                paths[0].clone(),
17891                Some(json!("one")),
17892            ),
17893            parallel_history_event(
17894                "ChildWorkflowScheduled",
17895                2,
17896                "child_workflow_type",
17897                "second",
17898                paths[1].clone(),
17899                None,
17900            ),
17901            parallel_history_event(
17902                "ChildRunFailed",
17903                2,
17904                "child_workflow_type",
17905                "second",
17906                paths[1].clone(),
17907                None,
17908            ),
17909            parallel_history_event(
17910                "ActivityCompleted",
17911                3,
17912                "activity_type",
17913                "third",
17914                paths[2].clone(),
17915                Some(json!("late")),
17916            ),
17917        ];
17918        let ctx = workflow_context(history);
17919        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17920        let mut task_context = TaskContext::from_waker(noop_waker_ref());
17921        let outcome = call.as_mut().poll(&mut task_context);
17922        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
17923            panic!("one failed child must return a typed partial failure: {outcome:?}");
17924        };
17925        assert_eq!(failure.member_path, [1, 0]);
17926        assert_eq!(failure.group_id, "parallel-calls:1:3");
17927        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
17928        assert_eq!(
17929            failure
17930                .completed
17931                .iter()
17932                .map(|completion| completion.member_path.clone())
17933                .collect::<Vec<_>>(),
17934            [vec![0], vec![1, 1]]
17935        );
17936    }
17937
17938    #[test]
17939    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
17940        let paths = nested_parallel_paths();
17941        let history = vec![
17942            parallel_history_event(
17943                "ActivityScheduled",
17944                1,
17945                "activity_type",
17946                "first",
17947                paths[0].clone(),
17948                None,
17949            ),
17950            parallel_history_event(
17951                "ChildWorkflowScheduled",
17952                2,
17953                "child_workflow_type",
17954                "second",
17955                paths[1].clone(),
17956                None,
17957            ),
17958            parallel_history_event(
17959                "ActivityScheduled",
17960                3,
17961                "activity_type",
17962                "third",
17963                paths[2].clone(),
17964                None,
17965            ),
17966        ];
17967        for _restart in 0..2 {
17968            let ctx = workflow_context(history.clone());
17969            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
17970            let mut task_context = TaskContext::from_waker(noop_waker_ref());
17971            let outcome = call.as_mut().poll(&mut task_context);
17972            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
17973            assert!(ctx.take_commands().expect("commands").is_empty());
17974        }
17975    }
17976
17977    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
17978        vec![selection_group_entry(
17979            1,
17980            2,
17981            index,
17982            "activity",
17983            &SelectionMemberMetadata {
17984                key: SelectionKey::Name(key.to_string()),
17985                index,
17986                base_sequence: index as u64 + 1,
17987                size: 1,
17988                kind: "activity".to_string(),
17989            },
17990        )]
17991    }
17992
17993    fn selection_activity_event(
17994        event_type: &str,
17995        index: usize,
17996        key: &str,
17997        result: Option<Value>,
17998    ) -> HistoryEvent {
17999        let sequence = index as u64 + 1;
18000        let mut event = parallel_history_event(
18001            event_type,
18002            sequence,
18003            "activity_type",
18004            &format!("{key}-activity"),
18005            selection_path(index, key),
18006            result,
18007        );
18008        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
18009        event.raw.insert(
18010            "id".to_string(),
18011            json!(if event_type == "ActivityCompleted" {
18012                format!("event-{key}")
18013            } else {
18014                format!("{event_type}-{key}")
18015            }),
18016        );
18017        event
18018    }
18019
18020    fn selection_winner_marker() -> HistoryEvent {
18021        history_event(
18022            "SelectionResolved",
18023            json!({
18024                "selection_group_id": "select-calls:1:2",
18025                "selection_group_base_sequence": 1,
18026                "selection_group_size": 2,
18027                "member_key": "fast",
18028                "member_index": 1,
18029                "member_base_sequence": 2,
18030                "member_size": 1,
18031                "operation_kind": "activity",
18032                "operation_identity": "activity-fast",
18033                "outcome": "completed",
18034                "resolution_event_id": "event-fast",
18035                "resolution_event_type": "ActivityCompleted",
18036            }),
18037        )
18038    }
18039
18040    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
18041        ctx.select_keyed(vec![
18042            (
18043                "slow",
18044                ParallelOperation::activity_with_options(
18045                    "slow-activity",
18046                    ActivityOptions::new().task_queue("default"),
18047                    json!([]),
18048                ),
18049            ),
18050            (
18051                "fast",
18052                ParallelOperation::activity_with_options(
18053                    "fast-activity",
18054                    ActivityOptions::new().task_queue("default"),
18055                    json!([]),
18056                ),
18057            ),
18058        ])
18059    }
18060
18061    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
18062        let ctx = workflow_context(history);
18063        let mut call = Box::pin(keyed_activity_selection(&ctx));
18064        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18065        let selected = match call.as_mut().poll(&mut task_context) {
18066            Poll::Ready(Ok(selected)) => selected,
18067            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
18068            Poll::Pending => panic!("persisted selection winner must replay without pending"),
18069        };
18070        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
18071        assert_eq!(
18072            selected.value,
18073            Some(ParallelResult::Activity(json!("winner-value")))
18074        );
18075        let slow = selected
18076            .handle(&SelectionKey::Name("slow".to_string()))
18077            .expect("slow handle")
18078            .clone();
18079        let mut await_slow = Box::pin(slow.await_result());
18080        assert!(matches!(
18081            await_slow.as_mut().poll(&mut task_context),
18082            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
18083        ));
18084        assert!(ctx.take_commands().expect("commands").is_empty());
18085    }
18086
18087    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
18088
18089    fn canonical_selection_history() -> Vec<HistoryEvent> {
18090        const FIXTURE: &[u8] =
18091            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
18092        assert_eq!(
18093            format!("{:x}", Sha256::digest(FIXTURE)),
18094            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18095        );
18096        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
18097
18098        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
18099    }
18100
18101    #[test]
18102    fn selection_fresh_process_entrypoint() {
18103        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
18104            return;
18105        };
18106        let persisted = fs::read(path).expect("persisted selection history");
18107        assert_eq!(
18108            format!("{:x}", Sha256::digest(&persisted)),
18109            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18110        );
18111        let fixture: Value =
18112            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
18113        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
18114            .expect("valid persisted selection history");
18115
18116        assert_persisted_selection_replay(history);
18117    }
18118
18119    #[test]
18120    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
18121        let ctx = workflow_context(Vec::new());
18122        let mut call = Box::pin(keyed_activity_selection(&ctx));
18123        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18124
18125        assert!(matches!(
18126            call.as_mut().poll(&mut task_context),
18127            Poll::Pending
18128        ));
18129        let commands = ctx.take_commands().expect("selection commands");
18130        assert_eq!(commands.len(), 2);
18131        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
18132        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
18133        assert!(commands.iter().all(|command| {
18134            command["parallel_group_id"] == json!("select-calls:1:2")
18135                && command["parallel_group_mode"] == json!("select")
18136        }));
18137    }
18138
18139    #[test]
18140    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
18141        let ctx = workflow_context(Vec::new());
18142        let mut invalid = Box::pin(ctx.select_keyed(vec![(
18143            "",
18144            ParallelOperation::activity("invalid", json!([])),
18145        )]));
18146        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18147        assert!(matches!(
18148            invalid.as_mut().poll(&mut task_context),
18149            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
18150                reason: "selection_key_invalid",
18151                ..
18152            })))
18153        ));
18154
18155        for invalid_key in [json!(""), json!(-1)] {
18156            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
18157            event.payload["selection_member_key"] = invalid_key.clone();
18158            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
18159            assert!(matches!(
18160                WorkflowState::new_with_identity(
18161                    vec![event],
18162                    None,
18163                    None,
18164                    "rust-workers".to_string(),
18165                    DEFAULT_CODEC.to_string(),
18166                    None,
18167                ),
18168                Err(Error::NonDeterministicReplay(_))
18169            ));
18170        }
18171    }
18172
18173    #[test]
18174    fn selection_preserves_valid_named_and_numeric_keys() {
18175        let ctx = workflow_context(Vec::new());
18176        let mut selection = Box::pin(ctx.select_keyed(vec![
18177            (
18178                SelectionKey::Index(0),
18179                ParallelOperation::activity("numeric", json!([])),
18180            ),
18181            (
18182                SelectionKey::Name("named".to_string()),
18183                ParallelOperation::timer(Duration::from_secs(1)),
18184            ),
18185        ]));
18186        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18187
18188        assert!(matches!(
18189            selection.as_mut().poll(&mut task_context),
18190            Poll::Pending
18191        ));
18192        let commands = ctx.take_commands().expect("selection commands");
18193        assert_eq!(commands[0]["selection_member_key"], json!(0));
18194        assert_eq!(commands[1]["selection_member_key"], json!("named"));
18195    }
18196
18197    #[test]
18198    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
18199        let history = canonical_selection_history();
18200        assert_persisted_selection_replay(history.clone());
18201
18202        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18203            .join("tests/fixtures/durable_selection_runtime_history.json");
18204        let output =
18205            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
18206                .args([
18207                    "--exact",
18208                    "tests::selection_fresh_process_entrypoint",
18209                    "--nocapture",
18210                ])
18211                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
18212                .output()
18213                .expect("run fresh selection replay process");
18214
18215        assert!(
18216            output.status.success(),
18217            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
18218            String::from_utf8_lossy(&output.stdout),
18219            String::from_utf8_lossy(&output.stderr),
18220        );
18221    }
18222
18223    #[test]
18224    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
18225        let mut history = canonical_selection_history();
18226        history.retain(|event| event.event_type != "SelectionResolved");
18227        let ctx = workflow_context(history);
18228        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18229        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18230
18231        assert!(matches!(
18232            selection.as_mut().poll(&mut task_context),
18233            Poll::Pending
18234        ));
18235        assert!(ctx.take_commands().expect("commands").is_empty());
18236        assert!(
18237            ctx.matched_recorded_pending()
18238                .expect("selection pending state"),
18239            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
18240        );
18241    }
18242
18243    #[test]
18244    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18245        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18246            ("ConditionWaitSatisfied", true, None),
18247            ("ConditionWaitTimedOut", false, Some(0)),
18248        ] {
18249            let member = SelectionMemberMetadata {
18250                key: SelectionKey::Name("condition".to_string()),
18251                index: 0,
18252                base_sequence: 1,
18253                size: 1,
18254                kind: "condition".to_string(),
18255            };
18256            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18257            let mut payload = json!({
18258                "sequence": 1,
18259                "condition_wait_id": "condition-1",
18260                "condition_wait_occurrence_id": "rust:condition-wait:0",
18261                "condition_key": "ready",
18262                "condition_definition_fingerprint": "sha256:ready-v1",
18263                "parallel_group_path": path,
18264            });
18265            payload
18266                .as_object_mut()
18267                .expect("condition history payload")
18268                .extend(
18269                    serde_json::to_value(&path[0])
18270                        .expect("condition selection metadata")
18271                        .as_object()
18272                        .expect("condition selection metadata object")
18273                        .clone(),
18274                );
18275            if let Some(timeout_seconds) = timeout_seconds {
18276                payload["timeout_seconds"] = json!(timeout_seconds);
18277            }
18278            let history = vec![
18279                history_event("ConditionWaitOpened", payload.clone()),
18280                history_event(terminal_event, payload),
18281            ];
18282            let ctx = workflow_context(history);
18283            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18284            if timeout_seconds.is_some() {
18285                options = options.timeout(Duration::ZERO);
18286            }
18287            let mut selection = Box::pin(ctx.select_keyed(vec![(
18288                "condition",
18289                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18290            )]));
18291            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18292
18293            assert!(matches!(
18294                selection.as_mut().poll(&mut task_context),
18295                Poll::Pending
18296            ));
18297            assert!(ctx.take_commands().expect("commands").is_empty());
18298            assert!(
18299                ctx.matched_recorded_pending()
18300                    .expect("condition selection pending state"),
18301                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18302            );
18303        }
18304    }
18305
18306    #[test]
18307    fn selection_immediate_condition_members_open_a_durable_wait() {
18308        for predicate_satisfied in [true, false] {
18309            let ctx = workflow_context(Vec::new());
18310            let mut selection = Box::pin(ctx.select_keyed(vec![(
18311                "condition",
18312                ParallelOperation::condition(
18313                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18314                    move || Ok(predicate_satisfied),
18315                ),
18316            )]));
18317            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18318
18319            assert!(matches!(
18320                selection.as_mut().poll(&mut task_context),
18321                Poll::Pending
18322            ));
18323            let commands = ctx.take_commands().expect("condition selection command");
18324            assert_eq!(commands.len(), 1);
18325            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18326            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18327            assert_eq!(
18328                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18329                json!("select")
18330            );
18331        }
18332    }
18333
18334    #[test]
18335    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18336        let history = vec![
18337            selection_activity_event("ActivityScheduled", 0, "slow", None),
18338            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18339            selection_winner_marker(),
18340        ];
18341        let ctx = workflow_context(history.clone());
18342        let mut call = Box::pin(keyed_activity_selection(&ctx));
18343        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18344        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18345            panic!("winner must replay");
18346        };
18347        let slow = selected
18348            .handle(&SelectionKey::Name("slow".to_string()))
18349            .expect("slow handle")
18350            .clone();
18351        let mut cancel = Box::pin(slow.cancel());
18352        assert!(matches!(
18353            cancel.as_mut().poll(&mut task_context),
18354            Poll::Pending
18355        ));
18356        assert!(matches!(
18357            cancel.as_mut().poll(&mut task_context),
18358            Poll::Pending
18359        ));
18360        let commands = ctx.take_commands().expect("cancel command");
18361        assert_eq!(commands.len(), 1);
18362        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18363        assert_eq!(commands[0]["member_key"], json!("slow"));
18364
18365        let mut cancelled_history = history;
18366        cancelled_history.push(history_event(
18367            "SelectionOperationCancelled",
18368            json!({
18369                "selection_group_id": "select-calls:1:2",
18370                "member_key": "slow",
18371                "member_index": 0,
18372                "member_base_sequence": 1,
18373                "member_size": 1,
18374                "operation_kind": "activity",
18375                "operation_identity": "activity-slow",
18376                "cancelled_at": "2026-08-27T00:00:00Z",
18377            }),
18378        ));
18379        let replayed = workflow_context(cancelled_history);
18380        let mut call = Box::pin(keyed_activity_selection(&replayed));
18381        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18382            panic!("winner must replay after cancellation");
18383        };
18384        let slow = selected
18385            .handle(&SelectionKey::Name("slow".to_string()))
18386            .expect("slow handle")
18387            .clone();
18388        let mut cancel = Box::pin(slow.cancel());
18389        assert!(matches!(
18390            cancel.as_mut().poll(&mut task_context),
18391            Poll::Ready(Ok(()))
18392        ));
18393        assert!(replayed.take_commands().expect("commands").is_empty());
18394    }
18395
18396    #[test]
18397    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
18398        let base_history = vec![
18399            selection_activity_event("ActivityScheduled", 0, "slow", None),
18400            selection_activity_event("ActivityScheduled", 1, "fast", None),
18401            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18402            selection_winner_marker(),
18403        ];
18404        for (field, corrupt) in [
18405            ("member_key", json!("fast")),
18406            ("member_index", json!(1)),
18407            ("member_base_sequence", json!(3)),
18408            ("member_size", json!(2)),
18409            ("operation_kind", json!("timer")),
18410            ("operation_identity", json!("forged")),
18411        ] {
18412            let mut cancellation = json!({
18413                "selection_group_id": "select-calls:1:2",
18414                "member_key": "slow",
18415                "member_index": 0,
18416                "member_base_sequence": 1,
18417                "member_size": 1,
18418                "operation_kind": "activity",
18419                "operation_identity": "activity-slow",
18420            });
18421            cancellation[field] = corrupt;
18422            let mut history = base_history.clone();
18423            history.push(history_event("SelectionOperationCancelled", cancellation));
18424            let ctx = workflow_context(history);
18425            let mut selection = Box::pin(keyed_activity_selection(&ctx));
18426            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18427
18428            assert!(matches!(
18429                selection.as_mut().poll(&mut task_context),
18430                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18431            ));
18432        }
18433    }
18434
18435    #[test]
18436    fn selection_child_identity_prefers_the_durable_run_id() {
18437        let ctx = workflow_context(vec![history_event(
18438            "ChildWorkflowScheduled",
18439            json!({
18440                "sequence": 1,
18441                "child_workflow_type": "child",
18442                "child_workflow_instance_id": "child-instance",
18443                "child_workflow_run_id": "child-run",
18444            }),
18445        )]);
18446        let state = ctx.state.lock().expect("workflow state");
18447
18448        assert_eq!(
18449            selection_operation_identity(&state, "child", 1, 1),
18450            "child-run"
18451        );
18452    }
18453
18454    #[test]
18455    fn selection_activity_identity_requires_canonical_execution_id() {
18456        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
18457        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
18458        let mut fast_completed =
18459            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
18460        for event in [&mut fast_open, &mut fast_completed] {
18461            event
18462                .payload
18463                .as_object_mut()
18464                .expect("activity payload")
18465                .remove("activity_execution_id");
18466            event.payload["activity_id"] = json!("forged-activity-id");
18467        }
18468        let mut marker = selection_winner_marker();
18469        marker.payload["operation_identity"] = json!("forged-activity-id");
18470        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
18471        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18472        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18473
18474        assert!(matches!(
18475            selection.as_mut().poll(&mut task_context),
18476            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18477        ));
18478    }
18479
18480    #[test]
18481    fn selection_completion_before_cancellation_remains_awaitable() {
18482        let history = vec![
18483            selection_activity_event("ActivityScheduled", 0, "slow", None),
18484            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18485            selection_winner_marker(),
18486            selection_activity_event(
18487                "ActivityCompleted",
18488                0,
18489                "slow",
18490                Some(json!("completed-first")),
18491            ),
18492        ];
18493        let ctx = workflow_context(history);
18494        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18495        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18496        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18497            panic!("winner must replay");
18498        };
18499        let slow = selected
18500            .handle(&SelectionKey::Name("slow".to_string()))
18501            .expect("slow handle")
18502            .clone();
18503        let mut cancel = Box::pin(slow.cancel());
18504        assert!(matches!(
18505            cancel.as_mut().poll(&mut task_context),
18506            Poll::Ready(Ok(()))
18507        ));
18508        let mut await_slow = Box::pin(slow.await_result());
18509        assert!(matches!(
18510            await_slow.as_mut().poll(&mut task_context),
18511            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
18512        ));
18513        let commands = ctx.take_commands().expect("commands");
18514        assert!(commands.is_empty());
18515    }
18516
18517    #[test]
18518    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
18519        let nested_member = SelectionMemberMetadata {
18520            key: SelectionKey::Name("nested".to_string()),
18521            index: 0,
18522            base_sequence: 1,
18523            size: 2,
18524            kind: "group".to_string(),
18525        };
18526        let deadline_member = SelectionMemberMetadata {
18527            key: SelectionKey::Name("deadline".to_string()),
18528            index: 1,
18529            base_sequence: 3,
18530            size: 1,
18531            kind: "timer".to_string(),
18532        };
18533        let nested_paths = [
18534            vec![
18535                selection_group_entry(1, 3, 0, "mixed", &nested_member),
18536                parallel_group_entry(1, 2, 0, "activity"),
18537            ],
18538            vec![
18539                selection_group_entry(1, 3, 1, "mixed", &nested_member),
18540                parallel_group_entry(1, 2, 1, "activity"),
18541            ],
18542        ];
18543        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
18544        let mut timer_fired = parallel_history_event(
18545            "TimerFired",
18546            3,
18547            "timer_id",
18548            "timer-3",
18549            deadline_path.clone(),
18550            None,
18551        );
18552        timer_fired.payload["delay_seconds"] = json!(0);
18553        timer_fired
18554            .raw
18555            .insert("id".to_string(), json!("timer-fired"));
18556        let mut timer_scheduled = parallel_history_event(
18557            "TimerScheduled",
18558            3,
18559            "timer_id",
18560            "timer-3",
18561            deadline_path,
18562            None,
18563        );
18564        timer_scheduled.payload["delay_seconds"] = json!(0);
18565        let history = vec![
18566            parallel_history_event(
18567                "ActivityScheduled",
18568                1,
18569                "activity_type",
18570                "nested-first",
18571                nested_paths[0].clone(),
18572                None,
18573            ),
18574            parallel_history_event(
18575                "ActivityScheduled",
18576                2,
18577                "activity_type",
18578                "nested-second",
18579                nested_paths[1].clone(),
18580                None,
18581            ),
18582            timer_scheduled,
18583            timer_fired,
18584            history_event(
18585                "SelectionResolved",
18586                json!({
18587                    "selection_group_id": "select-calls:1:3",
18588                    "selection_group_base_sequence": 1,
18589                    "selection_group_size": 3,
18590                    "member_key": "deadline",
18591                    "member_index": 1,
18592                    "member_base_sequence": 3,
18593                    "member_size": 1,
18594                    "operation_kind": "timer",
18595                    "operation_identity": "timer-3",
18596                    "outcome": "completed",
18597                    "resolution_event_id": "timer-fired",
18598                    "resolution_event_type": "TimerFired",
18599                }),
18600            ),
18601            parallel_history_event(
18602                "ActivityFailed",
18603                2,
18604                "activity_type",
18605                "nested-second",
18606                nested_paths[1].clone(),
18607                None,
18608            ),
18609        ];
18610        let ctx = workflow_context(history);
18611        let mut selection = Box::pin(ctx.select_keyed(vec![
18612            (
18613                "nested",
18614                ParallelOperation::group(vec![
18615                    ParallelOperation::activity("nested-first", json!([])),
18616                    ParallelOperation::activity("nested-second", json!([])),
18617                ]),
18618            ),
18619            ("deadline", ParallelOperation::timer(Duration::ZERO)),
18620        ]));
18621        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18622        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18623            panic!("deadline winner must replay");
18624        };
18625        let nested = selected
18626            .handle(&SelectionKey::Name("nested".to_string()))
18627            .expect("nested handle")
18628            .clone();
18629        let mut cancel = Box::pin(nested.cancel());
18630        assert!(matches!(
18631            cancel.as_mut().poll(&mut task_context),
18632            Poll::Ready(Ok(()))
18633        ));
18634        let mut await_nested = Box::pin(nested.await_result());
18635
18636        assert!(matches!(
18637            await_nested.as_mut().poll(&mut task_context),
18638            Poll::Ready(Err(Error::ActivityFailed(_)))
18639        ));
18640        assert!(ctx.take_commands().expect("commands").is_empty());
18641    }
18642
18643    #[test]
18644    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
18645        let ctx = workflow_context(Vec::new());
18646        let mut call = Box::pin(ctx.select(vec![
18647            ParallelOperation::child_workflow(
18648                "child",
18649                ChildWorkflowOptions::new("children"),
18650                json!([]),
18651            ),
18652            ParallelOperation::timer(Duration::from_secs(30)),
18653            ParallelOperation::signal("approval"),
18654            ParallelOperation::condition(
18655                ConditionWaitOptions::new("ready", "sha256:ready"),
18656                || Ok(false),
18657            ),
18658            ParallelOperation::group(vec![
18659                ParallelOperation::activity("nested-one", json!([])),
18660                ParallelOperation::activity("nested-two", json!([])),
18661            ]),
18662        ]));
18663        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18664        assert!(matches!(
18665            call.as_mut().poll(&mut task_context),
18666            Poll::Pending
18667        ));
18668        let commands = ctx.take_commands().expect("selection commands");
18669        assert_eq!(
18670            commands
18671                .iter()
18672                .map(|command| command["type"].as_str().unwrap_or_default())
18673                .collect::<Vec<_>>(),
18674            [
18675                "start_child_workflow",
18676                "start_timer",
18677                "open_signal_wait",
18678                "open_condition_wait",
18679                "schedule_activity",
18680                "schedule_activity",
18681            ]
18682        );
18683        assert!(commands.iter().all(|command| {
18684            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
18685        }));
18686        assert_eq!(
18687            commands[4]["parallel_group_path"].as_array().map(Vec::len),
18688            Some(2)
18689        );
18690        assert_eq!(
18691            commands[4]["parallel_group_path"][0]["selection_member_kind"],
18692            json!("group")
18693        );
18694        assert_eq!(
18695            commands[5]["parallel_group_path"][0]["selection_member_kind"],
18696            json!("group")
18697        );
18698
18699        let one_leaf_ctx = workflow_context(Vec::new());
18700        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
18701            ParallelOperation::activity("nested-only", json!([])),
18702        ])]));
18703        assert!(matches!(
18704            one_leaf.as_mut().poll(&mut task_context),
18705            Poll::Pending
18706        ));
18707        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
18708        assert_eq!(one_leaf_commands.len(), 1);
18709        assert_eq!(
18710            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
18711            json!("group")
18712        );
18713        assert_eq!(
18714            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
18715            json!(1)
18716        );
18717    }
18718
18719    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
18720        let mut saga = ctx.saga();
18721        let outcome = async {
18722            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18723            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18724            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
18725            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
18726            ctx.activity("trip.charge", json!([])).await?;
18727            Ok(json!({"status": "booked"}))
18728        }
18729        .await;
18730        saga.finish(outcome).await
18731    }
18732
18733    fn saga_activity(
18734        event_type: &str,
18735        sequence: u64,
18736        activity_type: &str,
18737        result: Option<Value>,
18738    ) -> HistoryEvent {
18739        let mut payload = json!({
18740            "sequence": sequence,
18741            "activity_type": activity_type,
18742            "message": format!("{activity_type} failed"),
18743            "exception_type": "PlannedFailure",
18744            "non_retryable": true,
18745        });
18746        if let Some(result) = result {
18747            payload["result"] = fixture_envelope(result);
18748        }
18749        history_event(event_type, payload)
18750    }
18751
18752    #[test]
18753    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
18754        let completed_hotel_compensation = saga_activity(
18755            "ActivityCompleted",
18756            4,
18757            "trip.cancel-hotel",
18758            Some(Value::Null),
18759        );
18760        let history = vec![
18761            saga_activity(
18762                "ActivityCompleted",
18763                1,
18764                "trip.reserve-flight",
18765                Some(json!("flight-1")),
18766            ),
18767            saga_activity(
18768                "ActivityCompleted",
18769                2,
18770                "trip.reserve-hotel",
18771                Some(json!("hotel-1")),
18772            ),
18773            saga_activity("ActivityFailed", 3, "trip.charge", None),
18774            completed_hotel_compensation.clone(),
18775            completed_hotel_compensation,
18776        ];
18777
18778        for _restart in 0..2 {
18779            let ctx = workflow_context(history.clone());
18780            let mut future = Box::pin(trip_saga(ctx.clone()));
18781            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18782            assert!(matches!(
18783                future.as_mut().poll(&mut task_context),
18784                Poll::Pending
18785            ));
18786            let commands = ctx.take_commands().expect("compensation command");
18787            assert_eq!(commands.len(), 1);
18788            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18789        }
18790    }
18791
18792    #[test]
18793    fn saga_compensation_failure_preserves_both_typed_failures() {
18794        let history = vec![
18795            saga_activity(
18796                "ActivityCompleted",
18797                1,
18798                "trip.reserve-flight",
18799                Some(json!("flight-1")),
18800            ),
18801            saga_activity(
18802                "ActivityCompleted",
18803                2,
18804                "trip.reserve-hotel",
18805                Some(json!("hotel-1")),
18806            ),
18807            saga_activity("ActivityFailed", 3, "trip.charge", None),
18808            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
18809        ];
18810        let ctx = workflow_context(history);
18811        let mut future = Box::pin(trip_saga(ctx));
18812        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18813        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
18814            future.as_mut().poll(&mut task_context)
18815        else {
18816            panic!("compensation failure must remain structured");
18817        };
18818        assert!(matches!(
18819            *failure.initiating_failure,
18820            Error::ActivityFailed(_)
18821        ));
18822        assert!(matches!(
18823            *failure.compensation_failure,
18824            Error::ActivityFailed(_)
18825        ));
18826        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
18827        assert_eq!(failure.compensation_registration_order, 2);
18828    }
18829
18830    #[test]
18831    fn saga_compensates_cooperative_cancellation() {
18832        let ctx = workflow_context(vec![saga_activity(
18833            "ActivityCompleted",
18834            1,
18835            "trip.reserve-flight",
18836            Some(json!("flight-1")),
18837        )]);
18838        ctx.state.lock().expect("state").cancel_requested = true;
18839        let run = {
18840            let ctx = ctx.clone();
18841            async move {
18842                let mut saga = ctx.saga();
18843                let outcome = async {
18844                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
18845                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
18846                    ctx.throw_if_cancellation_requested()?;
18847                    Ok(json!("unexpected"))
18848                }
18849                .await;
18850                saga.finish(outcome).await
18851            }
18852        };
18853        let mut future = Box::pin(run);
18854        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18855        assert!(matches!(
18856            future.as_mut().poll(&mut task_context),
18857            Poll::Pending
18858        ));
18859        let commands = ctx.take_commands().expect("cancellation compensation");
18860        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
18861    }
18862
18863    fn workflow_task(
18864        workflow_type: &str,
18865        history_events: Vec<HistoryEvent>,
18866        payload_codec: &str,
18867    ) -> WorkflowTask {
18868        WorkflowTask {
18869            task_id: format!("wft-{workflow_type}"),
18870            workflow_command_id: None,
18871            workflow_id: Some(format!("wf-{workflow_type}")),
18872            run_id: Some(format!("run-{workflow_type}")),
18873            workflow_type: workflow_type.to_string(),
18874            cancel_requested: false,
18875            payload_codec: payload_codec.to_string(),
18876            arguments: Some(
18877                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
18878            ),
18879            total_history_events: Some(history_events.len() as u64),
18880            history_size_bytes: None,
18881            continue_as_new_recommended: None,
18882            history_budget_pressure: None,
18883            history_events,
18884            next_history_page_token: None,
18885            workflow_task_attempt: 1,
18886            workflow_signal_id: None,
18887            signal_name: None,
18888            signal_arguments: None,
18889            workflow_update_id: None,
18890            update_name: None,
18891            lease_owner: Some("rust-worker".to_string()),
18892        }
18893    }
18894
18895    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18896    struct SideEffectProbe {
18897        request_id: String,
18898        attempt: u32,
18899    }
18900
18901    #[test]
18902    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
18903        let calls = AtomicUsize::new(0);
18904        let ctx = workflow_context(Vec::new());
18905        let value = ctx
18906            .side_effect(|| {
18907                calls.fetch_add(1, Ordering::SeqCst);
18908                SideEffectProbe {
18909                    request_id: "request-42".to_string(),
18910                    attempt: 3,
18911                }
18912            })
18913            .expect("first side effect");
18914        assert_eq!(value.attempt, 3);
18915        assert_eq!(calls.load(Ordering::SeqCst), 1);
18916        let commands = ctx.take_commands().expect("commands");
18917        assert_eq!(commands.len(), 1);
18918        assert_eq!(commands[0]["type"], "record_side_effect");
18919        assert_eq!(
18920            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18921            serde_json::to_value(&value).expect("value")
18922        );
18923
18924        let replay = workflow_context(vec![history_event(
18925            "SideEffectRecorded",
18926            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18927        )]);
18928        let replayed: SideEffectProbe = replay
18929            .side_effect(|| {
18930                calls.fetch_add(1, Ordering::SeqCst);
18931                panic!("committed side-effect callbacks must not run during replay")
18932            })
18933            .expect("replayed side effect");
18934        assert_eq!(replayed, value);
18935        assert_eq!(calls.load(Ordering::SeqCst), 1);
18936        assert!(replay.take_commands().expect("commands").is_empty());
18937        replay.ensure_history_consumed().expect("history consumed");
18938    }
18939
18940    #[test]
18941    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
18942        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18943        let value = ctx
18944            .side_effect(|| SideEffectProbe {
18945                request_id: "avro-request".to_string(),
18946                attempt: 1,
18947            })
18948            .expect("Avro side effect");
18949        let uuid = ctx.uuid_v4().expect("deterministic UUID");
18950        let commands = ctx.take_commands().expect("commands");
18951        assert_eq!(commands.len(), 2);
18952        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
18953        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
18954        assert_eq!(
18955            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
18956            serde_json::to_value(&value).expect("value")
18957        );
18958
18959        let replay = workflow_context_with_codec(
18960            vec![
18961                history_event(
18962                    "SideEffectRecorded",
18963                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18964                ),
18965                history_event(
18966                    "SideEffectRecorded",
18967                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
18968                ),
18969            ],
18970            DEFAULT_CODEC,
18971        );
18972        let replayed: SideEffectProbe = replay
18973            .side_effect(|| panic!("Avro callback must not run"))
18974            .expect("replayed Avro value");
18975        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
18976        assert_eq!(replayed, value);
18977        assert_eq!(replayed_uuid, uuid);
18978        assert!(replay.take_commands().expect("commands").is_empty());
18979    }
18980
18981    #[test]
18982    fn typed_side_effect_replay_preserves_bytes_and_maps() {
18983        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
18984        let value = ctx
18985            .side_effect_avro_value(typed_fidelity_probe)
18986            .expect("typed side effect");
18987        let commands = ctx.take_commands().expect("side-effect command");
18988        assert_eq!(
18989            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
18990                .expect("recorded side effect"),
18991            value
18992        );
18993
18994        let replay = workflow_context_with_codec(
18995            vec![history_event(
18996                "SideEffectRecorded",
18997                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
18998            )],
18999            DEFAULT_CODEC,
19000        );
19001        assert_eq!(
19002            replay
19003                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
19004                .expect("replayed typed side effect"),
19005            value
19006        );
19007    }
19008
19009    #[test]
19010    fn ordered_side_effects_share_the_durable_command_stream() {
19011        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
19012        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
19013        let ctx = workflow_context(vec![
19014            history_event(
19015                "SideEffectRecorded",
19016                json!({"sequence": 1, "result": first}),
19017            ),
19018            history_event(
19019                "SideEffectRecorded",
19020                json!({"sequence": 2, "result": second}),
19021            ),
19022        ]);
19023        let first: String = ctx
19024            .side_effect(|| panic!("first callback must not run"))
19025            .expect("first replay");
19026        let second: i32 = ctx
19027            .side_effect(|| panic!("second callback must not run"))
19028            .expect("second replay");
19029        assert_eq!(first, "first");
19030        assert_eq!(second, 29);
19031        ctx.ensure_history_consumed().expect("ordered history");
19032
19033        let reordered = workflow_context(vec![history_event(
19034            "VersionMarkerRecorded",
19035            json!({
19036                "sequence": 1,
19037                "change_id": "before-side-effect",
19038                "version": 1,
19039                "min_supported": 1,
19040                "max_supported": 1,
19041            }),
19042        )]);
19043        let error = reordered
19044            .side_effect(|| "new".to_string())
19045            .expect_err("command reordering must fail");
19046        assert!(matches!(
19047            error,
19048            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19049                if reason == "recorded_command_mismatch"
19050        ));
19051    }
19052
19053    #[test]
19054    fn legacy_patch_preserves_pending_and_completed_activity_history() {
19055        for completed in [false, true] {
19056            let mut history = vec![history_event(
19057                "ActivityScheduled",
19058                json!({"sequence": 1, "activity_type": "old"}),
19059            )];
19060            if completed {
19061                history.push(history_event(
19062                    "ActivityCompleted",
19063                    json!({
19064                        "sequence": 1,
19065                        "activity_type": "old",
19066                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
19067                    }),
19068                ));
19069            }
19070            for _cold_replay in 0..2 {
19071                let ctx = workflow_context(history.clone());
19072                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
19073                assert!(!ctx.patched("added-step").expect("same frozen decision"));
19074                ctx.deprecate_patch("added-step")
19075                    .expect("retained boundary");
19076                let mut activity = Box::pin(ctx.activity("old", json!([])));
19077                let mut context = TaskContext::from_waker(noop_waker_ref());
19078                match activity.as_mut().poll(&mut context) {
19079                    Poll::Ready(result) => {
19080                        assert!(completed);
19081                        assert_eq!(result.expect("recorded result"), json!(41));
19082                        ctx.ensure_history_consumed().expect("old command retained");
19083                    }
19084                    Poll::Pending => assert!(!completed),
19085                }
19086                assert!(ctx.take_commands().expect("commands").is_empty());
19087            }
19088        }
19089    }
19090
19091    #[test]
19092    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
19093        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
19094        assert!(!ctx.patched("added-step").expect("legacy completed run"));
19095        ctx.deprecate_patch("added-step")
19096            .expect("same legacy decision");
19097        assert!(ctx.take_commands().expect("commands").is_empty());
19098        ctx.ensure_history_consumed().expect("completed history");
19099    }
19100
19101    #[test]
19102    fn legacy_patch_rejects_a_range_without_the_original_branch() {
19103        let ctx = workflow_context(vec![history_event(
19104            "ActivityScheduled",
19105            json!({"sequence": 1, "activity_type": "old"}),
19106        )]);
19107        let error = ctx
19108            .get_version("added-step", 0, 1)
19109            .expect_err("legacy is unsupported");
19110        assert!(matches!(
19111            error,
19112            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19113                if reason == "version_marker_incompatible_range"
19114        ));
19115        assert!(!ctx
19116            .patched("supported-step")
19117            .expect("failed check did not consume history"));
19118        assert!(ctx.take_commands().expect("commands").is_empty());
19119    }
19120
19121    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
19122        let mut event = history_event(
19123            "VersionMarkerRecorded",
19124            json!({
19125                "sequence": sequence,
19126                "change_id": "retained-patch",
19127                "version": version,
19128                "min_supported": -1,
19129                "max_supported": 1,
19130            }),
19131        );
19132        event.raw.insert("timestamp".into(), json!(time));
19133        event
19134    }
19135
19136    #[test]
19137    fn retained_patch_markers_preserve_each_original_boundary() {
19138        for completed in [false, true] {
19139            let mut history = vec![
19140                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19141                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19142                history_event(
19143                    "ActivityScheduled",
19144                    json!({"sequence": 3, "activity_type": "old"}),
19145                ),
19146            ];
19147            if completed {
19148                history.push(history_event(
19149                    "ActivityCompleted",
19150                    json!({
19151                        "sequence": 3,
19152                        "activity_type": "old",
19153                        "result": fixture_envelope(json!(41)),
19154                    }),
19155                ));
19156            }
19157            for _cold_replay in 0..2 {
19158                let ctx = workflow_context(history.clone());
19159                assert!(ctx.patched("retained-patch").unwrap());
19160                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19161                assert!(ctx.patched("retained-patch").unwrap());
19162                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19163                ctx.deprecate_patch("retained-patch").unwrap();
19164                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19165                let mut activity = Box::pin(ctx.activity("old", json!([])));
19166                let mut context = TaskContext::from_waker(noop_waker_ref());
19167                match activity.as_mut().poll(&mut context) {
19168                    Poll::Ready(result) => {
19169                        assert!(completed);
19170                        assert_eq!(result.unwrap(), json!(41));
19171                        ctx.ensure_history_consumed().unwrap();
19172                    }
19173                    Poll::Pending => assert!(!completed),
19174                }
19175                assert!(ctx.take_commands().unwrap().is_empty());
19176                let state = ctx.state.lock().unwrap();
19177                for (actual, original) in state.history_events.iter().zip(&history) {
19178                    assert_eq!(actual.payload, original.payload);
19179                    assert_eq!(actual.raw, original.raw);
19180                }
19181            }
19182        }
19183    }
19184
19185    #[test]
19186    fn retained_patch_aliases_do_not_skip_intervening_operations() {
19187        let ctx = workflow_context(vec![
19188            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19189            history_event(
19190                "SideEffectRecorded",
19191                json!({
19192                    "sequence": 2, "result": fixture_envelope(json!("between")),
19193                }),
19194            ),
19195            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
19196            history_event(
19197                "VersionMarkerRecorded",
19198                json!({
19199                    "sequence": 4, "change_id": "other-patch", "version": 1,
19200                    "min_supported": -1, "max_supported": 1,
19201                }),
19202            ),
19203        ]);
19204        assert!(ctx.patched("retained-patch").unwrap());
19205        assert!(ctx.patched("retained-patch").unwrap());
19206        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19207        assert_eq!(
19208            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19209            "between"
19210        );
19211        ctx.deprecate_patch("retained-patch").unwrap();
19212        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19213        ctx.deprecate_patch("retained-patch").unwrap();
19214        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19215        assert!(ctx.patched("other-patch").unwrap());
19216        ctx.ensure_history_consumed().unwrap();
19217        assert!(ctx.take_commands().unwrap().is_empty());
19218    }
19219
19220    #[test]
19221    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
19222        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19223        alias.payload["max_supported"] = json!(3);
19224        let ctx = workflow_context(vec![
19225            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19226            alias,
19227        ]);
19228        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
19229        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
19230        assert!(matches!(error,
19231            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19232                if reason == "version_marker_incompatible_range"));
19233        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19234        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
19235        ctx.ensure_history_consumed().unwrap();
19236        assert!(ctx.take_commands().unwrap().is_empty());
19237    }
19238
19239    #[test]
19240    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
19241        let ctx = workflow_context(Vec::new());
19242        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
19243        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
19244        assert!(ctx.patched("new-search").expect("patch"));
19245        ctx.deprecate_patch("new-search").expect("deprecate patch");
19246        let commands = ctx.take_commands().expect("commands");
19247        assert_eq!(commands.len(), 2);
19248        assert_eq!(commands[0]["type"], "record_version_marker");
19249        assert_eq!(commands[0]["version"], 2);
19250        assert_eq!(commands[1]["change_id"], "new-search");
19251
19252        let replay = workflow_context(vec![history_event(
19253            "VersionMarkerRecorded",
19254            json!({
19255                "sequence": 1,
19256                "change_id": "checkout-v2",
19257                "version": 2,
19258                "min_supported": 1,
19259                "max_supported": 2,
19260            }),
19261        )]);
19262        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
19263        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
19264        assert!(replay.take_commands().expect("commands").is_empty());
19265        replay.ensure_history_consumed().expect("history consumed");
19266    }
19267
19268    #[test]
19269    fn version_markers_reject_incompatible_or_malformed_history() {
19270        let incompatible = workflow_context(vec![history_event(
19271            "VersionMarkerRecorded",
19272            json!({
19273                "sequence": 1,
19274                "change_id": "checkout-v2",
19275                "version": 1,
19276                "min_supported": 1,
19277                "max_supported": 2,
19278            }),
19279        )]);
19280        let error = incompatible
19281            .get_version("checkout-v2", 2, 3)
19282            .expect_err("old version is unsupported");
19283        assert!(matches!(
19284            error,
19285            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19286                if reason == "version_marker_incompatible_range"
19287        ));
19288
19289        for (history, reason) in [
19290            (
19291                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
19292                "side_effect_result_missing",
19293            ),
19294            (
19295                vec![history_event(
19296                    "SideEffectRecorded",
19297                    json!({
19298                        "sequence": 1,
19299                        "result": {"codec": "avro", "blob": "not-base64"},
19300                    }),
19301                )],
19302                "side_effect_payload_incompatible",
19303            ),
19304            (
19305                vec![history_event(
19306                    "SideEffectRecorded",
19307                    json!({"sequence": 1, "result": {"unwrapped": true}}),
19308                )],
19309                "side_effect_payload_malformed",
19310            ),
19311            (
19312                vec![history_event(
19313                    "VersionMarkerRecorded",
19314                    json!({
19315                        "sequence": 1,
19316                        "change_id": "change",
19317                        "version": 1,
19318                        "min_supported": 2,
19319                        "max_supported": 1,
19320                    }),
19321                )],
19322                "version_marker_history_range_invalid",
19323            ),
19324        ] {
19325            let error = WorkflowState::new(
19326                history,
19327                "rust-workers".to_string(),
19328                DEFAULT_CODEC.to_string(),
19329                None,
19330            )
19331            .expect_err("malformed history must fail");
19332            assert!(matches!(
19333                error,
19334                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
19335                    if actual == reason
19336            ));
19337        }
19338    }
19339
19340    #[test]
19341    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
19342        let history = vec![history_event(
19343            "SearchAttributesUpserted",
19344            json!({
19345                "sequence": 1,
19346                "attributes": {"customer_tier": "gold"},
19347                "attribute_types": {"customer_tier": "keyword"},
19348                "merged": {"customer_tier": "gold"}
19349            }),
19350        )];
19351
19352        let matching = workflow_context(history.clone());
19353        matching
19354            .upsert_search_attributes(
19355                SearchAttributeUpdate::new()
19356                    .keyword("customer_tier", "gold")
19357                    .expect("keyword update"),
19358            )
19359            .expect("matching typed update must replay");
19360        matching
19361            .ensure_history_consumed()
19362            .expect("history consumed");
19363
19364        let changed_type = workflow_context(history.clone());
19365        let error = changed_type
19366            .upsert_search_attributes(
19367                SearchAttributeUpdate::new()
19368                    .string("customer_tier", "gold")
19369                    .expect("string update"),
19370            )
19371            .expect_err("same JSON value with a different declaration must be nondeterministic");
19372        let Error::NonDeterministicReplay(failure) = error else {
19373            panic!("typed identity drift must be a replay failure");
19374        };
19375        assert_eq!(failure.reason, "search_attribute_type_mismatch");
19376        assert_eq!(failure.sequence, Some(1));
19377
19378        let changed_value = workflow_context(history);
19379        let error = changed_value
19380            .upsert_search_attributes(
19381                SearchAttributeUpdate::new()
19382                    .keyword("customer_tier", "platinum")
19383                    .expect("keyword update"),
19384            )
19385            .expect_err("changed values must be nondeterministic");
19386        let Error::NonDeterministicReplay(failure) = error else {
19387            panic!("value drift must be a replay failure");
19388        };
19389        assert_eq!(failure.reason, "search_attribute_value_mismatch");
19390    }
19391
19392    #[test]
19393    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
19394        let history = vec![history_event(
19395            "SearchAttributesUpserted",
19396            json!({
19397                "sequence": 1,
19398                "attributes": {"customer_tier": "gold"},
19399                "merged": {"customer_tier": "gold"}
19400            }),
19401        )];
19402
19403        for update in [
19404            SearchAttributeUpdate::new()
19405                .keyword("customer_tier", "gold")
19406                .expect("keyword update"),
19407            SearchAttributeUpdate::new()
19408                .string("customer_tier", "gold")
19409                .expect("string update"),
19410        ] {
19411            let restarted = workflow_context(history.clone());
19412            restarted
19413                .upsert_search_attributes(update)
19414                .expect("legacy history constrains values but has unknown type identity");
19415            restarted
19416                .ensure_history_consumed()
19417                .expect("history consumed");
19418        }
19419    }
19420
19421    #[test]
19422    fn search_attribute_command_emits_canonical_types() {
19423        let ctx = workflow_context(Vec::new());
19424        ctx.upsert_search_attributes(
19425            SearchAttributeUpdate::new()
19426                .keyword("customer_tier", "gold")
19427                .expect("keyword update")
19428                .int("attempts", 3)
19429                .expect("int update")
19430                .delete("obsolete")
19431                .expect("delete update"),
19432        )
19433        .expect("valid search attributes");
19434
19435        assert_eq!(
19436            ctx.take_commands().expect("commands"),
19437            vec![json!({
19438                "type": "upsert_search_attributes",
19439                "attributes": {
19440                    "attempts": 3,
19441                    "customer_tier": "gold",
19442                    "obsolete": null
19443                },
19444                "attribute_types": {
19445                    "attempts": "int",
19446                    "customer_tier": "keyword"
19447                }
19448            })]
19449        );
19450    }
19451
19452    #[test]
19453    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
19454        let duplicate_side_effect = WorkflowState::new(
19455            vec![
19456                history_event(
19457                    "SideEffectRecorded",
19458                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
19459                ),
19460                history_event(
19461                    "SideEffectRecorded",
19462                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
19463                ),
19464            ],
19465            "rust-workers".to_string(),
19466            DEFAULT_CODEC.to_string(),
19467            None,
19468        )
19469        .expect_err("duplicate side effect");
19470        assert!(matches!(
19471            duplicate_side_effect,
19472            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19473                if reason == "duplicate_side_effect_record"
19474        ));
19475
19476        let marker = |sequence, version| {
19477            history_event(
19478                "VersionMarkerRecorded",
19479                json!({
19480                    "sequence": sequence,
19481                    "change_id": "same-change",
19482                    "version": version,
19483                    "min_supported": -1,
19484                    "max_supported": 1,
19485                }),
19486            )
19487        };
19488        let duplicate_marker = WorkflowState::new(
19489            vec![marker(1, 1), marker(3, -1)],
19490            "rust-workers".to_string(),
19491            DEFAULT_CODEC.to_string(),
19492            None,
19493        )
19494        .expect_err("conflicting marker");
19495        assert!(matches!(
19496            duplicate_marker,
19497            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19498                if reason == "version_marker_conflict"
19499        ));
19500    }
19501
19502    #[test]
19503    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
19504        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
19505        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19506        invalid_alias.payload["max_supported"] = json!(0);
19507        for (history, expected_reason) in [
19508            (
19509                vec![marker.clone(), marker.clone()],
19510                "duplicate_version_marker_record",
19511            ),
19512            (
19513                vec![marker, invalid_alias],
19514                "version_marker_history_range_invalid",
19515            ),
19516        ] {
19517            let error =
19518                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
19519                    .expect_err("invalid historical alias");
19520            assert!(matches!(error,
19521                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
19522                    if reason == expected_reason));
19523        }
19524    }
19525
19526    #[test]
19527    fn retained_patch_aliases_require_the_original_call_boundary() {
19528        let ctx = workflow_context(vec![
19529            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19530            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19531        ]);
19532        assert!(ctx.patched("retained-patch").unwrap());
19533        assert!(ctx.ensure_history_consumed().is_err());
19534        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19535        ctx.deprecate_patch("retained-patch").unwrap();
19536        ctx.ensure_history_consumed().unwrap();
19537        assert!(ctx.take_commands().unwrap().is_empty());
19538    }
19539
19540    #[test]
19541    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
19542        let ctx = workflow_context(vec![
19543            history_event(
19544                "SideEffectRecorded",
19545                json!({
19546                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
19547                }),
19548            ),
19549            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19550        ]);
19551        assert!(!ctx.patched("retained-patch").unwrap());
19552        assert_eq!(
19553            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19554            "old-operation"
19555        );
19556        let error = ctx.patched("retained-patch").unwrap_err();
19557        assert!(matches!(error,
19558            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19559                if reason == "version_marker_conflict"));
19560        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19561        assert!(ctx.take_commands().unwrap().is_empty());
19562    }
19563
19564    #[test]
19565    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
19566        let mut state = WorkflowState::new(
19567            Vec::new(),
19568            "rust-workers".to_string(),
19569            DEFAULT_CODEC.to_string(),
19570            None,
19571        )
19572        .expect("workflow state");
19573        state.workflow_command_identity = "command-7".to_string();
19574        let context = WorkflowContext {
19575            state: Arc::new(Mutex::new(state)),
19576            cancellation_scope_id: "root".into(),
19577        };
19578        let item =
19579            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
19580
19581        context
19582            .append_workflow_stream("output", &[item], Some(10))
19583            .expect("append command");
19584        context
19585            .error_workflow_stream("output", "producer failed", None)
19586            .expect("error command");
19587        let commands = context.take_commands().expect("commands");
19588
19589        assert_eq!(commands[0]["type"], "record_side_effect");
19590        assert_eq!(
19591            commands[0]["workflow_stream"]["command_identity"],
19592            "command-7"
19593        );
19594        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
19595        assert_eq!(
19596            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19597            "dw-stream:command-7:0:0"
19598        );
19599        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
19600
19601        let recorded = history_event(
19602            "SideEffectRecorded",
19603            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
19604        );
19605        let mut replay_state = WorkflowState::new(
19606            vec![recorded],
19607            "rust-workers".to_string(),
19608            DEFAULT_CODEC.to_string(),
19609            None,
19610        )
19611        .expect("replay state");
19612        replay_state.workflow_command_identity = "command-7".to_string();
19613        let replay_context = WorkflowContext {
19614            state: Arc::new(Mutex::new(replay_state)),
19615            cancellation_scope_id: "root".into(),
19616        };
19617        replay_context
19618            .append_workflow_stream(
19619                "output",
19620                &[WorkflowStreamAppendItem::from_reference(
19621                    "s3://bucket/item.avro",
19622                )],
19623                Some(10),
19624            )
19625            .expect("replayed append");
19626        assert!(replay_context
19627            .take_commands()
19628            .expect("replayed commands")
19629            .is_empty());
19630    }
19631
19632    #[test]
19633    fn workflow_stream_authoring_requires_server_durable_command_identity() {
19634        let context = workflow_context(Vec::new());
19635        let error = context
19636            .append_workflow_stream(
19637                "output",
19638                &[WorkflowStreamAppendItem::from_reference(
19639                    "s3://bucket/item.avro",
19640                )],
19641                None,
19642            )
19643            .expect_err("stream append without durable command identity must fail closed");
19644
19645        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
19646        assert!(context.take_commands().expect("commands").is_empty());
19647    }
19648
19649    #[test]
19650    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
19651        let client = Client::builder("http://localhost:8080").build().unwrap();
19652        let mut worker = Worker::new(client, "rust-workers");
19653        worker.register_workflow("streams.worker", |ctx, _| async move {
19654            ctx.append_workflow_stream(
19655                "output",
19656                &[WorkflowStreamAppendItem::new(json!("hello"))?],
19657                None,
19658            )?;
19659            ctx.close_workflow_stream("output", None)?;
19660            Ok(json!("done"))
19661        });
19662        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
19663            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
19664            task.workflow_command_id = command_id.clone();
19665            let expected_identity = command_id
19666                .as_deref()
19667                .filter(|id| !id.is_empty())
19668                .unwrap_or(&task.task_id)
19669                .to_string();
19670            let commands = worker
19671                .execute_workflow_task(task)
19672                .expect("ordinary worker stream output");
19673            assert_eq!(commands.len(), 3);
19674            assert_eq!(
19675                commands[0]["workflow_stream"]["command_identity"],
19676                expected_identity
19677            );
19678            assert_eq!(
19679                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19680                format!("dw-stream:{expected_identity}:0:0")
19681            );
19682            assert_eq!(
19683                commands[1]["workflow_stream"]["command_identity"],
19684                expected_identity
19685            );
19686            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
19687            let history = commands[..2]
19688                .iter()
19689                .enumerate()
19690                .map(|(index, command)| {
19691                    history_event(
19692                        "SideEffectRecorded",
19693                        json!({"sequence":index + 1,"result":command["result"]}),
19694                    )
19695                })
19696                .collect();
19697            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
19698            replay.task_id = "replacement-task".to_string();
19699            let replayed = worker
19700                .execute_workflow_task(replay)
19701                .expect("replacement worker consumes recorded stream effects");
19702            assert_eq!(replayed.len(), 1);
19703            assert_eq!(replayed[0]["type"], "complete_workflow");
19704        }
19705        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
19706        missing.task_id.clear();
19707        assert!(matches!(
19708            worker.execute_workflow_task(missing),
19709            Err(Error::MissingWorkflowCommandIdentity)
19710        ));
19711    }
19712
19713    #[test]
19714    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
19715        fn worker(calls: Arc<AtomicUsize>) -> Worker {
19716            let client = Client::new("http://127.0.0.1:8080").expect("client");
19717            let mut worker = Worker::new(client, "rust-workers");
19718            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
19719                let calls = Arc::clone(&calls);
19720                async move {
19721                    let captured = ctx.side_effect(|| {
19722                        calls.fetch_add(1, Ordering::SeqCst);
19723                        "captured-once".to_string()
19724                    })?;
19725                    let version = ctx.get_version("cold-restart", 1, 2)?;
19726                    Ok(json!({"captured": captured, "version": version}))
19727                }
19728            });
19729            worker
19730        }
19731
19732        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
19733            WorkflowTask {
19734                task_id: "wft-side-effect-version".to_string(),
19735                workflow_command_id: None,
19736                workflow_id: Some("wf-side-effect-version".to_string()),
19737                run_id: Some("run-side-effect-version".to_string()),
19738                workflow_type: "rust.side-effect-version".to_string(),
19739                cancel_requested: false,
19740                payload_codec: DEFAULT_CODEC.to_string(),
19741                arguments: Some(
19742                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
19743                ),
19744                history_events,
19745                total_history_events: None,
19746                history_size_bytes: None,
19747                continue_as_new_recommended: None,
19748                history_budget_pressure: None,
19749                next_history_page_token: None,
19750                workflow_task_attempt: 1,
19751                workflow_signal_id: None,
19752                signal_name: None,
19753                signal_arguments: None,
19754                workflow_update_id: None,
19755                update_name: None,
19756                lease_owner: Some("rust-worker".to_string()),
19757            }
19758        }
19759
19760        let calls = Arc::new(AtomicUsize::new(0));
19761        let initial = worker(Arc::clone(&calls))
19762            .execute_workflow_task(task(Vec::new()))
19763            .expect("initial execution");
19764        assert_eq!(
19765            initial
19766                .iter()
19767                .map(|command| &command["type"])
19768                .collect::<Vec<_>>(),
19769            vec![
19770                "record_side_effect",
19771                "record_version_marker",
19772                "complete_workflow"
19773            ]
19774        );
19775        assert_eq!(calls.load(Ordering::SeqCst), 1);
19776
19777        let restarted = worker(Arc::clone(&calls));
19778        let replayed = restarted
19779            .execute_workflow_task(task(vec![
19780                history_event(
19781                    "SideEffectRecorded",
19782                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
19783                ),
19784                history_event(
19785                    "VersionMarkerRecorded",
19786                    json!({
19787                        "sequence": 2,
19788                        "change_id": "cold-restart",
19789                        "version": 2,
19790                        "min_supported": 1,
19791                        "max_supported": 2,
19792                    }),
19793                ),
19794            ]))
19795            .expect("cold replay");
19796        assert_eq!(replayed.len(), 1);
19797        assert_eq!(replayed[0]["type"], "complete_workflow");
19798        assert_eq!(calls.load(Ordering::SeqCst), 1);
19799    }
19800
19801    #[test]
19802    fn side_effect_replay_rejects_changed_rust_value_type() {
19803        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
19804        let ctx = workflow_context(vec![history_event(
19805            "SideEffectRecorded",
19806            json!({"sequence": 1, "result": result}),
19807        )]);
19808        let error = ctx
19809            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
19810            .expect_err("changed type must fail replay");
19811        assert!(matches!(
19812            error,
19813            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19814                if reason == "side_effect_type_mismatch"
19815        ));
19816    }
19817
19818    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
19819        vec![
19820            history_event(
19821                "ActivityScheduled",
19822                json!({
19823                    "sequence": 1,
19824                    "activity_type": "flaky",
19825                    "activity_execution_id": "act-1",
19826                    "activity": {
19827                        "id": "act-1",
19828                        "sequence": 1,
19829                        "type": "flaky",
19830                        "queue": "critical-activities",
19831                        "execution_mode": null,
19832                        "retry_policy": {
19833                            "snapshot_version": 1,
19834                            "max_attempts": 3,
19835                            "backoff_seconds": [2, 4],
19836                            "start_to_close_timeout": 30,
19837                            "schedule_to_start_timeout": 5,
19838                            "schedule_to_close_timeout": 90,
19839                            "heartbeat_timeout": 10,
19840                            "non_retryable_error_types": ["PermanentError"]
19841                        }
19842                    }
19843                }),
19844            ),
19845            history_event(
19846                "ActivityStarted",
19847                json!({
19848                    "sequence": 1,
19849                    "activity_type": "flaky",
19850                    "activity_execution_id": "act-1",
19851                    "activity_attempt_id": "attempt-1",
19852                    "attempt_number": 1
19853                }),
19854            ),
19855            history_event(
19856                "ActivityRetryScheduled",
19857                json!({
19858                    "sequence": 1,
19859                    "activity_type": "flaky",
19860                    "activity_execution_id": "act-1",
19861                    "activity_attempt_id": "attempt-1",
19862                    "attempt_number": 1,
19863                    "retry_after_attempt": 1,
19864                    "retry_backoff_seconds": 2,
19865                    "failure_category": "activity",
19866                    "exception_type": "TransientError"
19867                }),
19868            ),
19869            history_event(
19870                "ActivityStarted",
19871                json!({
19872                    "sequence": 1,
19873                    "activity_type": "flaky",
19874                    "activity_execution_id": "act-1",
19875                    "activity_attempt_id": "attempt-2",
19876                    "attempt_number": 2
19877                }),
19878            ),
19879            history_event(
19880                "ActivityCompleted",
19881                json!({
19882                    "sequence": 1,
19883                    "activity_type": "flaky",
19884                    "activity_execution_id": "act-1",
19885                    "activity_attempt_id": "attempt-2",
19886                    "attempt_number": 2,
19887                    "payload_codec": DEFAULT_CODEC,
19888                    "result": fixture_envelope(json!({"status":"recovered"}))
19889                }),
19890            ),
19891        ]
19892    }
19893
19894    fn retry_activity_options() -> ActivityOptions {
19895        ActivityOptions::new()
19896            .task_queue("critical-activities")
19897            .retry_policy(
19898                ActivityRetryPolicy::new(3)
19899                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
19900                    .non_retryable_error_type("PermanentError"),
19901            )
19902            .start_to_close_timeout(Duration::from_secs(30))
19903            .schedule_to_start_timeout(Duration::from_secs(5))
19904            .schedule_to_close_timeout(Duration::from_secs(90))
19905            .heartbeat_timeout(Duration::from_secs(10))
19906    }
19907
19908    #[test]
19909    fn fixed_avro_value_round_trips_json_values() {
19910        let value = json!({"greeting": "hello", "count": 3, "ok": true});
19911        let envelope = PayloadEnvelope::avro(&value).expect("encode");
19912        assert_eq!(envelope.codec, DEFAULT_CODEC);
19913        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
19914    }
19915
19916    #[tokio::test]
19917    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
19918        let client = Client::new("http://127.0.0.1:8080").expect("client");
19919        let mut worker = Worker::new(client, "rust-workers");
19920        worker.register_typed_workflow(
19921            "typed.contract.workflow",
19922            |_ctx, input: TypedContract| async move { Ok(input) },
19923        );
19924        worker.register_typed_activity(
19925            "typed.contract.activity",
19926            |_ctx, input: TypedContract| async move { Ok(input) },
19927        );
19928
19929        let expected = typed_contract();
19930        let arguments = AvroValue::Array(vec![
19931            AvroValue::from_serialize(&expected).expect("typed request")
19932        ]);
19933        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
19934        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
19935        workflow.arguments = Some(envelope.clone());
19936        let commands = worker
19937            .execute_workflow_task(workflow)
19938            .expect("typed workflow task");
19939        let workflow_result: TypedContract =
19940            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19941                .expect("workflow result envelope")
19942                .deserialize()
19943                .expect("workflow result type");
19944        assert_eq!(workflow_result, expected);
19945
19946        let activity = ActivityTask {
19947            task_id: "typed-contract-activity".to_string(),
19948            activity_attempt_id: Some("typed-contract-attempt".to_string()),
19949            attempt_id: None,
19950            activity_type: "typed.contract.activity".to_string(),
19951            payload_codec: DEFAULT_CODEC.to_string(),
19952            arguments: Some(envelope),
19953            attempt_number: 1,
19954            lease_owner: Some("rust-worker".to_string()),
19955        };
19956        let activity_result: TypedContract = worker
19957            .execute_activity_task(activity)
19958            .await
19959            .expect("typed activity task")
19960            .deserialize()
19961            .expect("activity result type");
19962        assert_eq!(activity_result, expected);
19963    }
19964
19965    #[tokio::test]
19966    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
19967        let client = Client::new("http://127.0.0.1:8080").expect("client");
19968        let mut worker = Worker::new(client, "rust-workers");
19969        worker.register_typed_workflow(
19970            "typed.shape.workflow",
19971            |_ctx, input: TypedContract| async move { Ok(input) },
19972        );
19973        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
19974            Ok(f64::NAN)
19975        });
19976
19977        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
19978        workflow.arguments = Some(
19979            encode_typed_envelope(
19980                &AvroValue::Array(vec![
19981                    AvroValue::String("first".to_string()),
19982                    AvroValue::String("second".to_string()),
19983                ]),
19984                DEFAULT_CODEC,
19985            )
19986            .expect("malformed typed arguments"),
19987        );
19988        let commands = worker
19989            .execute_workflow_task(workflow)
19990            .expect("shape mismatch becomes a workflow failure");
19991        let message = commands[0]["message"].as_str().expect("failure message");
19992        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
19993        assert!(message.contains(type_name::<TypedContract>()));
19994        assert!(message.contains("task carried 2 arguments"));
19995
19996        let activity = ActivityTask {
19997            task_id: "typed-unsupported-activity".to_string(),
19998            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
19999            attempt_id: None,
20000            activity_type: "typed.unsupported.activity".to_string(),
20001            payload_codec: DEFAULT_CODEC.to_string(),
20002            arguments: Some(
20003                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20004                    .expect("unit arguments"),
20005            ),
20006            attempt_number: 1,
20007            lease_owner: Some("rust-worker".to_string()),
20008        };
20009        let Error::HandlerType {
20010            handler_kind,
20011            handler_name,
20012            value_kind,
20013            rust_type,
20014            message,
20015        } = worker
20016            .execute_activity_task(activity)
20017            .await
20018            .expect_err("non-finite handler output must fail")
20019        else {
20020            panic!("expected contextual handler type failure");
20021        };
20022        assert_eq!(handler_kind, HandlerKind::Activity);
20023        assert_eq!(handler_name, "typed.unsupported.activity");
20024        assert_eq!(value_kind, HandlerValueKind::Result);
20025        assert_eq!(rust_type, type_name::<f64>());
20026        assert!(message.contains("non_finite_float"));
20027    }
20028
20029    #[tokio::test]
20030    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
20031        #[derive(Clone, Default)]
20032        struct State {
20033            observed: Option<TypedContract>,
20034        }
20035
20036        let client = Client::new("http://127.0.0.1:8080").expect("client");
20037        let mut worker = Worker::new(client, "rust-workers");
20038        worker.register_typed_replayed_workflow(
20039            "typed.contract.replayed",
20040            State::default,
20041            |ctx, input: TypedContract, state| async move {
20042                let result: TypedContract =
20043                    ctx.activity_typed("typed.contract.activity", input).await?;
20044                state.update(|current| current.observed = Some(result.clone()))?;
20045                Ok(result)
20046            },
20047        );
20048        worker.register_replayed_query::<State, _, _>(
20049            "typed.contract.replayed",
20050            "observed",
20051            |_ctx, state, _args| async move {
20052                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
20053            },
20054        );
20055
20056        let expected = typed_contract();
20057        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
20058        let workflow_arguments =
20059            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
20060                .expect("workflow arguments");
20061        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
20062        let task = QueryTask {
20063            query_task_id: "typed-replay-query".to_string(),
20064            query_task_attempt: 1,
20065            lease_owner: Some("rust-worker".to_string()),
20066            workflow_id: Some("typed-replay".to_string()),
20067            run_id: Some("typed-replay-run".to_string()),
20068            workflow_type: "typed.contract.replayed".to_string(),
20069            query_name: "observed".to_string(),
20070            payload_codec: DEFAULT_CODEC.to_string(),
20071            workflow_arguments: Some(workflow_arguments),
20072            query_arguments: Some(
20073                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20074                    .expect("query arguments"),
20075            ),
20076            history_events: vec![
20077                history_event(
20078                    "ActivityScheduled",
20079                    json!({
20080                        "sequence": 1,
20081                        "activity_type": "typed.contract.activity"
20082                    }),
20083                ),
20084                history_event(
20085                    "ActivityCompleted",
20086                    json!({
20087                        "sequence": 1,
20088                        "activity_type": "typed.contract.activity",
20089                        "payload_codec": DEFAULT_CODEC,
20090                        "result": result
20091                    }),
20092                ),
20093            ],
20094            history_export: None,
20095            run_status: Some("completed".to_string()),
20096        };
20097
20098        assert_eq!(
20099            worker
20100                .execute_query_task(task)
20101                .await
20102                .expect("typed replay query")
20103                .deserialize::<i64>()
20104                .expect("query result"),
20105            expected.signed
20106        );
20107    }
20108
20109    #[tokio::test]
20110    async fn update_context_preserves_workflow_input_and_committed_signals() {
20111        let client = Client::new("http://127.0.0.1:8080").expect("client");
20112        let mut worker = Worker::new(client, "rust-workers");
20113        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20114        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
20115        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
20116        let expected_input = workflow_input.clone();
20117        let expected_signals = signal_arguments.clone();
20118        let handler = move |context: QueryContext, arguments: AvroValue| {
20119            let expected_input = expected_input.clone();
20120            let expected_signals = expected_signals.clone();
20121            async move {
20122                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
20123                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
20124                assert_eq!(context.workflow_input_avro_value(), &expected_input);
20125                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
20126                assert_eq!(
20127                    context.signals_avro_value("changed"),
20128                    vec![expected_signals.clone()]
20129                );
20130                assert_eq!(
20131                    context.signals("changed"),
20132                    vec![expected_signals
20133                        .into_iter()
20134                        .map(AvroValue::into_json)
20135                        .collect::<Result<Vec<_>>>()?]
20136                );
20137                assert_eq!(
20138                    context.signal_events()[0].id.as_deref(),
20139                    Some("signal-original")
20140                );
20141                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
20142                Ok(arguments)
20143            }
20144        };
20145        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
20146        worker.register_update_avro_value("snapshot", "inspect", handler);
20147        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
20148        let update_envelope =
20149            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
20150        let mut task = workflow_task(
20151            "snapshot",
20152            vec![
20153                history_event(
20154                    "SignalReceived",
20155                    json!({
20156                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
20157                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
20158                    }),
20159                ),
20160                history_event(
20161                    "UpdateAccepted",
20162                    json!({
20163                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
20164                    }),
20165                ),
20166            ],
20167            DEFAULT_CODEC,
20168        );
20169        task.arguments =
20170            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
20171        task.workflow_update_id = Some("update-original".into());
20172        task.update_name = Some("inspect".into());
20173        let query = QueryTask {
20174            query_task_id: "query-snapshot".into(),
20175            query_task_attempt: 1,
20176            lease_owner: None,
20177            workflow_id: task.workflow_id.clone(),
20178            run_id: task.run_id.clone(),
20179            workflow_type: task.workflow_type.clone(),
20180            query_name: "inspect".into(),
20181            payload_codec: DEFAULT_CODEC.into(),
20182            workflow_arguments: task.arguments.clone(),
20183            query_arguments: Some(update_envelope),
20184            history_events: task.history_events.clone(),
20185            history_export: None,
20186            run_status: Some("running".into()),
20187        };
20188        assert_eq!(
20189            worker
20190                .execute_query_task(query)
20191                .await
20192                .expect("query snapshot"),
20193            update_arguments
20194        );
20195        for _ in 0..2 {
20196            let commands = worker
20197                .execute_workflow_task(task.clone())
20198                .expect("cold update snapshot");
20199            assert_eq!(commands[0]["type"], "complete_update");
20200            assert_eq!(commands[0]["update_id"], "update-original");
20201            assert_eq!(
20202                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20203                    .expect("update result"),
20204                update_arguments
20205            );
20206        }
20207    }
20208
20209    #[test]
20210    fn committed_signal_snapshot_counts_identities_once() {
20211        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
20212        let received = history_event(
20213            "SignalReceived",
20214            json!({
20215                "signal_id": "signal-first", "workflow_command_id": "command-first",
20216                "signal_name": "changed", "arguments": arguments.clone(),
20217            }),
20218        );
20219        let applied = history_event(
20220            "SignalApplied",
20221            json!({
20222                "signal_id": "signal-first", "workflow_command_id": "command-first",
20223                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
20224            }),
20225        );
20226        let distinct = history_event(
20227            "SignalReceived",
20228            json!({
20229                "signal_id": "signal-second", "workflow_command_id": "command-second",
20230                "signal_name": "changed", "arguments": arguments,
20231            }),
20232        );
20233        let history = vec![received.clone(), applied.clone(), distinct];
20234        let signals =
20235            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
20236        assert_eq!(signals.len(), 2);
20237        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20238        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
20239        assert_eq!(signals[0].workflow_sequence, Some(1));
20240        assert_eq!(signals[0].arguments, signals[1].arguments);
20241        let mut command_only = received.clone();
20242        command_only
20243            .payload
20244            .as_object_mut()
20245            .expect("payload")
20246            .remove("signal_id");
20247        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
20248            .expect("command identity");
20249        assert_eq!(signals.len(), 1);
20250        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20251        let mut conflicting = applied;
20252        conflicting.payload["value"] =
20253            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
20254        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
20255    }
20256
20257    #[test]
20258    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
20259        for arguments in [
20260            vec![],
20261            vec![AvroValue::Array(vec![
20262                AvroValue::Long(1),
20263                AvroValue::Long(2),
20264            ])],
20265            vec![AvroValue::Bytes(vec![0, 255])],
20266            vec![AvroValue::Null],
20267            vec![AvroValue::Boolean(false)],
20268            vec![
20269                AvroValue::Long(1),
20270                AvroValue::Array(vec![AvroValue::Long(2)]),
20271            ],
20272        ] {
20273            let applied = match arguments.as_slice() {
20274                [] => AvroValue::Boolean(true),
20275                [value] => value.clone(),
20276                values => AvroValue::Array(values.to_vec()),
20277            };
20278            for applied in [applied, AvroValue::Array(arguments.clone())] {
20279                let events = vec![
20280                    history_event(
20281                        "SignalReceived",
20282                        json!({
20283                            "signal_id": "original", "signal_name": "changed",
20284                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
20285                        }),
20286                    ),
20287                    history_event(
20288                        "SignalApplied",
20289                        json!({
20290                            "signal_id": "original", "signal_name": "changed",
20291                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
20292                        }),
20293                    ),
20294                ];
20295                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
20296                    .expect("canonical signal snapshot");
20297                assert_eq!(signals.len(), 1);
20298                assert_eq!(signals[0].avro_arguments, arguments);
20299            }
20300        }
20301    }
20302
20303    #[tokio::test]
20304    async fn update_context_rejects_malformed_snapshot_before_handler() {
20305        let client = Client::new("http://127.0.0.1:8080").expect("client");
20306        let mut worker = Worker::new(client, "rust-workers");
20307        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20308        let calls = Arc::new(AtomicUsize::new(0));
20309        let observed = Arc::clone(&calls);
20310        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
20311            observed.fetch_add(1, Ordering::SeqCst);
20312            async { Ok(Value::Null) }
20313        });
20314        let mut task = workflow_task(
20315            "snapshot",
20316            vec![history_event(
20317                "UpdateAccepted",
20318                json!({
20319                    "update_id": "update-original", "update_name": "inspect",
20320                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
20321                }),
20322            )],
20323            DEFAULT_CODEC,
20324        );
20325        task.workflow_update_id = Some("update-original".into());
20326        task.update_name = Some("inspect".into());
20327        let mut bad_input = task.clone();
20328        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
20329        assert!(worker.execute_workflow_task(bad_input).is_err());
20330        task.history_events.insert(0, history_event("SignalReceived", json!({
20331            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
20332        })));
20333        assert!(worker.execute_workflow_task(task).is_err());
20334        assert_eq!(calls.load(Ordering::SeqCst), 0);
20335    }
20336
20337    #[tokio::test]
20338    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
20339        let client = Client::new("http://127.0.0.1:8080").expect("client");
20340        let mut worker = Worker::new(client, "rust-workers");
20341        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
20342        worker
20343            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
20344        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
20345            Ok(input)
20346        });
20347        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
20348            Ok(input)
20349        });
20350        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
20351            Ok(AvroValue::Array(
20352                ctx.wait_signal_avro_value("changed").await?,
20353            ))
20354        });
20355
20356        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
20357        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
20358
20359        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
20360        workflow.arguments = Some(envelope.clone());
20361        let commands = worker
20362            .execute_workflow_task(workflow)
20363            .expect("typed workflow task");
20364        assert_eq!(commands[0]["type"], "complete_workflow");
20365        assert_eq!(
20366            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20367                .expect("typed workflow result"),
20368            arguments
20369        );
20370
20371        let activity = ActivityTask {
20372            task_id: "activity-typed".to_string(),
20373            activity_attempt_id: Some("attempt-typed".to_string()),
20374            attempt_id: None,
20375            activity_type: "typed.activity".to_string(),
20376            payload_codec: DEFAULT_CODEC.to_string(),
20377            arguments: Some(envelope.clone()),
20378            attempt_number: 1,
20379            lease_owner: Some("rust-worker".to_string()),
20380        };
20381        assert_eq!(
20382            worker
20383                .execute_activity_task(activity)
20384                .await
20385                .expect("typed activity result"),
20386            arguments
20387        );
20388
20389        let query = QueryTask {
20390            query_task_id: "query-typed".to_string(),
20391            query_task_attempt: 1,
20392            lease_owner: Some("rust-worker".to_string()),
20393            workflow_id: Some("typed-1".to_string()),
20394            run_id: Some("run-typed".to_string()),
20395            workflow_type: "typed.echo".to_string(),
20396            query_name: "inspect".to_string(),
20397            payload_codec: DEFAULT_CODEC.to_string(),
20398            workflow_arguments: Some(
20399                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20400                    .expect("workflow input"),
20401            ),
20402            query_arguments: Some(envelope.clone()),
20403            history_events: Vec::new(),
20404            history_export: None,
20405            run_status: Some("running".to_string()),
20406        };
20407        assert_eq!(
20408            worker
20409                .execute_query_task(query)
20410                .await
20411                .expect("typed query result"),
20412            arguments
20413        );
20414
20415        let mut update = workflow_task(
20416            "typed.echo",
20417            vec![history_event(
20418                "UpdateAccepted",
20419                json!({
20420                    "update_id": "update-typed",
20421                    "update_name": "replace",
20422                    "arguments": envelope.clone(),
20423                }),
20424            )],
20425            DEFAULT_CODEC,
20426        );
20427        update.workflow_update_id = Some("update-typed".to_string());
20428        update.update_name = Some("replace".to_string());
20429        let commands = worker
20430            .execute_workflow_task(update)
20431            .expect("typed update task");
20432        assert_eq!(commands[0]["type"], "complete_update");
20433        assert_eq!(
20434            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20435                .expect("typed update result"),
20436            arguments
20437        );
20438
20439        let mut signal = workflow_task(
20440            "typed.signal",
20441            vec![history_event(
20442                "SignalReceived",
20443                json!({
20444                    "signal_id": "signal-typed",
20445                    "signal_name": "changed",
20446                    "arguments": envelope.clone(),
20447                }),
20448            )],
20449            DEFAULT_CODEC,
20450        );
20451        signal.workflow_signal_id = Some("signal-typed".to_string());
20452        signal.signal_name = Some("changed".to_string());
20453        signal.signal_arguments = Some(envelope);
20454        let commands = worker
20455            .execute_workflow_task(signal)
20456            .expect("typed signal resume");
20457        assert_eq!(
20458            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20459                .expect("typed signal result"),
20460            arguments
20461        );
20462    }
20463
20464    #[tokio::test]
20465    async fn typed_helpers_never_parse_json_inspection_projection() {
20466        let collision_values = projection_collision_probe();
20467        let expected = AvroValue::Array(collision_values.clone());
20468        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
20469
20470        let activity_context = workflow_context_with_codec(
20471            vec![history_event(
20472                "ActivityCompleted",
20473                json!({
20474                    "sequence": 1,
20475                    "activity_type": "collision.activity",
20476                    "payload_codec": DEFAULT_CODEC,
20477                    "result": envelope.clone(),
20478                }),
20479            )],
20480            DEFAULT_CODEC,
20481        );
20482        assert_eq!(
20483            activity_context
20484                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
20485                .await
20486                .expect("typed activity collision result"),
20487            expected
20488        );
20489
20490        let signal_context = workflow_context_with_codec(
20491            vec![
20492                history_event(
20493                    "SignalWaitOpened",
20494                    json!({"sequence": 1, "signal_name": "collision"}),
20495                ),
20496                history_event(
20497                    "SignalApplied",
20498                    json!({
20499                        "sequence": 1,
20500                        "signal_name": "collision",
20501                        "payload_codec": DEFAULT_CODEC,
20502                        "value": envelope.clone(),
20503                    }),
20504                ),
20505            ],
20506            DEFAULT_CODEC,
20507        );
20508        assert_eq!(
20509            signal_context
20510                .wait_signal_avro_value("collision")
20511                .await
20512                .expect("typed signal collision arguments"),
20513            collision_values
20514        );
20515
20516        let child_context = workflow_context_with_codec(
20517            vec![
20518                history_event(
20519                    "ChildWorkflowScheduled",
20520                    json!({
20521                        "sequence": 1,
20522                        "child_workflow_instance_id": "collision-child",
20523                        "child_workflow_run_id": "collision-run",
20524                        "child_workflow_type": "collision.child",
20525                    }),
20526                ),
20527                history_event(
20528                    "ChildRunCompleted",
20529                    json!({
20530                        "sequence": 1,
20531                        "child_workflow_instance_id": "collision-child",
20532                        "child_workflow_run_id": "collision-run",
20533                        "child_workflow_type": "collision.child",
20534                        "payload_codec": DEFAULT_CODEC,
20535                        "result": envelope,
20536                    }),
20537                ),
20538            ],
20539            DEFAULT_CODEC,
20540        );
20541        let child = child_context
20542            .start_child_workflow_avro_value(
20543                "collision.child",
20544                ChildWorkflowOptions::new("collision-workers"),
20545                AvroValue::Array(Vec::new()),
20546            )
20547            .await
20548            .expect("typed child collision result");
20549        assert_eq!(child.result, expected);
20550    }
20551
20552    #[tokio::test]
20553    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
20554        let client = Client::new("http://127.0.0.1:8080").expect("client");
20555        let mut worker = Worker::new(client, "rust-workers");
20556        worker.register_replayed_workflow_avro_value(
20557            "typed.replayed",
20558            || (),
20559            |_ctx, input, _state| async move { Ok(input) },
20560        );
20561        worker.register_replayed_query_avro_value::<(), _, _>(
20562            "typed.replayed",
20563            "inspect",
20564            |ctx, _state, args| async move {
20565                let mut signals = ctx.signals_avro_value("collision");
20566                let signal = signals
20567                    .pop()
20568                    .map(AvroValue::Array)
20569                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
20570                Ok(AvroValue::Array(vec![
20571                    ctx.workflow_input_avro_value().clone(),
20572                    signal,
20573                    args,
20574                ]))
20575            },
20576        );
20577        let arguments = AvroValue::Array(projection_collision_probe());
20578        let signal_arguments =
20579            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
20580        let task = QueryTask {
20581            query_task_id: "query-typed-replay".to_string(),
20582            query_task_attempt: 1,
20583            lease_owner: Some("rust-worker".to_string()),
20584            workflow_id: Some("typed-replay".to_string()),
20585            run_id: Some("run-typed-replay".to_string()),
20586            workflow_type: "typed.replayed".to_string(),
20587            query_name: "inspect".to_string(),
20588            payload_codec: DEFAULT_CODEC.to_string(),
20589            workflow_arguments: Some(
20590                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
20591            ),
20592            query_arguments: Some(
20593                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
20594            ),
20595            history_events: vec![history_event(
20596                "SignalReceived",
20597                json!({
20598                    "signal_id": "collision-signal",
20599                    "signal_name": "collision",
20600                    "workflow_sequence": 1,
20601                    "payload_codec": DEFAULT_CODEC,
20602                    "arguments": signal_arguments,
20603                }),
20604            )],
20605            history_export: None,
20606            run_status: Some("completed".to_string()),
20607        };
20608
20609        assert_eq!(
20610            worker
20611                .execute_query_task(task)
20612                .await
20613                .expect("typed replay query"),
20614            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
20615        );
20616    }
20617
20618    #[test]
20619    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
20620        let value = BTreeMap::from([(1_i32, "integer key")]);
20621        let error = PayloadEnvelope::avro(&value)
20622            .expect_err("integer map keys must fail")
20623            .to_string();
20624
20625        assert!(error.contains("invalid_map_key"));
20626    }
20627
20628    #[test]
20629    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
20630        let envelope = PayloadEnvelope {
20631            codec: "json".to_string(),
20632            blob: r#"{"greeting":"hello"}"#.to_string(),
20633        };
20634
20635        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
20636        let diagnostic = error.to_string();
20637        assert!(diagnostic.contains("unsupported_payload_codec"));
20638        assert!(diagnostic.contains("codec=\"avro\""));
20639        assert!(diagnostic.contains("HTTP document transport"));
20640    }
20641
20642    #[test]
20643    fn untagged_json_payload_value_fails_closed() {
20644        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
20645            .expect_err("untagged JSON payload values must fail");
20646        let diagnostic = error.to_string();
20647        assert!(diagnostic.contains("unsupported_payload_codec"));
20648        assert!(diagnostic.contains("untagged durable payload"));
20649        assert!(diagnostic.contains("HTTP document transport"));
20650    }
20651
20652    #[test]
20653    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
20654        let envelope = PayloadEnvelope {
20655            codec: DEFAULT_CODEC.to_string(),
20656            blob: BASE64.encode([0x01]),
20657        };
20658
20659        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
20660        assert!(error.to_string().contains("invalid_payload_framing"));
20661    }
20662
20663    #[tokio::test]
20664    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
20665        let server = MockWorkerServer::start();
20666        let client = Client::builder(server.base_url())
20667            .timeout(Duration::from_secs(2))
20668            .build()
20669            .expect("client");
20670        let invalid_commands = [
20671            json!({
20672                "type": "complete_workflow",
20673                "result": {"codec": "json", "blob": null}
20674            }),
20675            json!({
20676                "type": "schedule_activity",
20677                "arguments": {"codec": "yaml", "blob": "ignored"}
20678            }),
20679            json!({
20680                "type": "start_child_workflow",
20681                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
20682            }),
20683            json!({"type": "continue_as_new", "arguments": []}),
20684            json!({"type": "complete_update"}),
20685            json!({"type": "record_side_effect", "result": null}),
20686            json!({
20687                "type": "start_service_operation",
20688                "payload_codec": DEFAULT_CODEC,
20689                "request_payload": "raw-avro-bytes"
20690            }),
20691        ];
20692
20693        for command in invalid_commands {
20694            let error = client
20695                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
20696                .await
20697                .expect_err("invalid durable payload must fail locally");
20698            let diagnostic = error.to_string();
20699            assert!(
20700                diagnostic.contains("unsupported_payload_codec")
20701                    || diagnostic.contains("invalid_payload_envelope")
20702                    || diagnostic.contains("untagged durable payload"),
20703                "unexpected validation diagnostic: {diagnostic}"
20704            );
20705        }
20706
20707        assert_eq!(
20708            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
20709            0,
20710            "invalid command payloads must not reach HTTP transport"
20711        );
20712    }
20713
20714    #[test]
20715    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
20716        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
20717        let commands = [
20718            json!({"type": "complete_workflow", "result": envelope.clone()}),
20719            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
20720            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
20721            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
20722            json!({"type": "complete_update", "result": envelope.clone()}),
20723            json!({"type": "record_side_effect", "result": envelope.clone()}),
20724            json!({
20725                "type": "start_service_operation",
20726                "payload_codec": DEFAULT_CODEC,
20727                "request_payload": envelope.clone()
20728            }),
20729            json!({
20730                "type": "complete_workflow",
20731                "result": envelope,
20732                "metadata": {
20733                    "codec": "json",
20734                    "payload_codec": "customer-codec",
20735                    "result": {"codec": "yaml", "blob": null}
20736                }
20737            }),
20738        ];
20739
20740        validate_workflow_task_commands(&commands)
20741            .expect("customer metadata must not become a protocol codec declaration");
20742    }
20743
20744    #[test]
20745    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
20746        assert_eq!(
20747            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
20748            AvroValue::Array(Vec::new())
20749        );
20750        assert_eq!(
20751            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
20752            AvroValue::Array(Vec::new())
20753        );
20754
20755        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
20756        signal.signal_name = Some("empty-signal".to_string());
20757        signal.signal_arguments = None;
20758        let decoded = decode_resume_signal(&signal)
20759            .expect("valid Avro signal")
20760            .expect("named signal resumes the workflow");
20761        assert!(decoded.arguments.is_empty());
20762    }
20763
20764    #[tokio::test]
20765    async fn malformed_task_level_codecs_become_pre_handler_failures() {
20766        let client = Client::new("http://127.0.0.1:8080").expect("client");
20767        let mut worker = Worker::new(client, "rust-workers");
20768        let handler_calls = Arc::new(AtomicUsize::new(0));
20769
20770        let calls = Arc::clone(&handler_calls);
20771        worker.register_workflow("codec.workflow", move |_ctx, _args| {
20772            calls.fetch_add(1, Ordering::SeqCst);
20773            async move { Ok(Value::Null) }
20774        });
20775        let calls = Arc::clone(&handler_calls);
20776        worker.register_activity("codec.activity", move |_ctx, _args| {
20777            calls.fetch_add(1, Ordering::SeqCst);
20778            async move { Ok(Value::Null) }
20779        });
20780        let calls = Arc::clone(&handler_calls);
20781        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20782            calls.fetch_add(1, Ordering::SeqCst);
20783            async move { Ok(Value::Null) }
20784        });
20785
20786        let mut failures = Vec::new();
20787        for codec_case in [
20788            InvalidTaskPayloadCodec::Missing,
20789            InvalidTaskPayloadCodec::Null,
20790            InvalidTaskPayloadCodec::NonString,
20791        ] {
20792            let mut workflow = json!({
20793                "task_id": format!("workflow-{}", codec_case.label()),
20794                "workflow_type": "codec.workflow"
20795            });
20796            codec_case.apply(&mut workflow);
20797            match serde_json::from_value::<WorkflowTask>(workflow) {
20798                Ok(task) => match worker.execute_workflow_task(task) {
20799                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
20800                    outcome => failures.push(format!(
20801                        "workflow {} codec returned {outcome:?}",
20802                        codec_case.label()
20803                    )),
20804                },
20805                Err(error) => failures.push(format!(
20806                    "workflow {} codec failed transport deserialization: {error}",
20807                    codec_case.label()
20808                )),
20809            }
20810
20811            let mut activity = json!({
20812                "task_id": format!("activity-{}", codec_case.label()),
20813                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
20814                "activity_type": "codec.activity",
20815                "attempt_number": 1
20816            });
20817            codec_case.apply(&mut activity);
20818            match serde_json::from_value::<ActivityTask>(activity) {
20819                Ok(task) => match worker.execute_activity_task(task).await {
20820                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
20821                    outcome => failures.push(format!(
20822                        "activity {} codec returned {outcome:?}",
20823                        codec_case.label()
20824                    )),
20825                },
20826                Err(error) => failures.push(format!(
20827                    "activity {} codec failed transport deserialization: {error}",
20828                    codec_case.label()
20829                )),
20830            }
20831
20832            let mut query = json!({
20833                "query_task_id": format!("query-{}", codec_case.label()),
20834                "workflow_type": "codec.workflow",
20835                "query_name": "known"
20836            });
20837            codec_case.apply(&mut query);
20838            match serde_json::from_value::<QueryTask>(query) {
20839                Ok(task) => match worker.execute_query_task(task).await {
20840                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
20841                    outcome => failures.push(format!(
20842                        "query {} codec returned {outcome:?}",
20843                        codec_case.label()
20844                    )),
20845                },
20846                Err(error) => failures.push(format!(
20847                    "query {} codec failed transport deserialization: {error}",
20848                    codec_case.label()
20849                )),
20850            }
20851        }
20852
20853        assert!(failures.is_empty(), "{}", failures.join("\n"));
20854        assert_eq!(
20855            handler_calls.load(Ordering::SeqCst),
20856            0,
20857            "invalid task codecs must not invoke a handler"
20858        );
20859    }
20860
20861    #[tokio::test]
20862    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
20863        for codec_case in [
20864            InvalidTaskPayloadCodec::Missing,
20865            InvalidTaskPayloadCodec::Null,
20866            InvalidTaskPayloadCodec::NonString,
20867        ] {
20868            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
20869            let client = Client::builder(server.base_url())
20870                .timeout(Duration::from_secs(2))
20871                .build()
20872                .expect("client");
20873            let mut worker = Worker::new(client, "rust-workers")
20874                .worker_id("codec-worker")
20875                .poll_timeout(Duration::from_millis(10));
20876            let handler_calls = Arc::new(AtomicUsize::new(0));
20877
20878            let calls = Arc::clone(&handler_calls);
20879            worker.register_workflow("codec.workflow", move |_ctx, _args| {
20880                calls.fetch_add(1, Ordering::SeqCst);
20881                async move { Ok(Value::Null) }
20882            });
20883            let calls = Arc::clone(&handler_calls);
20884            worker.register_activity("codec.activity", move |_ctx, _args| {
20885                calls.fetch_add(1, Ordering::SeqCst);
20886                async move { Ok(Value::Null) }
20887            });
20888            let calls = Arc::clone(&handler_calls);
20889            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20890                calls.fetch_add(1, Ordering::SeqCst);
20891                async move { Ok(Value::Null) }
20892            });
20893
20894            assert_eq!(
20895                worker.run_once().await.expect("invalid tasks are settled"),
20896                3,
20897                "all {} codec tasks must be handled",
20898                codec_case.label()
20899            );
20900            assert_eq!(
20901                handler_calls.load(Ordering::SeqCst),
20902                0,
20903                "{} task codecs must fail before every handler",
20904                codec_case.label()
20905            );
20906
20907            for path in [
20908                "/api/worker/workflow-tasks/codec-workflow/fail",
20909                "/api/worker/activity-tasks/codec-activity/fail",
20910                "/api/worker/query-tasks/codec-query/fail",
20911            ] {
20912                let body = server.request_body(path);
20913                assert!(
20914                    body["failure"]["message"]
20915                        .as_str()
20916                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
20917                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
20918                    codec_case.label()
20919                );
20920            }
20921            assert_eq!(
20922                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
20923                    ["reason"],
20924                "query_payload_decode_failed"
20925            );
20926            for path in [
20927                "/api/worker/workflow-tasks/codec-workflow/complete",
20928                "/api/worker/activity-tasks/codec-activity/complete",
20929                "/api/worker/query-tasks/codec-query/complete",
20930            ] {
20931                assert_eq!(
20932                    server.request_count(path),
20933                    0,
20934                    "invalid {} codec task reached {path}",
20935                    codec_case.label()
20936                );
20937            }
20938        }
20939    }
20940
20941    #[tokio::test]
20942    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
20943        let client = Client::new("http://127.0.0.1:8080").expect("client");
20944        let mut worker = Worker::new(client, "rust-workers");
20945        let handler_calls = Arc::new(AtomicUsize::new(0));
20946
20947        let calls = Arc::clone(&handler_calls);
20948        worker.register_workflow("codec.workflow", move |_ctx, _args| {
20949            calls.fetch_add(1, Ordering::SeqCst);
20950            async move { Ok(Value::Null) }
20951        });
20952        let calls = Arc::clone(&handler_calls);
20953        worker.register_activity("codec.activity", move |_ctx, _args| {
20954            calls.fetch_add(1, Ordering::SeqCst);
20955            async move { Ok(Value::Null) }
20956        });
20957        let calls = Arc::clone(&handler_calls);
20958        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
20959            calls.fetch_add(1, Ordering::SeqCst);
20960            async move { Ok(Value::Null) }
20961        });
20962        let calls = Arc::clone(&handler_calls);
20963        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
20964            calls.fetch_add(1, Ordering::SeqCst);
20965            async move { Ok(Value::Null) }
20966        });
20967
20968        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20969        workflow.payload_codec = "json".to_string();
20970        workflow.arguments = None;
20971        let error = worker
20972            .execute_workflow_task(workflow)
20973            .expect_err("task codec must be checked before workflow invocation");
20974        assert!(error.to_string().contains("unsupported_payload_codec"));
20975
20976        let activity = ActivityTask {
20977            task_id: "activity-invalid-codec".to_string(),
20978            activity_attempt_id: None,
20979            attempt_id: None,
20980            activity_type: "codec.activity".to_string(),
20981            payload_codec: "unknown".to_string(),
20982            arguments: None,
20983            attempt_number: 1,
20984            lease_owner: None,
20985        };
20986        let error = worker
20987            .execute_activity_task(activity)
20988            .await
20989            .expect_err("task codec must be checked before activity invocation");
20990        assert!(error.to_string().contains("unsupported_payload_codec"));
20991
20992        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
20993        update.workflow_update_id = Some("update-invalid-codec".to_string());
20994        update.update_name = Some("known".to_string());
20995        update.history_events.push(history_event(
20996            "UpdateAccepted",
20997            json!({
20998                "update_id": "update-invalid-codec",
20999                "update_name": "known",
21000                "arguments": {"codec": "json", "blob": null}
21001            }),
21002        ));
21003        let error = worker
21004            .execute_workflow_task(update)
21005            .expect_err("nested update codec must be checked before handler lookup");
21006        assert!(error.to_string().contains("unsupported_payload_codec"));
21007
21008        let query: QueryTask = serde_json::from_value(json!({
21009            "query_task_id": "query-invalid-codec",
21010            "workflow_type": "codec.workflow",
21011            "query_name": "known",
21012            "payload_codec": DEFAULT_CODEC,
21013            "workflow_arguments": null,
21014            "query_arguments": null,
21015            "history_export": {
21016                "payloads": {"codec": DEFAULT_CODEC},
21017                "signals": [{
21018                    "name": "empty",
21019                    "payload_codec": "json",
21020                    "arguments": null
21021                }]
21022            }
21023        }))
21024        .expect("query task");
21025        let failure = worker
21026            .execute_query_task(query)
21027            .await
21028            .expect_err("exported signal codec must be checked before query invocation");
21029        assert_eq!(failure.reason, "query_payload_decode_failed");
21030        assert!(failure.message.contains("unsupported_payload_codec"));
21031
21032        let exported_history: QueryTask = serde_json::from_value(json!({
21033            "query_task_id": "query-invalid-history-codec",
21034            "workflow_type": "codec.workflow",
21035            "query_name": "known",
21036            "payload_codec": DEFAULT_CODEC,
21037            "history_export": {
21038                "payloads": {"codec": DEFAULT_CODEC},
21039                "history_events": [{
21040                    "type": "ActivityCompleted",
21041                    "payload": {"payload_codec": "unknown", "result": null}
21042                }]
21043            }
21044        }))
21045        .expect("query task");
21046        let failure = worker
21047            .execute_query_task(exported_history)
21048            .await
21049            .expect_err("exported history codec must be checked before query invocation");
21050        assert_eq!(failure.reason, "query_payload_decode_failed");
21051        assert!(failure.message.contains("unsupported_payload_codec"));
21052        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
21053
21054        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21055        unknown_workflow.arguments = None;
21056        unknown_workflow.history_events.push(history_event(
21057            "SignalReceived",
21058            json!({
21059                "signal_name": "empty",
21060                "payload_codec": "json",
21061                "arguments": null
21062            }),
21063        ));
21064        let error = worker
21065            .execute_workflow_task(unknown_workflow)
21066            .expect_err("history codec must precede unknown workflow outcome");
21067        assert!(error.to_string().contains("unsupported_payload_codec"));
21068
21069        let unknown_activity = ActivityTask {
21070            task_id: "activity-unknown".to_string(),
21071            activity_attempt_id: None,
21072            attempt_id: None,
21073            activity_type: "missing".to_string(),
21074            payload_codec: "json".to_string(),
21075            arguments: None,
21076            attempt_number: 1,
21077            lease_owner: None,
21078        };
21079        let error = worker
21080            .execute_activity_task(unknown_activity)
21081            .await
21082            .expect_err("codec must precede unknown activity outcome");
21083        assert!(error.to_string().contains("unsupported_payload_codec"));
21084
21085        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21086        unknown_update.payload_codec = "json".to_string();
21087        unknown_update.arguments = None;
21088        unknown_update.workflow_update_id = Some("update-unknown".to_string());
21089        unknown_update.update_name = Some("missing".to_string());
21090        let error = worker
21091            .execute_workflow_task(unknown_update)
21092            .expect_err("codec must precede fail_update shortcut");
21093        assert!(error.to_string().contains("unsupported_payload_codec"));
21094
21095        let unknown_query: QueryTask = serde_json::from_value(json!({
21096            "query_task_id": "query-unknown",
21097            "workflow_type": "missing",
21098            "query_name": "missing",
21099            "payload_codec": "json",
21100            "workflow_arguments": null,
21101            "query_arguments": null
21102        }))
21103        .expect("query task");
21104        let failure = worker
21105            .execute_query_task(unknown_query)
21106            .await
21107            .expect_err("codec must precede unknown query outcome");
21108        assert_eq!(failure.reason, "query_payload_decode_failed");
21109        assert!(failure.message.contains("unsupported_payload_codec"));
21110    }
21111
21112    #[tokio::test]
21113    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
21114        let client = Client::new("http://127.0.0.1:8080").expect("client");
21115        let worker = Worker::new(client, "rust-workers");
21116
21117        for event_type in ["SignalReceived", "SignalApplied"] {
21118            for (payload_field, codec) in [
21119                ("value", "json"),
21120                ("input", "unknown"),
21121                ("arguments", "json"),
21122            ] {
21123                let payload = json!({
21124                    "signal_name": "empty",
21125                    payload_field: {"codec": codec, "blob": null}
21126                });
21127                let workflow = workflow_task(
21128                    "missing",
21129                    vec![history_event(event_type, payload.clone())],
21130                    DEFAULT_CODEC,
21131                );
21132                let error = worker
21133                    .execute_workflow_task(workflow)
21134                    .expect_err("signal payload codec must precede unknown workflow outcome");
21135                assert!(
21136                    error.to_string().contains("unsupported_payload_codec"),
21137                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
21138                );
21139
21140                let query: QueryTask = serde_json::from_value(json!({
21141                    "query_task_id": format!("query-{event_type}-{payload_field}"),
21142                    "workflow_type": "missing",
21143                    "query_name": "missing",
21144                    "payload_codec": DEFAULT_CODEC,
21145                    "workflow_arguments": null,
21146                    "query_arguments": null,
21147                    "history_events": [{
21148                        "event_type": event_type,
21149                        "payload": payload
21150                    }]
21151                }))
21152                .expect("query task");
21153                let failure = worker
21154                    .execute_query_task(query)
21155                    .await
21156                    .expect_err("signal payload codec must precede unknown query outcome");
21157                assert_eq!(
21158                    failure.reason, "query_payload_decode_failed",
21159                    "{event_type}.{payload_field} returned an unrelated query outcome"
21160                );
21161                assert!(
21162                    failure.message.contains("unsupported_payload_codec"),
21163                    "{event_type}.{payload_field} returned an unrelated query error: {}",
21164                    failure.message
21165                );
21166            }
21167        }
21168    }
21169
21170    #[test]
21171    fn workflow_context_schedules_activity_until_completion_is_in_history() {
21172        let ctx = WorkflowContext {
21173            cancellation_scope_id: "root".into(),
21174            state: Arc::new(Mutex::new(
21175                WorkflowState::new_with_identity(
21176                    Vec::new(),
21177                    Some("wf-parent".to_string()),
21178                    Some("run-parent".to_string()),
21179                    "rust-workers".to_string(),
21180                    DEFAULT_CODEC.to_string(),
21181                    None,
21182                )
21183                .expect("workflow state"),
21184            )),
21185        };
21186
21187        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
21188        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21189        assert!(matches!(
21190            call.as_mut().poll(&mut task_context),
21191            Poll::Pending
21192        ));
21193
21194        let commands = ctx.take_commands().expect("commands");
21195        assert_eq!(commands[0]["type"], "schedule_activity");
21196        assert_eq!(commands[0]["activity_type"], "hello.activity");
21197    }
21198
21199    #[test]
21200    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
21201        let ctx = workflow_context(Vec::new());
21202        let options = ActivityOptions::new()
21203            .task_queue("payments")
21204            .retry_policy(
21205                ActivityRetryPolicy::new(4)
21206                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
21207                    .non_retryable_error_type("ValidationError"),
21208            )
21209            .start_to_close_timeout(Duration::from_secs(120))
21210            .schedule_to_start_timeout(Duration::from_secs(10))
21211            .schedule_to_close_timeout(Duration::from_secs(300))
21212            .heartbeat_timeout(Duration::from_secs(15));
21213        let mut call = Box::pin(ctx.activity_with_options(
21214            "charge-card",
21215            options,
21216            json!([{"order_id": "o-1"}]),
21217        ));
21218        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21219
21220        assert!(matches!(
21221            call.as_mut().poll(&mut task_context),
21222            Poll::Pending
21223        ));
21224        assert!(matches!(
21225            call.as_mut().poll(&mut task_context),
21226            Poll::Pending
21227        ));
21228
21229        let commands = ctx.take_commands().expect("activity command");
21230        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
21231        assert_eq!(commands[0]["queue"], "payments");
21232        assert_eq!(
21233            commands[0]["retry_policy"],
21234            json!({
21235                "max_attempts": 4,
21236                "backoff_seconds": [1, 3, 9],
21237                "non_retryable_error_types": ["ValidationError"],
21238            })
21239        );
21240        assert_eq!(commands[0]["start_to_close_timeout"], 120);
21241        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
21242        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
21243        assert_eq!(commands[0]["heartbeat_timeout"], 15);
21244    }
21245
21246    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
21247        vec![
21248            history_event(
21249                "ActivityScheduled",
21250                json!({"sequence":1,"activity_type":"render",
21251                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
21252            ),
21253            history_event(
21254                "ActivityCompleted",
21255                json!({"sequence":1,"activity_type":"render",
21256                "payload_codec":DEFAULT_CODEC,
21257                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
21258            ),
21259        ]
21260    }
21261
21262    #[test]
21263    fn worker_session_activity_routes_to_session_queue_once() {
21264        let ctx = workflow_context(Vec::new());
21265        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21266        let mut call = Box::pin(
21267            ctx.activity("render", json!([]))
21268                .in_worker_session(session.clone()),
21269        );
21270        let mut cx = TaskContext::from_waker(noop_waker_ref());
21271        assert!(call.as_mut().poll(&mut cx).is_pending());
21272        assert!(call.as_mut().poll(&mut cx).is_pending());
21273        let commands = ctx.take_commands().unwrap();
21274        assert_eq!(commands.len(), 1);
21275        assert_eq!(commands[0]["queue"], "gpu-workers");
21276        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
21277    }
21278
21279    #[tokio::test]
21280    async fn worker_session_cold_replay_uses_recorded_avro_result() {
21281        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21282        for _replacement in 0..2 {
21283            let ctx = workflow_context(completed_worker_session_history(&session));
21284            let result: i64 = ctx
21285                .activity("render", json!([]))
21286                .in_worker_session(session.clone())
21287                .typed()
21288                .await
21289                .unwrap();
21290            assert_eq!(result, 42);
21291            assert!(ctx.take_commands().unwrap().is_empty());
21292        }
21293    }
21294
21295    #[test]
21296    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
21297        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21298        for changed in [
21299            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
21300            Some(original.clone().ttl_seconds(60)),
21301            Some(original.clone().requirements(["gpu:l4"])),
21302            None,
21303        ] {
21304            let ctx = workflow_context(completed_worker_session_history(&original));
21305            let mut call = ctx.activity_with_options(
21306                "render",
21307                ActivityOptions::new().task_queue("gpu-workers"),
21308                json!([]),
21309            );
21310            if let Some(changed) = changed {
21311                call = call.in_worker_session(changed);
21312            }
21313            let mut call = Box::pin(call);
21314            let mut cx = TaskContext::from_waker(noop_waker_ref());
21315            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21316                call.as_mut().poll(&mut cx)
21317            else {
21318                panic!("changed session must fail replay");
21319            };
21320            assert_eq!(failure.reason, "activity_worker_session_mismatch");
21321            assert!(ctx.take_commands().unwrap().is_empty());
21322        }
21323    }
21324
21325    #[test]
21326    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
21327        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21328        let ctx = workflow_context(Vec::new());
21329        let mut local = Box::pin(
21330            ctx.local_activity("render", json!([]))
21331                .in_worker_session(session.clone()),
21332        );
21333        let mut cx = TaskContext::from_waker(noop_waker_ref());
21334        assert!(matches!(
21335            local.as_mut().poll(&mut cx),
21336            Poll::Ready(Err(Error::WorkerLoop(_)))
21337        ));
21338        assert!(ctx.take_commands().unwrap().is_empty());
21339        let mut remote = Box::pin(
21340            ctx.activity_with_options(
21341                "render",
21342                ActivityOptions::new().task_queue("other"),
21343                json!([]),
21344            )
21345            .in_worker_session(session),
21346        );
21347        assert!(matches!(
21348            remote.as_mut().poll(&mut cx),
21349            Poll::Ready(Err(Error::WorkerLoop(_)))
21350        ));
21351        assert!(ctx.take_commands().unwrap().is_empty());
21352    }
21353
21354    #[test]
21355    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
21356        let ctx = workflow_context(Vec::new());
21357        let options = ActivityOptions::new().retry_policy(
21358            ActivityRetryPolicy::new(3)
21359                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
21360        );
21361        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21362        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21363
21364        assert!(matches!(
21365            call.as_mut().poll(&mut task_context),
21366            Poll::Pending
21367        ));
21368        assert_eq!(
21369            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
21370            json!([1, 2])
21371        );
21372    }
21373
21374    #[test]
21375    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
21376        let cases = [
21377            (
21378                ActivityOptions::new().task_queue("  "),
21379                ActivityOptionsErrorKind::EmptyTaskQueue,
21380            ),
21381            (
21382                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
21383                ActivityOptionsErrorKind::EmptyRetryPolicy,
21384            ),
21385            (
21386                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
21387                ActivityOptionsErrorKind::InvalidMaxAttempts,
21388            ),
21389            (
21390                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
21391                    max_attempts: None,
21392                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
21393                    non_retryable_error_types: Vec::new(),
21394                }),
21395                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
21396            ),
21397            (
21398                ActivityOptions::new().retry_policy(
21399                    ActivityRetryPolicy::new(2)
21400                        .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
21401                ),
21402                ActivityOptionsErrorKind::TooManyBackoffIntervals,
21403            ),
21404            (
21405                ActivityOptions::new().retry_policy(
21406                    ActivityRetryPolicy::new(2).exponential_backoff(
21407                        Duration::from_secs(1),
21408                        0,
21409                        None,
21410                    ),
21411                ),
21412                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
21413            ),
21414            (
21415                ActivityOptions::new()
21416                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
21417                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
21418            ),
21419            (
21420                ActivityOptions::new().retry_policy(
21421                    ActivityRetryPolicy::new(10_002).exponential_backoff(
21422                        Duration::from_secs(1),
21423                        1,
21424                        None,
21425                    ),
21426                ),
21427                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
21428            ),
21429            (
21430                ActivityOptions::new().retry_policy(
21431                    ActivityRetryPolicy::new(2)
21432                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
21433                ),
21434                ActivityOptionsErrorKind::BackoffOverflow,
21435            ),
21436        ];
21437
21438        for (options, expected_kind) in cases {
21439            let ctx = workflow_context(Vec::new());
21440            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21441            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21442            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
21443                call.as_mut().poll(&mut task_context)
21444            else {
21445                panic!("expected typed activity validation error");
21446            };
21447            assert_eq!(error.kind, expected_kind);
21448            assert!(ctx.take_commands().expect("commands").is_empty());
21449        }
21450    }
21451
21452    #[test]
21453    fn activity_options_validate_positive_and_ordered_timeouts() {
21454        let zero_timeout_cases = [
21455            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
21456            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
21457            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
21458            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
21459        ];
21460        for options in zero_timeout_cases {
21461            assert_eq!(
21462                options.validate().expect_err("zero timeout").kind,
21463                ActivityOptionsErrorKind::TimeoutNotPositive
21464            );
21465        }
21466
21467        let ordering_cases = [
21468            ActivityOptions::new()
21469                .heartbeat_timeout(Duration::from_secs(11))
21470                .start_to_close_timeout(Duration::from_secs(10)),
21471            ActivityOptions::new()
21472                .start_to_close_timeout(Duration::from_secs(31))
21473                .schedule_to_close_timeout(Duration::from_secs(30)),
21474            ActivityOptions::new()
21475                .schedule_to_start_timeout(Duration::from_secs(31))
21476                .schedule_to_close_timeout(Duration::from_secs(30)),
21477        ];
21478        for options in ordering_cases {
21479            assert_eq!(
21480                options.validate().expect_err("timeout order").kind,
21481                ActivityOptionsErrorKind::TimeoutOrder
21482            );
21483        }
21484
21485        assert_eq!(
21486            ActivityOptions::new()
21487                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
21488                .validate()
21489                .expect_err("protocol integer overflow")
21490                .kind,
21491            ActivityOptionsErrorKind::TimeoutOverflow
21492        );
21493    }
21494
21495    #[test]
21496    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
21497        let ctx = workflow_context(completed_retry_activity_history());
21498        let mut call =
21499            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21500        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21501
21502        assert!(matches!(
21503            call.as_mut().poll(&mut task_context),
21504            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21505        ));
21506        assert!(ctx.take_commands().expect("commands").is_empty());
21507        ctx.ensure_history_consumed().expect("history consumed");
21508    }
21509
21510    #[test]
21511    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
21512        let mut options = retry_activity_options();
21513        options
21514            .retry_policy
21515            .as_mut()
21516            .expect("retry policy")
21517            .non_retryable_error_types
21518            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
21519
21520        let new_ctx = workflow_context(Vec::new());
21521        let mut new_call =
21522            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
21523        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21524        assert!(matches!(
21525            new_call.as_mut().poll(&mut task_context),
21526            Poll::Pending
21527        ));
21528        let commands = new_ctx.take_commands().expect("commands");
21529        assert_eq!(commands.len(), 1);
21530        assert_eq!(
21531            commands[0]["retry_policy"]["non_retryable_error_types"],
21532            json!(["PermanentError"])
21533        );
21534
21535        let replay_ctx = workflow_context(completed_retry_activity_history());
21536        let mut replay_call =
21537            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
21538        assert!(matches!(
21539            replay_call.as_mut().poll(&mut task_context),
21540            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21541        ));
21542        assert!(replay_ctx.take_commands().expect("commands").is_empty());
21543        replay_ctx
21544            .ensure_history_consumed()
21545            .expect("history consumed");
21546    }
21547
21548    #[test]
21549    fn replayed_intermediate_retry_remains_pending_across_restarts() {
21550        let history = completed_retry_activity_history()
21551            .into_iter()
21552            .take(3)
21553            .collect::<Vec<_>>();
21554
21555        for _restart in 0..2 {
21556            let ctx = workflow_context(history.clone());
21557            let mut call =
21558                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21559            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21560            assert!(matches!(
21561                call.as_mut().poll(&mut task_context),
21562                Poll::Pending
21563            ));
21564            assert!(ctx.take_commands().expect("commands").is_empty());
21565        }
21566    }
21567
21568    #[test]
21569    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
21570        let mut changed_queue = retry_activity_options();
21571        changed_queue.task_queue = Some("different-queue".to_string());
21572
21573        let mut changed_max_attempts = retry_activity_options();
21574        let retry_policy = changed_max_attempts
21575            .retry_policy
21576            .as_mut()
21577            .expect("retry policy");
21578        retry_policy.max_attempts = Some(4);
21579
21580        let mut changed_backoff = retry_activity_options();
21581        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
21582        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
21583            Duration::from_secs(3),
21584            Duration::from_secs(4),
21585        ]));
21586
21587        let mut changed_non_retryable_types = retry_activity_options();
21588        let retry_policy = changed_non_retryable_types
21589            .retry_policy
21590            .as_mut()
21591            .expect("retry policy");
21592        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
21593
21594        let mut changed_start_to_close = retry_activity_options();
21595        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
21596        let mut changed_schedule_to_start = retry_activity_options();
21597        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
21598        let mut changed_schedule_to_close = retry_activity_options();
21599        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
21600        let mut changed_heartbeat = retry_activity_options();
21601        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
21602
21603        let cases = [
21604            (changed_queue, "activity_task_queue_mismatch"),
21605            (changed_max_attempts, "activity_retry_policy_mismatch"),
21606            (changed_backoff, "activity_retry_policy_mismatch"),
21607            (
21608                changed_non_retryable_types,
21609                "activity_retry_policy_mismatch",
21610            ),
21611            (changed_start_to_close, "activity_retry_policy_mismatch"),
21612            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
21613            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
21614            (changed_heartbeat, "activity_retry_policy_mismatch"),
21615        ];
21616
21617        for (options, expected_reason) in cases {
21618            let ctx = workflow_context(completed_retry_activity_history());
21619            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
21620            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21621            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21622                call.as_mut().poll(&mut task_context)
21623            else {
21624                panic!("changed activity options must fail replay");
21625            };
21626            assert_eq!(failure.reason, expected_reason);
21627            assert_eq!(failure.sequence, Some(1));
21628            assert!(ctx.take_commands().expect("commands").is_empty());
21629        }
21630    }
21631
21632    #[test]
21633    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
21634        let cases = [
21635            (
21636                "execution_mode",
21637                json!("local"),
21638                "activity_execution_mode_mismatch",
21639            ),
21640            (
21641                "snapshot_version",
21642                json!(2),
21643                "activity_retry_policy_mismatch",
21644            ),
21645        ];
21646
21647        for (field, value, expected_reason) in cases {
21648            let mut history = completed_retry_activity_history();
21649            let activity = history[0].payload["activity"]
21650                .as_object_mut()
21651                .expect("activity snapshot");
21652            if field == "execution_mode" {
21653                activity.insert(field.to_string(), value);
21654            } else {
21655                activity["retry_policy"]
21656                    .as_object_mut()
21657                    .expect("retry snapshot")
21658                    .insert(field.to_string(), value);
21659            }
21660
21661            let ctx = workflow_context(history);
21662            let mut call =
21663                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21664            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21665            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21666                call.as_mut().poll(&mut task_context)
21667            else {
21668                panic!("changed {field} must fail replay");
21669            };
21670            assert_eq!(failure.reason, expected_reason);
21671            assert_eq!(failure.sequence, Some(1));
21672            assert!(ctx.take_commands().expect("commands").is_empty());
21673        }
21674    }
21675
21676    #[test]
21677    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
21678        for (nested, field, value, terminal_only) in [
21679            (false, "execution_mode", json!("local"), false),
21680            (false, "local_activity", json!(true), false),
21681            (true, "local_activity", json!(true), false),
21682            (false, "local_activity", json!(true), true),
21683        ] {
21684            let mut history = completed_retry_activity_history();
21685            history[0]
21686                .payload
21687                .as_object_mut()
21688                .unwrap()
21689                .remove("activity");
21690            let event = if terminal_only {
21691                history.last_mut().unwrap()
21692            } else {
21693                &mut history[0]
21694            };
21695            if nested {
21696                event.payload["activity"] = json!({(field): value});
21697            } else {
21698                event.payload[field] = value;
21699            }
21700            let ctx = workflow_context(history);
21701            let mut call =
21702                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21703            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21704            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21705                call.as_mut().poll(&mut task_context)
21706            else {
21707                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
21708            };
21709            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
21710            assert_eq!(failure.sequence, Some(1));
21711            assert!(ctx.take_commands().expect("commands").is_empty());
21712        }
21713    }
21714
21715    #[test]
21716    fn activity_history_rejects_conflicting_local_execution_markers() {
21717        let mut history = completed_retry_activity_history();
21718        history.last_mut().unwrap().payload["local_activity"] = json!(true);
21719        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
21720            .expect_err("remote schedule cannot become a local completion");
21721        assert!(
21722            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
21723            if reason == "activity_execution_mode_conflict")
21724        );
21725    }
21726
21727    #[test]
21728    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
21729        let mut history = completed_retry_activity_history();
21730        let activity = history[0].payload["activity"]
21731            .as_object_mut()
21732            .expect("activity snapshot");
21733        activity.remove("execution_mode");
21734        activity.remove("retry_policy");
21735
21736        let mut current = retry_activity_options();
21737        current.start_to_close_timeout = Some(Duration::from_secs(45));
21738        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
21739        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
21740        current.heartbeat_timeout = Some(Duration::from_secs(12));
21741
21742        let ctx = workflow_context(history);
21743        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
21744        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21745        assert!(matches!(
21746            call.as_mut().poll(&mut task_context),
21747            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21748        ));
21749        assert!(ctx.take_commands().expect("commands").is_empty());
21750        ctx.ensure_history_consumed().expect("history consumed");
21751    }
21752
21753    #[test]
21754    fn terminal_activity_failed_after_start_returns_typed_failure() {
21755        let history = vec![
21756            history_event(
21757                "ActivityScheduled",
21758                json!({
21759                    "sequence": 1,
21760                    "activity_type": "flaky",
21761                    "activity_execution_id": "act-terminal",
21762                    "activity": {
21763                        "id": "act-terminal",
21764                        "sequence": 1,
21765                        "type": "flaky",
21766                        "queue": "critical-activities",
21767                        "retry_policy": {
21768                            "snapshot_version": 1,
21769                            "max_attempts": 3,
21770                            "backoff_seconds": [2, 4],
21771                            "non_retryable_error_types": ["PermanentError"]
21772                        }
21773                    }
21774                }),
21775            ),
21776            history_event(
21777                "ActivityStarted",
21778                json!({
21779                    "sequence": 1,
21780                    "activity_type": "flaky",
21781                    "activity_execution_id": "act-terminal",
21782                    "activity_attempt_id": "attempt-1",
21783                    "attempt_number": 1
21784                }),
21785            ),
21786            history_event(
21787                "ActivityFailed",
21788                json!({
21789                    "sequence": 1,
21790                    "activity_type": "flaky",
21791                    "activity_execution_id": "act-terminal",
21792                    "activity_attempt_id": "attempt-1",
21793                    "attempt_number": 1,
21794                    "failure_id": "failure-terminal",
21795                    "failure_category": "activity",
21796                    "exception_type": "PermanentError",
21797                    "message": "cannot retry",
21798                    "non_retryable": true
21799                }),
21800            ),
21801        ];
21802        let ctx = workflow_context(history);
21803        let mut call =
21804            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21805        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21806
21807        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21808            call.as_mut().poll(&mut task_context)
21809        else {
21810            panic!("terminal ActivityFailed must settle the activity future");
21811        };
21812        assert_eq!(failure.kind, ActivityFailureKind::Failed);
21813        assert_eq!(
21814            failure.activity_execution_id.as_deref(),
21815            Some("act-terminal")
21816        );
21817        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
21818        assert!(failure.non_retryable);
21819        assert!(ctx.take_commands().expect("commands").is_empty());
21820        ctx.ensure_history_consumed().expect("history consumed");
21821    }
21822
21823    #[test]
21824    fn activity_terminal_events_return_machine_readable_failures() {
21825        let cases = [
21826            (
21827                "ActivityFailed",
21828                json!({
21829                    "sequence": 1,
21830                    "activity_type": "charge-card",
21831                    "activity_execution_id": "act-1",
21832                    "activity_attempt_id": "attempt-2",
21833                    "attempt_number": 2,
21834                    "failure_id": "failure-1",
21835                    "failure_category": "activity",
21836                    "exception_type": "PaymentDeclined",
21837                    "exception_class": "payments.PaymentDeclined",
21838                    "message": "card declined",
21839                    "non_retryable": true
21840                }),
21841                ActivityFailureKind::Failed,
21842                "activity",
21843            ),
21844            (
21845                "ActivityCancelled",
21846                json!({
21847                    "sequence": 1,
21848                    "activity_type": "charge-card",
21849                    "activity_execution_id": "act-1",
21850                    "activity_attempt_id": "attempt-1"
21851                }),
21852                ActivityFailureKind::Cancelled,
21853                "cancelled",
21854            ),
21855        ];
21856
21857        for (event_type, payload, expected_kind, expected_reason) in cases {
21858            let ctx = workflow_context(vec![history_event(event_type, payload)]);
21859            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
21860            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21861            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21862                call.as_mut().poll(&mut task_context)
21863            else {
21864                panic!("expected terminal activity failure");
21865            };
21866            assert_eq!(failure.kind, expected_kind);
21867            assert_eq!(failure.reason, expected_reason);
21868            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
21869            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
21870        }
21871    }
21872
21873    #[test]
21874    fn every_activity_timeout_class_is_typed() {
21875        for timeout_kind in [
21876            "start_to_close",
21877            "schedule_to_start",
21878            "schedule_to_close",
21879            "heartbeat",
21880        ] {
21881            let ctx = workflow_context(vec![history_event(
21882                "ActivityTimedOut",
21883                json!({
21884                    "sequence": 1,
21885                    "activity_type": "slow",
21886                    "activity_execution_id": "act-timeout",
21887                    "activity_attempt_id": "attempt-timeout",
21888                    "failure_category": "timeout",
21889                    "timeout_kind": timeout_kind,
21890                    "message": "deadline expired"
21891                }),
21892            )]);
21893            let mut call = Box::pin(ctx.activity("slow", json!([])));
21894            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21895            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
21896                call.as_mut().poll(&mut task_context)
21897            else {
21898                panic!("expected timeout failure");
21899            };
21900            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
21901            assert_eq!(failure.reason, timeout_kind);
21902            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
21903            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
21904        }
21905    }
21906
21907    #[test]
21908    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
21909        let ctx = workflow_context(Vec::new());
21910        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
21911        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21912
21913        assert!(matches!(
21914            sleep.as_mut().poll(&mut task_context),
21915            Poll::Pending
21916        ));
21917        assert!(matches!(
21918            sleep.as_mut().poll(&mut task_context),
21919            Poll::Pending
21920        ));
21921
21922        let commands = ctx.take_commands().expect("timer command");
21923        assert_eq!(
21924            commands,
21925            vec![json!({
21926                "type": "start_timer",
21927                "delay_seconds": 2,
21928            })]
21929        );
21930    }
21931
21932    #[test]
21933    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
21934        let history = vec![
21935            history_event(
21936                "TimerScheduled",
21937                json!({
21938                    "sequence": 1,
21939                    "timer_id": "timer-1",
21940                    "delay_seconds": 5,
21941                    "fire_at": "2026-07-11T12:00:05Z",
21942                }),
21943            ),
21944            history_event(
21945                "TimerFired",
21946                json!({
21947                    "sequence": 1,
21948                    "timer_id": "timer-1",
21949                    "delay_seconds": 5,
21950                    "fire_at": "2026-07-11T12:00:05Z",
21951                    "fired_at": "2026-07-11T12:00:05Z",
21952                }),
21953            ),
21954        ];
21955
21956        for _restart in 0..2 {
21957            let ctx = workflow_context(history.clone());
21958            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
21959            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21960            assert!(matches!(
21961                sleep.as_mut().poll(&mut task_context),
21962                Poll::Ready(Ok(()))
21963            ));
21964            assert!(ctx.take_commands().expect("commands").is_empty());
21965            ctx.ensure_history_consumed().expect("history consumed");
21966        }
21967    }
21968
21969    #[test]
21970    fn workflow_sleep_rejects_changed_delay_during_replay() {
21971        let ctx = workflow_context(vec![
21972            history_event(
21973                "TimerScheduled",
21974                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21975            ),
21976            history_event(
21977                "TimerFired",
21978                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
21979            ),
21980        ]);
21981        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
21982        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21983
21984        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21985            sleep.as_mut().poll(&mut task_context)
21986        else {
21987            panic!("changed timer delay must be rejected");
21988        };
21989        assert_eq!(failure.reason, "timer_delay_mismatch");
21990        assert_eq!(failure.sequence, Some(1));
21991    }
21992
21993    #[test]
21994    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
21995        let ctx = workflow_context(Vec::new());
21996        let mut wait = Box::pin(
21997            ctx.wait_condition(
21998                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
21999                    .timeout(Duration::from_millis(60_001)),
22000                || Ok(false),
22001            ),
22002        );
22003        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22004
22005        assert!(matches!(
22006            wait.as_mut().poll(&mut task_context),
22007            Poll::Pending
22008        ));
22009        assert!(matches!(
22010            wait.as_mut().poll(&mut task_context),
22011            Poll::Pending
22012        ));
22013        assert_eq!(
22014            ctx.take_commands().expect("condition command"),
22015            vec![json!({
22016                "type": "open_condition_wait",
22017                "condition_wait_occurrence_id": "rust:condition-wait:0",
22018                "condition_key": "approval.ready",
22019                "condition_definition_fingerprint": "sha256:approval-v1",
22020                "timeout_seconds": 61,
22021            })]
22022        );
22023    }
22024
22025    #[test]
22026    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
22027        let ctx = workflow_context(Vec::new());
22028        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
22029        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22030        assert!(matches!(
22031            satisfied.as_mut().poll(&mut task_context),
22032            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22033        ));
22034
22035        let mut timed_out = Box::pin(wait_condition!(
22036            ctx,
22037            "no-wait",
22038            timeout: Duration::ZERO,
22039            || Ok(false),
22040        ));
22041        assert!(matches!(
22042            timed_out.as_mut().poll(&mut task_context),
22043            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22044        ));
22045        assert!(ctx.take_commands().expect("commands").is_empty());
22046    }
22047
22048    #[test]
22049    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
22050        let signal_history = vec![
22051            history_event(
22052                "ConditionWaitOpened",
22053                json!({
22054                    "sequence": 4,
22055                    "condition_wait_id": "condition:4",
22056                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22057                    "condition_key": "approval",
22058                    "condition_definition_fingerprint": "sha256:approval-v1",
22059                    "timeout_seconds": 30,
22060                }),
22061            ),
22062            history_event(
22063                "SignalReceived",
22064                json!({
22065                    "workflow_sequence": 4,
22066                    "signal_name": "approve",
22067                    "arguments": fixture_envelope(json!(["Ada"])),
22068                }),
22069            ),
22070        ];
22071        for _worker_before_or_after_restart in 0..2 {
22072            let ctx = workflow_context(signal_history.clone());
22073            let predicate_ctx = ctx.clone();
22074            let mut wait = Box::pin(
22075                ctx.wait_condition(
22076                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
22077                        .timeout(Duration::from_secs(30)),
22078                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
22079                ),
22080            );
22081            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22082            assert!(matches!(
22083                wait.as_mut().poll(&mut task_context),
22084                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22085            ));
22086            assert!(ctx.take_commands().expect("commands").is_empty());
22087            ctx.ensure_history_consumed().expect("condition consumed");
22088        }
22089
22090        let update_history = vec![
22091            history_event(
22092                "ConditionWaitOpened",
22093                json!({
22094                    "sequence": 7,
22095                    "condition_wait_id": "condition:7",
22096                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22097                    "condition_key": "update-approval",
22098                    "condition_definition_fingerprint": "sha256:update-approval-v1",
22099                }),
22100            ),
22101            history_event(
22102                "UpdateApplied",
22103                json!({
22104                    "sequence": 7,
22105                    "update_id": "update-1",
22106                    "update_name": "approve",
22107                    "arguments": fixture_envelope(json!([true])),
22108                }),
22109            ),
22110        ];
22111        let ctx = workflow_context(update_history);
22112        let predicate_ctx = ctx.clone();
22113        let mut wait = Box::pin(ctx.wait_condition(
22114            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
22115            move || {
22116                Ok(predicate_ctx
22117                    .updates("approve")?
22118                    .first()
22119                    .and_then(|arguments| arguments.first())
22120                    .and_then(Value::as_bool)
22121                    == Some(true))
22122            },
22123        ));
22124        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22125        assert!(matches!(
22126            wait.as_mut().poll(&mut task_context),
22127            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22128        ));
22129        assert!(ctx.take_commands().expect("commands").is_empty());
22130        ctx.ensure_history_consumed().expect("condition consumed");
22131    }
22132
22133    #[test]
22134    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
22135        let open_history = vec![
22136            history_event(
22137                "ConditionWaitOpened",
22138                json!({
22139                    "sequence": 3,
22140                    "condition_wait_id": "condition:3",
22141                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22142                    "condition_key": "two-votes",
22143                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22144                    "timeout_seconds": 120,
22145                }),
22146            ),
22147            history_event(
22148                "SignalReceived",
22149                json!({
22150                    "workflow_sequence": 3,
22151                    "signal_name": "vote",
22152                    "arguments": fixture_envelope(json!(["first"])),
22153                }),
22154            ),
22155        ];
22156        for _worker_before_or_after_restart in 0..2 {
22157            let ctx = workflow_context(open_history.clone());
22158            let predicate_ctx = ctx.clone();
22159            let mut wait = Box::pin(
22160                ctx.wait_condition(
22161                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22162                        .timeout(Duration::from_secs(120)),
22163                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22164                ),
22165            );
22166            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22167            assert!(matches!(
22168                wait.as_mut().poll(&mut task_context),
22169                Poll::Pending
22170            ));
22171            assert_eq!(
22172                ctx.take_commands().expect("reopened condition"),
22173                vec![json!({
22174                    "type": "open_condition_wait",
22175                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22176                    "condition_key": "two-votes",
22177                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22178                    "timeout_seconds": 120,
22179                })]
22180            );
22181        }
22182
22183        let satisfied_ctx = workflow_context(vec![
22184            history_event(
22185                "ConditionWaitOpened",
22186                json!({
22187                    "sequence": 5,
22188                    "condition_wait_id": "condition:5",
22189                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22190                    "condition_key": "approval",
22191                    "condition_definition_fingerprint": "sha256:approval-v1",
22192                }),
22193            ),
22194            history_event(
22195                "ConditionWaitSatisfied",
22196                json!({
22197                    "sequence": 5,
22198                    "condition_wait_id": "condition:5",
22199                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22200                    "condition_key": "approval",
22201                    "condition_definition_fingerprint": "sha256:approval-v1",
22202                }),
22203            ),
22204        ]);
22205        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
22206            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
22207            || Ok(false),
22208        ));
22209        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22210        assert!(matches!(
22211            satisfied.as_mut().poll(&mut task_context),
22212            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22213        ));
22214
22215        let timed_out_ctx = workflow_context(vec![
22216            history_event(
22217                "ConditionWaitOpened",
22218                json!({
22219                    "sequence": 8,
22220                    "condition_wait_id": "condition:8",
22221                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22222                    "condition_key": "approval-timeout",
22223                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
22224                    "timeout_seconds": 5,
22225                }),
22226            ),
22227            history_event(
22228                "TimerScheduled",
22229                json!({
22230                    "sequence": 9,
22231                    "timer_id": "condition-timer:9",
22232                    "timer_kind": "condition_timeout",
22233                    "condition_wait_id": "condition:8",
22234                    "delay_seconds": 5,
22235                }),
22236            ),
22237            history_event(
22238                "TimerFired",
22239                json!({
22240                    "sequence": 9,
22241                    "timer_id": "condition-timer:9",
22242                    "timer_kind": "condition_timeout",
22243                    "condition_wait_id": "condition:8",
22244                    "delay_seconds": 5,
22245                }),
22246            ),
22247        ]);
22248        let mut timed_out = Box::pin(
22249            timed_out_ctx.wait_condition(
22250                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
22251                    .timeout(Duration::from_secs(5)),
22252                || Ok(true),
22253            ),
22254        );
22255        assert!(matches!(
22256            timed_out.as_mut().poll(&mut task_context),
22257            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22258        ));
22259    }
22260
22261    #[test]
22262    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
22263        let ctx = workflow_context(reopened_selection_condition_history());
22264        {
22265            let state = ctx.state.lock().unwrap();
22266            assert!(matches!(
22267                selection_member_recorded_command(&state, 2),
22268                Some(RecordedCommand::ConditionWait {
22269                    sequence: 3,
22270                    result: None,
22271                    ..
22272                })
22273            ));
22274        }
22275        let mut selected = Box::pin(ctx.select_keyed(vec![
22276            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22277            (
22278                "votes",
22279                ParallelOperation::condition(
22280                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
22281                    || Ok(true),
22282                ),
22283            ),
22284        ]));
22285        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22286        assert!(selected.as_mut().poll(&mut task_context).is_pending());
22287        assert!(
22288            ctx.take_commands().unwrap().is_empty(),
22289            "true predicate must not reopen the recorded wait"
22290        );
22291        ctx.ensure_history_consumed()
22292            .expect("physical reopens are consumed while canonical selection is pending");
22293    }
22294
22295    #[test]
22296    fn reopened_selection_condition_replays_its_latest_physical_winner() {
22297        for (terminal_type, acknowledge_timeout) in [
22298            ("ConditionWaitSatisfied", false),
22299            ("ConditionWaitTimedOut", false),
22300            ("TimerFired", false),
22301            ("TimerFired", true),
22302        ] {
22303            let mut history = reopened_selection_condition_history();
22304            let original_identity = history[1].payload["condition_wait_id"].clone();
22305            let uses_timer = terminal_type == "TimerFired";
22306            let mut resolution_payload = history[3].payload.clone();
22307            if uses_timer {
22308                for event in &mut history[1..] {
22309                    event.payload["timeout_seconds"] = json!(3);
22310                }
22311                resolution_payload = history[3].payload.clone();
22312                resolution_payload["timer_kind"] = json!("condition_timeout");
22313                resolution_payload["timer_id"] = json!("condition-timeout-3");
22314                resolution_payload["delay_seconds"] = json!(3);
22315                history.push(history_event("TimerScheduled", resolution_payload.clone()));
22316            }
22317            let mut resolution = history_event(terminal_type, resolution_payload.clone());
22318            resolution
22319                .raw
22320                .insert("id".into(), json!("latest-condition-resolution"));
22321            history.push(resolution);
22322            history.push(history_event(
22323                "SelectionResolved",
22324                json!({
22325                    "selection_group_id": "select-calls:1:2",
22326                    "selection_group_base_sequence": 1,
22327                    "selection_group_size": 2,
22328                    "member_key": "votes",
22329                    "member_index": 1,
22330                    "member_base_sequence": 2,
22331                    "member_size": 1,
22332                    "operation_kind": "condition",
22333                    "operation_identity": original_identity,
22334                    "outcome": "completed",
22335                    "resolution_event_id": "latest-condition-resolution",
22336                    "resolution_event_type": terminal_type,
22337                }),
22338            ));
22339            if acknowledge_timeout {
22340                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
22341            }
22342            let ctx = workflow_context(history);
22343            let mut selected = Box::pin(ctx.select_keyed(vec![
22344                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22345                (
22346                    "votes",
22347                    ParallelOperation::condition(
22348                        if uses_timer {
22349                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22350                                .timeout(Duration::from_secs(3))
22351                        } else {
22352                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22353                        },
22354                        || Ok(true),
22355                    ),
22356                ),
22357            ]));
22358            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22359            match selected.as_mut().poll(&mut task_context) {
22360                Poll::Ready(Ok(result)) => {
22361                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
22362                    let expected = if terminal_type == "ConditionWaitSatisfied" {
22363                        ConditionWaitResult::Satisfied
22364                    } else {
22365                        ConditionWaitResult::TimedOut
22366                    };
22367                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
22368                }
22369                other => panic!("latest physical winner must replay: {other:?}"),
22370            }
22371            assert!(ctx.take_commands().unwrap().is_empty());
22372            ctx.ensure_history_consumed()
22373                .expect("winner history consumed");
22374        }
22375    }
22376
22377    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
22378        let fixture: Value = serde_json::from_str(include_str!(
22379            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22380        ))
22381        .expect("grouped condition fixture");
22382        fixture["history"]
22383            .as_array()
22384            .unwrap()
22385            .iter()
22386            .map(|event| {
22387                let mut payload = event["payload"].clone();
22388                let index = payload["parallel_group_index"].as_u64().unwrap();
22389                payload["parallel_group_id"] = json!("select-calls:1:2");
22390                payload["parallel_group_mode"] = json!("select");
22391                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
22392                payload["selection_member_index"] = json!(index);
22393                payload["selection_member_base_sequence"] = json!(index + 1);
22394                payload["selection_member_size"] = json!(1);
22395                payload["selection_member_kind"] =
22396                    json!(if index == 0 { "timer" } else { "condition" });
22397                history_event(event["event_type"].as_str().unwrap(), payload)
22398            })
22399            .collect()
22400    }
22401
22402    #[test]
22403    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
22404        let fixture: Value = serde_json::from_str(include_str!(
22405            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22406        ))
22407        .expect("grouped condition fixture");
22408        let original = fixture["history"].as_array().expect("fixture history");
22409        let decode = |events: &[Value]| {
22410            let history = events
22411                .iter()
22412                .map(|event| {
22413                    history_event(
22414                        event["event_type"].as_str().unwrap(),
22415                        event["payload"].clone(),
22416                    )
22417                })
22418                .collect::<Vec<_>>();
22419            recorded_commands(
22420                &history,
22421                DEFAULT_CODEC,
22422                WorkflowIdentity {
22423                    workflow_id: None,
22424                    run_id: None,
22425                },
22426            )
22427        };
22428        assert!(decode(original).is_ok());
22429        for field in [
22430            "condition_wait_occurrence_id",
22431            "condition_key",
22432            "condition_definition_fingerprint",
22433            "timeout_seconds",
22434            "parallel_group_id",
22435            "parallel_group_size",
22436            "parallel_group_index",
22437        ] {
22438            let mut changed = original.clone();
22439            changed[3]["payload"][field] = match field {
22440                "timeout_seconds" | "parallel_group_size" => json!(30),
22441                "parallel_group_index" => json!(0),
22442                _ => json!("changed"),
22443            };
22444            assert!(
22445                decode(&changed).is_err(),
22446                "reopen must reject changed {field}"
22447            );
22448        }
22449        let mut unsettled = original.clone();
22450        unsettled.remove(2);
22451        assert!(
22452            decode(&unsettled).is_err(),
22453            "physical predecessor must be resolved"
22454        );
22455        let mut timed_out = original.clone();
22456        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
22457        assert!(decode(&timed_out).is_err(), "timeout is terminal");
22458        let mut late_resolution = original.clone();
22459        late_resolution.swap(2, 3);
22460        assert!(
22461            decode(&late_resolution).is_err(),
22462            "later history cannot authorize a reopen"
22463        );
22464    }
22465
22466    #[test]
22467    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
22468        let history = vec![
22469            history_event(
22470                "ConditionWaitOpened",
22471                json!({
22472                    "sequence": 3,
22473                    "condition_wait_id": "condition:3",
22474                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22475                    "condition_key": "two-votes",
22476                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22477                }),
22478            ),
22479            history_event(
22480                "SignalReceived",
22481                json!({
22482                    "workflow_sequence": 3,
22483                    "signal_name": "vote",
22484                    "arguments": fixture_envelope(json!(["first"])),
22485                }),
22486            ),
22487            history_event(
22488                "ConditionWaitSatisfied",
22489                json!({
22490                    "sequence": 3,
22491                    "condition_wait_id": "condition:3",
22492                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22493                    "condition_key": "two-votes",
22494                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22495                }),
22496            ),
22497            history_event(
22498                "ConditionWaitOpened",
22499                json!({
22500                    "sequence": 5,
22501                    "condition_wait_id": "condition:5",
22502                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22503                    "condition_key": "two-votes",
22504                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22505                }),
22506            ),
22507            history_event(
22508                "SignalReceived",
22509                json!({
22510                    "workflow_sequence": 5,
22511                    "signal_name": "vote",
22512                    "arguments": fixture_envelope(json!(["second"])),
22513                }),
22514            ),
22515            history_event(
22516                "ConditionWaitSatisfied",
22517                json!({
22518                    "sequence": 5,
22519                    "condition_wait_id": "condition:5",
22520                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22521                    "condition_key": "two-votes",
22522                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22523                }),
22524            ),
22525        ];
22526        for _cold_worker_or_restart in 0..2 {
22527            let ctx = workflow_context(history.clone());
22528            let predicate_ctx = ctx.clone();
22529            let mut wait = Box::pin(ctx.wait_condition(
22530                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
22531                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22532            ));
22533            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22534
22535            assert!(matches!(
22536                wait.as_mut().poll(&mut task_context),
22537                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22538            ));
22539            assert!(ctx.take_commands().expect("commands").is_empty());
22540            ctx.ensure_history_consumed()
22541                .expect("every physical wait-open is consumed");
22542        }
22543    }
22544
22545    #[test]
22546    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
22547        let history = vec![
22548            history_event(
22549                "ConditionWaitOpened",
22550                json!({
22551                    "sequence": 3,
22552                    "condition_wait_id": "condition:3",
22553                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22554                    "condition_key": "approved",
22555                    "condition_definition_fingerprint": "sha256:approved-v1",
22556                }),
22557            ),
22558            history_event(
22559                "UpdateApplied",
22560                json!({
22561                    "sequence": 3,
22562                    "update_id": "update-1",
22563                    "update_name": "approve",
22564                    "arguments": fixture_envelope(json!([false])),
22565                }),
22566            ),
22567            history_event(
22568                "ConditionWaitOpened",
22569                json!({
22570                    "sequence": 5,
22571                    "condition_wait_id": "condition:5",
22572                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22573                    "condition_key": "approved",
22574                    "condition_definition_fingerprint": "sha256:approved-v1",
22575                }),
22576            ),
22577            history_event(
22578                "UpdateApplied",
22579                json!({
22580                    "sequence": 5,
22581                    "update_id": "update-2",
22582                    "update_name": "approve",
22583                    "arguments": fixture_envelope(json!([true])),
22584                }),
22585            ),
22586        ];
22587
22588        for _cold_worker_or_restart in 0..2 {
22589            let ctx = workflow_context(history.clone());
22590            let predicate_ctx = ctx.clone();
22591            let mut wait = Box::pin(ctx.wait_condition(
22592                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
22593                move || {
22594                    Ok(predicate_ctx
22595                        .updates("approve")?
22596                        .last()
22597                        .and_then(|arguments| arguments.first())
22598                        .and_then(Value::as_bool)
22599                        == Some(true))
22600                },
22601            ));
22602            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22603
22604            assert!(matches!(
22605                wait.as_mut().poll(&mut task_context),
22606                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22607            ));
22608            assert!(ctx.take_commands().expect("commands").is_empty());
22609            ctx.ensure_history_consumed()
22610                .expect("every update-driven reopen is consumed");
22611        }
22612    }
22613
22614    #[test]
22615    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
22616        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
22617            ("shared", "sha256:first", "shared", "sha256:second"),
22618            ("first", "sha256:shared", "second", "sha256:shared"),
22619            ("shared", "sha256:shared", "shared", "sha256:shared"),
22620            ("first", "sha256:first", "second", "sha256:second"),
22621        ] {
22622            let history = vec![
22623                history_event(
22624                    "ConditionWaitOpened",
22625                    json!({
22626                        "sequence": 3,
22627                        "condition_wait_id": "condition:3",
22628                        "condition_wait_occurrence_id": "rust:condition-wait:0",
22629                        "condition_key": first_key,
22630                        "condition_definition_fingerprint": first_fingerprint,
22631                    }),
22632                ),
22633                history_event(
22634                    "ConditionWaitSatisfied",
22635                    json!({
22636                        "sequence": 3,
22637                        "condition_wait_id": "condition:3",
22638                        "condition_wait_occurrence_id": "rust:condition-wait:0",
22639                        "condition_key": first_key,
22640                        "condition_definition_fingerprint": first_fingerprint,
22641                    }),
22642                ),
22643                history_event(
22644                    "ConditionWaitOpened",
22645                    json!({
22646                        "sequence": 4,
22647                        "condition_wait_id": "condition:4",
22648                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22649                        "condition_key": second_key,
22650                        "condition_definition_fingerprint": second_fingerprint,
22651                    }),
22652                ),
22653                history_event(
22654                    "ConditionWaitSatisfied",
22655                    json!({
22656                        "sequence": 4,
22657                        "condition_wait_id": "condition:4",
22658                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22659                        "condition_key": second_key,
22660                        "condition_definition_fingerprint": second_fingerprint,
22661                    }),
22662                ),
22663            ];
22664            for _cold_worker_or_restart in 0..2 {
22665                let ctx = workflow_context(history.clone());
22666                let mut task_context = TaskContext::from_waker(noop_waker_ref());
22667                let mut first = Box::pin(ctx.wait_condition(
22668                    ConditionWaitOptions::new(first_key, first_fingerprint),
22669                    || Ok(false),
22670                ));
22671                assert!(matches!(
22672                    first.as_mut().poll(&mut task_context),
22673                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22674                ));
22675
22676                let mut second = Box::pin(ctx.wait_condition(
22677                    ConditionWaitOptions::new(second_key, second_fingerprint),
22678                    || Ok(false),
22679                ));
22680                assert!(matches!(
22681                    second.as_mut().poll(&mut task_context),
22682                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22683                ));
22684                assert!(ctx.take_commands().expect("commands").is_empty());
22685                ctx.ensure_history_consumed()
22686                    .expect("each authored wait consumes one occurrence");
22687            }
22688        }
22689    }
22690
22691    #[test]
22692    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
22693        fn worker() -> Worker {
22694            let client = Client::new("http://127.0.0.1:8080").expect("client");
22695            let mut worker = Worker::new(client, "rust-workers");
22696            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
22697                let mut outcomes = Vec::new();
22698                for _ in 0..2 {
22699                    outcomes.push(
22700                        ctx.wait_condition(
22701                            ConditionWaitOptions::new("shared", "sha256:shared"),
22702                            || Ok(false),
22703                        )
22704                        .await?,
22705                    );
22706                }
22707                Ok(json!(outcomes))
22708            });
22709            worker
22710        }
22711
22712        let task = workflow_task(
22713            "rust.condition-loop",
22714            vec![
22715                history_event(
22716                    "ConditionWaitOpened",
22717                    json!({
22718                        "sequence": 1,
22719                        "condition_wait_id": "condition:1",
22720                        "condition_wait_occurrence_id": "rust:condition-wait:0",
22721                        "condition_key": "shared",
22722                        "condition_definition_fingerprint": "sha256:shared",
22723                    }),
22724                ),
22725                history_event(
22726                    "ConditionWaitSatisfied",
22727                    json!({
22728                        "sequence": 1,
22729                        "condition_wait_id": "condition:1",
22730                        "condition_wait_occurrence_id": "rust:condition-wait:0",
22731                        "condition_key": "shared",
22732                        "condition_definition_fingerprint": "sha256:shared",
22733                    }),
22734                ),
22735                history_event(
22736                    "ConditionWaitOpened",
22737                    json!({
22738                        "sequence": 2,
22739                        "condition_wait_id": "condition:2",
22740                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22741                        "condition_key": "shared",
22742                        "condition_definition_fingerprint": "sha256:shared",
22743                    }),
22744                ),
22745                history_event(
22746                    "ConditionWaitSatisfied",
22747                    json!({
22748                        "sequence": 2,
22749                        "condition_wait_id": "condition:2",
22750                        "condition_wait_occurrence_id": "rust:condition-wait:1",
22751                        "condition_key": "shared",
22752                        "condition_definition_fingerprint": "sha256:shared",
22753                    }),
22754                ),
22755            ],
22756            DEFAULT_CODEC,
22757        );
22758
22759        for _cold_worker_or_restart in 0..2 {
22760            let commands = worker()
22761                .execute_workflow_task(task.clone())
22762                .expect("adjacent loop waits replay deterministically");
22763            assert_eq!(commands.len(), 1);
22764            assert_eq!(commands[0]["type"], "complete_workflow");
22765            assert_eq!(
22766                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
22767                json!(["satisfied", "satisfied"])
22768            );
22769        }
22770    }
22771
22772    #[test]
22773    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
22774        let history = vec![history_event(
22775            "ConditionWaitOpened",
22776            json!({
22777                "sequence": 12,
22778                "condition_wait_id": "condition:12",
22779                "condition_wait_occurrence_id": "rust:condition-wait:0",
22780                "condition_key": "approval",
22781                "condition_definition_fingerprint": "sha256:approval-v1",
22782                "timeout_seconds": 30,
22783            }),
22784        )];
22785        for (options, expected_reason) in [
22786            (
22787                ConditionWaitOptions::new("changed", "sha256:approval-v1")
22788                    .timeout(Duration::from_secs(30)),
22789                "condition_wait_key_mismatch",
22790            ),
22791            (
22792                ConditionWaitOptions::new("approval", "sha256:approval-v2")
22793                    .timeout(Duration::from_secs(30)),
22794                "condition_wait_predicate_mismatch",
22795            ),
22796            (
22797                ConditionWaitOptions::new("approval", "sha256:approval-v1")
22798                    .timeout(Duration::from_secs(29)),
22799                "condition_wait_timeout_mismatch",
22800            ),
22801        ] {
22802            let ctx = workflow_context(history.clone());
22803            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
22804            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22805            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22806                wait.as_mut().poll(&mut task_context)
22807            else {
22808                panic!("changed condition definition must fail replay");
22809            };
22810            assert_eq!(failure.reason, expected_reason);
22811            assert_eq!(failure.sequence, Some(12));
22812        }
22813    }
22814
22815    #[test]
22816    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
22817        let error = WorkflowState::new(
22818            vec![history_event(
22819                "ConditionWaitOpened",
22820                json!({
22821                    "sequence": 12,
22822                    "condition_wait_id": "condition:12",
22823                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22824                    "condition_key": "approval",
22825                }),
22826            )],
22827            "rust-workers".to_string(),
22828            DEFAULT_CODEC.to_string(),
22829            None,
22830        )
22831        .expect_err("condition history without a predicate fingerprint must fail");
22832
22833        assert!(matches!(
22834            error,
22835            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22836                if reason == "condition_wait_predicate_fingerprint_missing"
22837        ));
22838    }
22839
22840    #[test]
22841    fn condition_wait_history_requires_authored_occurrence_identity() {
22842        let error = WorkflowState::new(
22843            vec![history_event(
22844                "ConditionWaitOpened",
22845                json!({
22846                    "sequence": 12,
22847                    "condition_wait_id": "condition:12",
22848                    "condition_key": "approval",
22849                    "condition_definition_fingerprint": "sha256:approval-v1",
22850                }),
22851            )],
22852            "rust-workers".to_string(),
22853            DEFAULT_CODEC.to_string(),
22854            None,
22855        )
22856        .expect_err("condition history without occurrence identity must fail");
22857
22858        assert!(matches!(
22859            error,
22860            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22861                if reason == "condition_wait_occurrence_id_missing"
22862        ));
22863    }
22864
22865    #[test]
22866    fn typed_search_attribute_updates_validate_emit_and_replay() {
22867        let update = SearchAttributeUpdate::new()
22868            .keyword("OrderStatus", " waiting ")
22869            .expect("keyword")
22870            .int("Attempt", 3)
22871            .expect("int")
22872            .bool("Escalated", false)
22873            .expect("bool")
22874            .keyword_list("Regions", ["us-east", "eu-west"])
22875            .expect("list")
22876            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
22877            .expect("datetime")
22878            .delete("LegacyStatus")
22879            .expect("delete");
22880        let ctx = workflow_context(Vec::new());
22881        ctx.upsert_search_attributes(update.clone())
22882            .expect("typed update");
22883        assert_eq!(
22884            ctx.take_commands().expect("search-attribute command"),
22885            vec![json!({
22886                "type": "upsert_search_attributes",
22887                "attributes": {
22888                    "Attempt": 3,
22889                    "Escalated": false,
22890                    "LegacyStatus": null,
22891                    "OrderStatus": "waiting",
22892                    "Regions": ["us-east", "eu-west"],
22893                    "UpdatedAt": "2026-08-22T04:00:00Z",
22894                },
22895                "attribute_types": {
22896                    "Attempt": "int",
22897                    "Escalated": "bool",
22898                    "OrderStatus": "keyword",
22899                    "Regions": "keyword_list",
22900                    "UpdatedAt": "datetime",
22901                },
22902            })]
22903        );
22904
22905        let replay = workflow_context(vec![history_event(
22906            "SearchAttributesUpserted",
22907            json!({
22908                "sequence": 6,
22909                "attributes": {
22910                    "Attempt": 3,
22911                    "Escalated": false,
22912                    "LegacyStatus": null,
22913                    "OrderStatus": "waiting",
22914                    "Regions": ["us-east", "eu-west"],
22915                    "UpdatedAt": "2026-08-22T04:00:00Z",
22916                },
22917                "attribute_types": {
22918                    "Attempt": "int",
22919                    "Escalated": "bool",
22920                    "OrderStatus": "keyword",
22921                    "Regions": "keyword_list",
22922                    "UpdatedAt": "datetime",
22923                },
22924                "merged": {},
22925            }),
22926        )]);
22927        replay
22928            .upsert_search_attributes(update)
22929            .expect("matching update replays");
22930        assert!(replay.take_commands().expect("commands").is_empty());
22931        replay.ensure_history_consumed().expect("history consumed");
22932
22933        let type_drift = workflow_context(vec![history_event(
22934            "SearchAttributesUpserted",
22935            json!({
22936                "sequence": 7,
22937                "attributes": {"OrderStatus": "waiting"},
22938                "attribute_types": {"OrderStatus": "keyword"},
22939                "merged": {"OrderStatus": "waiting"},
22940            }),
22941        )]);
22942        let error = type_drift
22943            .upsert_search_attributes(
22944                SearchAttributeUpdate::new()
22945                    .string("OrderStatus", "waiting")
22946                    .expect("string update"),
22947            )
22948            .expect_err("same JSON value with a changed type must fail replay");
22949        assert!(matches!(
22950            error,
22951            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22952                if reason == "search_attribute_type_mismatch"
22953        ));
22954
22955        let malformed_types = WorkflowState::new(
22956            vec![history_event(
22957                "SearchAttributesUpserted",
22958                json!({
22959                    "sequence": 8,
22960                    "attributes": {"OrderStatus": "waiting"},
22961                    "attribute_types": {"OrderStatus": "unsupported"},
22962                    "merged": {"OrderStatus": "waiting"},
22963                }),
22964            )],
22965            "rust-workers".to_string(),
22966            DEFAULT_CODEC.to_string(),
22967            None,
22968        )
22969        .expect_err("unsupported search-attribute type metadata must fail");
22970        assert!(matches!(
22971            malformed_types,
22972            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22973                if reason == "search_attribute_types_malformed"
22974        ));
22975
22976        assert!(matches!(
22977            SearchAttributeUpdate::new().keyword("bad key", "value"),
22978            Err(SearchAttributeUpdateError::InvalidKey(_))
22979        ));
22980        assert!(matches!(
22981            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
22982            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
22983        ));
22984        assert!(matches!(
22985            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
22986            Err(SearchAttributeUpdateError::ValueTooLong { .. })
22987        ));
22988        assert!(matches!(
22989            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
22990            Err(SearchAttributeUpdateError::InvalidDateTime(_))
22991        ));
22992        assert!(matches!(
22993            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
22994            Err(Error::InvalidSearchAttributeUpdate(
22995                SearchAttributeUpdateError::Empty
22996            ))
22997        ));
22998    }
22999
23000    #[test]
23001    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
23002        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
23003        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
23004
23005        assert!(SearchAttributeUpdate::new()
23006            .string("AsciiDescription", ascii)
23007            .is_ok());
23008        assert!(SearchAttributeUpdate::new()
23009            .string("Utf8Description", utf8)
23010            .is_ok());
23011        assert!(matches!(
23012            SearchAttributeUpdate::new().string(
23013                "TooLongDescription",
23014                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
23015            ),
23016            Err(SearchAttributeUpdateError::ValueTooLong {
23017                kind: "string",
23018                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
23019                ..
23020            })
23021        ));
23022    }
23023
23024    #[test]
23025    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
23026        let lone_fire = WorkflowState::new(
23027            vec![history_event(
23028                "TimerFired",
23029                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23030            )],
23031            "rust-workers".to_string(),
23032            DEFAULT_CODEC.to_string(),
23033            None,
23034        )
23035        .expect_err("TimerFired requires TimerScheduled");
23036        assert!(matches!(
23037            lone_fire,
23038            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23039                if reason == "timer_schedule_missing_or_duplicate"
23040        ));
23041
23042        let wrong_identity = WorkflowState::new(
23043            vec![
23044                history_event(
23045                    "TimerScheduled",
23046                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23047                ),
23048                history_event(
23049                    "TimerFired",
23050                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23051                ),
23052            ],
23053            "rust-workers".to_string(),
23054            DEFAULT_CODEC.to_string(),
23055            None,
23056        )
23057        .expect_err("fire must match scheduled timer identity");
23058        assert!(matches!(
23059            wrong_identity,
23060            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23061                if reason == "timer_identity_mismatch"
23062        ));
23063
23064        let duplicate_fire = WorkflowState::new(
23065            vec![
23066                history_event(
23067                    "TimerScheduled",
23068                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23069                ),
23070                history_event(
23071                    "TimerFired",
23072                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23073                ),
23074                history_event(
23075                    "TimerFired",
23076                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23077                ),
23078            ],
23079            "rust-workers".to_string(),
23080            DEFAULT_CODEC.to_string(),
23081            None,
23082        )
23083        .expect_err("a durable timer cannot fire twice");
23084        assert!(matches!(
23085            duplicate_fire,
23086            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23087                if reason == "duplicate_timer_fire"
23088        ));
23089
23090        let wrong_fired_delay = WorkflowState::new(
23091            vec![
23092                history_event(
23093                    "TimerScheduled",
23094                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23095                ),
23096                history_event(
23097                    "TimerFired",
23098                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
23099                ),
23100            ],
23101            "rust-workers".to_string(),
23102            DEFAULT_CODEC.to_string(),
23103            None,
23104        )
23105        .expect_err("timer schedule and fire delays must agree");
23106        assert!(matches!(
23107            wrong_fired_delay,
23108            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23109                if reason == "timer_history_delay_mismatch"
23110        ));
23111    }
23112
23113    #[test]
23114    fn replay_rejects_activity_moved_before_recorded_timer() {
23115        let ctx = workflow_context(vec![
23116            history_event(
23117                "TimerScheduled",
23118                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23119            ),
23120            history_event(
23121                "TimerFired",
23122                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23123            ),
23124            history_event(
23125                "ActivityCompleted",
23126                json!({
23127                    "sequence": 2,
23128                    "activity_type": "after-timer",
23129                    "payload_codec": DEFAULT_CODEC,
23130                    "result": fixture_envelope(json!("done")),
23131                }),
23132            ),
23133        ]);
23134        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
23135        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23136
23137        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23138            activity.as_mut().poll(&mut task_context)
23139        else {
23140            panic!("reordered durable command must be rejected");
23141        };
23142        assert_eq!(failure.reason, "recorded_command_mismatch");
23143        assert_eq!(failure.sequence, Some(1));
23144        assert_eq!(failure.expected.as_deref(), Some("timer"));
23145        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
23146    }
23147
23148    #[test]
23149    fn workflow_context_emits_a_typed_named_signal_wait() {
23150        let ctx = workflow_context(Vec::new());
23151        let mut signal = Box::pin(ctx.wait_signal("finish"));
23152        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23153
23154        assert!(matches!(
23155            signal.as_mut().poll(&mut task_context),
23156            Poll::Pending
23157        ));
23158        assert_eq!(
23159            ctx.take_commands().expect("signal-wait command"),
23160            vec![json!({
23161                "type": "open_signal_wait",
23162                "signal_name": "finish",
23163            })]
23164        );
23165    }
23166
23167    #[test]
23168    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
23169        let ctx = workflow_context(Vec::new());
23170        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
23171        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23172
23173        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
23174        else {
23175            panic!("runtime-reserved signal should be rejected");
23176        };
23177        assert!(message.contains("reserved by the workflow runtime"));
23178        assert!(ctx.take_commands().expect("commands").is_empty());
23179    }
23180
23181    #[tokio::test]
23182    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
23183        let client = Client::builder("http://127.0.0.1:9")
23184            .build()
23185            .expect("client");
23186        let error = client
23187            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
23188            .await
23189            .expect_err("runtime-reserved signal should be rejected before transport");
23190
23191        assert!(
23192            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
23193        );
23194    }
23195
23196    #[test]
23197    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
23198        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23199            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23200                value.to_string(),
23201            )]))
23202            .expect("message payload");
23203            json!({
23204                "schema": MESSAGE_STREAM_SCHEMA,
23205                "stream_name": "orders",
23206                "message_id": message_id,
23207                "position": position,
23208                "payload_envelope": payload,
23209            })
23210        }
23211
23212        fn opened(sequence: u64) -> HistoryEvent {
23213            history_event(
23214                "SignalWaitOpened",
23215                json!({
23216                    "sequence": sequence,
23217                    "signal_name": MESSAGE_STREAM_SIGNAL,
23218                }),
23219            )
23220        }
23221
23222        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23223            history_event(
23224                "SignalApplied",
23225                json!({
23226                    "sequence": sequence,
23227                    "signal_name": MESSAGE_STREAM_SIGNAL,
23228                    "value": fixture_envelope(json!([delivery])),
23229                }),
23230            )
23231        }
23232
23233        fn received(delivery: Value) -> HistoryEvent {
23234            history_event(
23235                "SignalReceived",
23236                json!({
23237                    "signal_name": MESSAGE_STREAM_SIGNAL,
23238                    "arguments": fixture_envelope(json!([delivery])),
23239                    "payload_codec": DEFAULT_CODEC,
23240                }),
23241            )
23242        }
23243
23244        let client = Client::new("http://127.0.0.1:8080").expect("client");
23245        let mut worker = Worker::new(client, "rust-workers");
23246        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
23247            let messages = ctx.message_stream("orders")?.receive(2).await?;
23248            Ok(json!(messages
23249                .into_iter()
23250                .map(|message| message.message_id)
23251                .collect::<Vec<_>>()))
23252        });
23253
23254        let first = delivery("message-1", 1, "one");
23255        let second = delivery("message-2", 2, "two");
23256        let batch = worker
23257            .execute_workflow_task_decision(workflow_task(
23258                "rust.message-stream-batch",
23259                vec![
23260                    opened(1),
23261                    received(first.clone()),
23262                    applied(1, first.clone()),
23263                    received(first.clone()),
23264                    received(second),
23265                ],
23266                DEFAULT_CODEC,
23267            ))
23268            .expect("worker task consumes the available batch");
23269
23270        assert_eq!(batch.commands.len(), 1);
23271        assert_eq!(batch.commands[0]["type"], "complete_workflow");
23272        assert_eq!(
23273            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
23274                .expect("workflow result"),
23275            json!(["message-1", "message-2"])
23276        );
23277        assert_eq!(
23278            batch.message_stream_cursors,
23279            vec![json!({"stream_name": "orders", "through_position": 2})]
23280        );
23281        assert!(batch.message_stream_waits.is_empty());
23282
23283        let partial = worker
23284            .execute_workflow_task_decision(workflow_task(
23285                "rust.message-stream-batch",
23286                vec![opened(1), received(first.clone()), applied(1, first)],
23287                DEFAULT_CODEC,
23288            ))
23289            .expect("worker task returns without waiting for a missing second item");
23290        assert_eq!(partial.commands.len(), 1);
23291        assert_eq!(partial.commands[0]["type"], "complete_workflow");
23292        assert_eq!(
23293            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
23294                .expect("workflow result"),
23295            json!(["message-1"])
23296        );
23297        assert_eq!(
23298            partial.message_stream_cursors,
23299            vec![json!({"stream_name": "orders", "through_position": 1})]
23300        );
23301        assert!(partial.message_stream_waits.is_empty());
23302    }
23303
23304    #[test]
23305    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
23306        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23307            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23308                value.to_string(),
23309            )]))
23310            .expect("message payload");
23311            json!({
23312                "schema": MESSAGE_STREAM_SCHEMA,
23313                "stream_name": "orders",
23314                "message_id": message_id,
23315                "position": position,
23316                "payload_envelope": payload,
23317            })
23318        }
23319
23320        fn opened(sequence: u64) -> HistoryEvent {
23321            history_event(
23322                "SignalWaitOpened",
23323                json!({
23324                    "sequence": sequence,
23325                    "signal_name": MESSAGE_STREAM_SIGNAL,
23326                }),
23327            )
23328        }
23329
23330        fn received(delivery: Value) -> HistoryEvent {
23331            history_event(
23332                "SignalReceived",
23333                json!({
23334                    "signal_name": MESSAGE_STREAM_SIGNAL,
23335                    "arguments": fixture_envelope(json!([delivery])),
23336                    "payload_codec": DEFAULT_CODEC,
23337                }),
23338            )
23339        }
23340
23341        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23342            history_event(
23343                "SignalApplied",
23344                json!({
23345                    "sequence": sequence,
23346                    "signal_name": MESSAGE_STREAM_SIGNAL,
23347                    "value": fixture_envelope(json!([delivery])),
23348                }),
23349            )
23350        }
23351
23352        let client = Client::new("http://127.0.0.1:8080").expect("client");
23353        let mut worker = Worker::new(client, "rust-workers");
23354        worker.register_workflow(
23355            "rust.message-stream-partial-batches",
23356            |ctx, _input| async move {
23357                let stream = ctx.message_stream("orders")?;
23358                let first = stream.receive(10).await?;
23359                let second = stream.receive(10).await?;
23360                Ok(json!([
23361                    first
23362                        .into_iter()
23363                        .map(|message| message.message_id)
23364                        .collect::<Vec<_>>(),
23365                    second
23366                        .into_iter()
23367                        .map(|message| message.message_id)
23368                        .collect::<Vec<_>>(),
23369                ]))
23370            },
23371        );
23372
23373        let first = delivery("message-1", 1, "one");
23374        let second = delivery("message-2", 2, "two");
23375        let decision = worker
23376            .execute_workflow_task_decision(workflow_task(
23377                "rust.message-stream-partial-batches",
23378                vec![
23379                    opened(1),
23380                    received(first.clone()),
23381                    applied(1, first),
23382                    opened(2),
23383                    received(second.clone()),
23384                    applied(2, second),
23385                ],
23386                DEFAULT_CODEC,
23387            ))
23388            .expect("cold replay preserves both authored receive boundaries");
23389
23390        assert_eq!(decision.commands.len(), 1);
23391        assert_eq!(decision.commands[0]["type"], "complete_workflow");
23392        assert_eq!(
23393            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
23394                .expect("workflow result"),
23395            json!([["message-1"], ["message-2"]])
23396        );
23397        assert_eq!(
23398            decision.message_stream_cursors,
23399            vec![json!({"stream_name": "orders", "through_position": 2})]
23400        );
23401        assert!(decision.message_stream_waits.is_empty());
23402    }
23403
23404    #[test]
23405    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
23406        let ctx = workflow_context(Vec::new());
23407        let stream = ctx.message_stream("orders").expect("message stream");
23408        let mut receive = Box::pin(stream.receive(10));
23409        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23410
23411        assert!(matches!(
23412            receive.as_mut().poll(&mut task_context),
23413            Poll::Pending
23414        ));
23415        assert_eq!(
23416            ctx.take_commands().expect("message-stream wait command"),
23417            vec![json!({
23418                "type": "open_signal_wait",
23419                "signal_name": MESSAGE_STREAM_SIGNAL,
23420            })]
23421        );
23422        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
23423        assert!(cursors.is_empty());
23424        assert_eq!(
23425            waits,
23426            vec![json!({"stream_name": "orders", "after_position": 0})]
23427        );
23428    }
23429
23430    #[test]
23431    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
23432        let ctx = workflow_context(vec![history_event(
23433            "SignalReceived",
23434            json!({
23435                "signal_name": MESSAGE_STREAM_SIGNAL,
23436                "arguments": fixture_envelope(json!([{
23437                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
23438                    "stream_name": "orders",
23439                    "through_position": 2,
23440                }])),
23441                "payload_codec": DEFAULT_CODEC,
23442            }),
23443        )]);
23444        let stream = ctx.message_stream("orders").expect("message stream");
23445        let mut receive = Box::pin(stream.receive(10));
23446        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23447
23448        assert!(matches!(
23449            receive.as_mut().poll(&mut task_context),
23450            Poll::Pending
23451        ));
23452        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
23453        assert_eq!(
23454            cursors,
23455            vec![json!({"stream_name": "orders", "through_position": 2})]
23456        );
23457        assert_eq!(
23458            waits,
23459            vec![json!({"stream_name": "orders", "after_position": 2})]
23460        );
23461    }
23462
23463    #[test]
23464    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
23465        let mut empty_map = BTreeMap::new();
23466        let mut nested = BTreeMap::new();
23467        nested.insert(
23468            "value".to_string(),
23469            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
23470        );
23471        let values = vec![
23472            AvroValue::Bytes(vec![0, 255]),
23473            AvroValue::Long(1),
23474            AvroValue::Double(1.0),
23475            AvroValue::Array(Vec::new()),
23476            AvroValue::Map(std::mem::take(&mut empty_map)),
23477            AvroValue::Map(nested),
23478        ];
23479        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
23480        let transport = vec![json!({
23481            "schema": MESSAGE_STREAM_SCHEMA,
23482            "stream_name": "orders",
23483            "message_id": "message-1",
23484            "position": 1,
23485            "payload_envelope": payload,
23486        })];
23487
23488        for _ in 0..2 {
23489            let Some(MessageStreamDelivery::Message(message)) =
23490                decode_message_stream_delivery(transport.clone()).expect("delivery")
23491            else {
23492                panic!("message delivery expected");
23493            };
23494            assert_eq!(message.arguments, values);
23495            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
23496            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
23497        }
23498    }
23499
23500    #[test]
23501    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
23502        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23503            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23504                value.to_string(),
23505            )]))
23506            .expect("message payload");
23507            json!({
23508                "schema": MESSAGE_STREAM_SCHEMA,
23509                "stream_name": "orders",
23510                "message_id": message_id,
23511                "position": position,
23512                "payload_envelope": payload,
23513            })
23514        }
23515
23516        fn opened(sequence: u64) -> HistoryEvent {
23517            history_event(
23518                "SignalWaitOpened",
23519                json!({
23520                    "sequence": sequence,
23521                    "signal_name": MESSAGE_STREAM_SIGNAL,
23522                }),
23523            )
23524        }
23525
23526        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23527            history_event(
23528                "SignalApplied",
23529                json!({
23530                    "sequence": sequence,
23531                    "signal_name": MESSAGE_STREAM_SIGNAL,
23532                    "value": fixture_envelope(json!([delivery])),
23533                }),
23534            )
23535        }
23536
23537        fn worker() -> Worker {
23538            let client = Client::new("http://127.0.0.1:8080").expect("client");
23539            let mut worker = Worker::new(client, "rust-workers");
23540            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
23541                let stream = ctx.message_stream("orders")?;
23542                let first = stream.receive_one().await?;
23543                let second = stream.receive_one().await?;
23544                Ok(json!([first.message_id, second.message_id]))
23545            });
23546            worker
23547        }
23548
23549        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
23550            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
23551            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
23552            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
23553            task
23554        }
23555
23556        let waiting = worker()
23557            .execute_workflow_task_decision(workflow_task(
23558                "rust.message-stream",
23559                Vec::new(),
23560                DEFAULT_CODEC,
23561            ))
23562            .expect("first worker opens the stream wait");
23563        assert_eq!(
23564            waiting.commands,
23565            vec![json!({
23566                "type": "open_signal_wait",
23567                "signal_name": MESSAGE_STREAM_SIGNAL,
23568            })]
23569        );
23570        assert!(waiting.message_stream_cursors.is_empty());
23571        assert_eq!(
23572            waiting.message_stream_waits,
23573            vec![json!({"stream_name": "orders", "after_position": 0})]
23574        );
23575
23576        let first_delivery = delivery("message-1", 1, "one");
23577        let first_arrival = worker()
23578            .execute_workflow_task_decision(task_with_resume(
23579                vec![opened(1)],
23580                first_delivery.clone(),
23581            ))
23582            .expect("replacement worker consumes the first arrival");
23583        assert_eq!(
23584            first_arrival.commands,
23585            vec![json!({
23586                "type": "open_signal_wait",
23587                "signal_name": MESSAGE_STREAM_SIGNAL,
23588            })]
23589        );
23590        assert_eq!(
23591            first_arrival.message_stream_cursors,
23592            vec![json!({"stream_name": "orders", "through_position": 1})]
23593        );
23594        assert_eq!(
23595            first_arrival.message_stream_waits,
23596            vec![json!({"stream_name": "orders", "after_position": 1})]
23597        );
23598
23599        let second_delivery = delivery("message-2", 2, "two");
23600        let first_applied = applied(1, first_delivery);
23601        let completed = worker()
23602            .execute_workflow_task_decision(task_with_resume(
23603                vec![opened(1), first_applied.clone(), opened(2)],
23604                second_delivery.clone(),
23605            ))
23606            .expect("next replacement worker consumes the second arrival");
23607        assert_eq!(completed.commands.len(), 1);
23608        assert_eq!(completed.commands[0]["type"], "complete_workflow");
23609        assert_eq!(
23610            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
23611                .expect("workflow result"),
23612            json!(["message-1", "message-2"])
23613        );
23614        assert_eq!(
23615            completed.message_stream_cursors,
23616            vec![json!({"stream_name": "orders", "through_position": 2})]
23617        );
23618        assert!(completed.message_stream_waits.is_empty());
23619
23620        let replay_history = vec![
23621            opened(1),
23622            first_applied,
23623            opened(2),
23624            applied(2, second_delivery),
23625        ];
23626        for _cold_worker_or_restart in 0..2 {
23627            let replayed = worker()
23628                .execute_workflow_task_decision(workflow_task(
23629                    "rust.message-stream",
23630                    replay_history.clone(),
23631                    DEFAULT_CODEC,
23632                ))
23633                .expect("cold worker replays each logical message exactly once");
23634            assert_eq!(replayed.commands.len(), 1);
23635            assert_eq!(
23636                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
23637                    .expect("replayed workflow result"),
23638                json!(["message-1", "message-2"])
23639            );
23640            assert_eq!(
23641                replayed.message_stream_cursors,
23642                vec![json!({"stream_name": "orders", "through_position": 2})]
23643            );
23644            assert!(replayed.message_stream_waits.is_empty());
23645        }
23646    }
23647
23648    #[test]
23649    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
23650        assert!(!worker_protocol_supports_message_streams("1.14"));
23651        assert!(worker_protocol_supports_message_streams("1.15"));
23652        assert!(worker_protocol_supports_message_streams("1.16"));
23653        assert!(worker_protocol_supports_message_streams(
23654            WORKER_PROTOCOL_VERSION
23655        ));
23656        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
23657    }
23658
23659    #[test]
23660    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
23661        let ctx = workflow_context(vec![
23662            history_event(
23663                "ConditionWaitOpened",
23664                json!({
23665                    "sequence": 1,
23666                    "condition_wait_id": "condition:1",
23667                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23668                    "condition_key": "signal:finish",
23669                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
23670                }),
23671            ),
23672            history_event(
23673                "ConditionWaitSatisfied",
23674                json!({
23675                    "sequence": 1,
23676                    "condition_wait_id": "condition:1",
23677                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23678                    "condition_key": "signal:finish",
23679                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
23680                }),
23681            ),
23682            history_event(
23683                "SignalReceived",
23684                json!({"signal_name": "finish", "arguments": []}),
23685            ),
23686        ]);
23687        let mut signal = Box::pin(ctx.wait_signal("finish"));
23688        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23689
23690        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23691            signal.as_mut().poll(&mut task_context)
23692        else {
23693            panic!("condition history must not resolve as a typed signal wait");
23694        };
23695        assert_eq!(failure.reason, "recorded_command_mismatch");
23696        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
23697    }
23698
23699    #[test]
23700    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
23701        let signal_then_timer = vec![
23702            history_event(
23703                "SignalWaitOpened",
23704                json!({"sequence": 1, "signal_name": "go"}),
23705            ),
23706            history_event(
23707                "SignalApplied",
23708                json!({
23709                    "sequence": 1,
23710                    "signal_name": "go",
23711                    "value": fixture_envelope(json!(["now"])),
23712                }),
23713            ),
23714            history_event(
23715                "TimerScheduled",
23716                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
23717            ),
23718            history_event(
23719                "TimerFired",
23720                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
23721            ),
23722        ];
23723
23724        let ctx = workflow_context(signal_then_timer.clone());
23725        let mut signal = Box::pin(ctx.wait_signal("go"));
23726        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23727        assert!(matches!(
23728            signal.as_mut().poll(&mut task_context),
23729            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
23730        ));
23731        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
23732        assert!(matches!(
23733            timer.as_mut().poll(&mut task_context),
23734            Poll::Ready(Ok(()))
23735        ));
23736        ctx.ensure_history_consumed()
23737            .expect("signal and timer history consumed in order");
23738
23739        let reordered = workflow_context(signal_then_timer);
23740        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
23741        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23742            timer_first.as_mut().poll(&mut task_context)
23743        else {
23744            panic!("timer cannot consume signal-wait-first history");
23745        };
23746        assert_eq!(failure.reason, "recorded_command_mismatch");
23747        assert_eq!(failure.sequence, Some(1));
23748        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
23749
23750        let timer_then_signal = vec![
23751            history_event(
23752                "TimerScheduled",
23753                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23754            ),
23755            history_event(
23756                "TimerFired",
23757                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23758            ),
23759            history_event(
23760                "SignalWaitOpened",
23761                json!({"sequence": 2, "signal_name": "go"}),
23762            ),
23763            history_event(
23764                "SignalApplied",
23765                json!({
23766                    "sequence": 2,
23767                    "signal_name": "go",
23768                    "value": fixture_envelope(json!([])),
23769                }),
23770            ),
23771        ];
23772        let reordered = workflow_context(timer_then_signal);
23773        let mut signal_first = Box::pin(reordered.wait_signal("go"));
23774        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23775            signal_first.as_mut().poll(&mut task_context)
23776        else {
23777            panic!("signal wait cannot consume timer-first history");
23778        };
23779        assert_eq!(failure.reason, "recorded_command_mismatch");
23780        assert_eq!(failure.sequence, Some(1));
23781        assert_eq!(failure.expected.as_deref(), Some("timer"));
23782    }
23783
23784    #[test]
23785    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
23786        let duplicate_timer = WorkflowState::new(
23787            vec![
23788                history_event(
23789                    "TimerScheduled",
23790                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23791                ),
23792                history_event(
23793                    "TimerScheduled",
23794                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23795                ),
23796            ],
23797            "rust-workers".to_string(),
23798            DEFAULT_CODEC.to_string(),
23799            None,
23800        )
23801        .expect_err("one workflow sequence cannot schedule two timers");
23802        assert!(matches!(
23803            duplicate_timer,
23804            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23805                if reason == "timer_schedule_missing_or_duplicate"
23806        ));
23807
23808        let colliding_kinds = WorkflowState::new(
23809            vec![
23810                history_event(
23811                    "TimerScheduled",
23812                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23813                ),
23814                history_event(
23815                    "ActivityCompleted",
23816                    json!({"sequence": 1, "activity_type": "same-sequence"}),
23817                ),
23818            ],
23819            "rust-workers".to_string(),
23820            DEFAULT_CODEC.to_string(),
23821            None,
23822        )
23823        .expect_err("one workflow sequence cannot identify two command kinds");
23824        assert!(matches!(
23825            colliding_kinds,
23826            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23827                if reason == "durable_command_sequence_collision"
23828        ));
23829
23830        let duplicate_signal_wait = WorkflowState::new(
23831            vec![
23832                history_event(
23833                    "SignalWaitOpened",
23834                    json!({"sequence": 1, "signal_name": "go"}),
23835                ),
23836                history_event(
23837                    "SignalWaitOpened",
23838                    json!({"sequence": 1, "signal_name": "go"}),
23839                ),
23840            ],
23841            "rust-workers".to_string(),
23842            DEFAULT_CODEC.to_string(),
23843            None,
23844        )
23845        .expect_err("one workflow sequence cannot open two signal waits");
23846        assert!(matches!(
23847            duplicate_signal_wait,
23848            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23849                if reason == "signal_wait_open_missing_or_duplicate"
23850        ));
23851    }
23852
23853    #[test]
23854    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
23855        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
23856            .expect("side-effect result");
23857        let ctx = workflow_context(vec![history_event(
23858            "SideEffectRecorded",
23859            json!({"sequence": 99, "result": result}),
23860        )]);
23861
23862        let replayed: Value = ctx
23863            .side_effect(|| panic!("recorded side effect must not run"))
23864            .expect("positive global workflow sequence is valid");
23865        assert_eq!(replayed, json!({"captured": true}));
23866        ctx.ensure_history_consumed().expect("history consumed");
23867    }
23868
23869    #[test]
23870    fn workflow_history_rejects_zero_and_descending_command_sequences() {
23871        let result =
23872            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
23873        let zero = WorkflowState::new(
23874            vec![history_event(
23875                "SideEffectRecorded",
23876                json!({"sequence": 0, "result": result.clone()}),
23877            )],
23878            "rust-workers".to_string(),
23879            DEFAULT_CODEC.to_string(),
23880            None,
23881        )
23882        .expect_err("durable command sequences must be positive");
23883        assert!(matches!(
23884            zero,
23885            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23886                if reason == "durable_command_sequence_invalid"
23887        ));
23888
23889        let descending = WorkflowState::new(
23890            vec![
23891                history_event(
23892                    "SideEffectRecorded",
23893                    json!({"sequence": 3, "result": result}),
23894                ),
23895                history_event(
23896                    "VersionMarkerRecorded",
23897                    json!({
23898                        "sequence": 2,
23899                        "change_id": "descending-marker",
23900                        "version": 1,
23901                        "min_supported": 1,
23902                        "max_supported": 1,
23903                    }),
23904                ),
23905            ],
23906            "rust-workers".to_string(),
23907            DEFAULT_CODEC.to_string(),
23908            None,
23909        )
23910        .expect_err("new durable commands must remain strictly ordered");
23911        let Error::NonDeterministicReplay(failure) = descending else {
23912            panic!("expected typed replay failure");
23913        };
23914        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
23915        assert_eq!(failure.sequence, Some(2));
23916        assert_eq!(
23917            failure.expected.as_deref(),
23918            Some("workflow sequence greater than 3")
23919        );
23920        assert_eq!(failure.actual.as_deref(), Some("2"));
23921    }
23922
23923    #[test]
23924    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
23925        fn worker() -> Worker {
23926            let client = Client::new("http://127.0.0.1:8080").expect("client");
23927            let mut worker = Worker::new(client, "rust-workers");
23928            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
23929                ctx.wait_signal("finish").await?;
23930                let marker: String =
23931                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
23932                assert_eq!(marker, "after-finish");
23933                Ok(json!("finished"))
23934            });
23935            worker
23936        }
23937
23938        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
23939            .expect("side-effect result");
23940        let task = workflow_task(
23941            "rust.finish-after-gaps",
23942            vec![
23943                history_event(
23944                    "SignalWaitOpened",
23945                    json!({"sequence": 1, "signal_name": "finish"}),
23946                ),
23947                history_event(
23948                    "SignalReceived",
23949                    json!({
23950                        "signal_id": "increment-3",
23951                        "signal_name": "increment",
23952                        "workflow_sequence": 2,
23953                        "payload_codec": DEFAULT_CODEC,
23954                        "arguments": fixture_envelope(json!([3])),
23955                    }),
23956                ),
23957                history_event(
23958                    "SignalReceived",
23959                    json!({
23960                        "signal_id": "increment-5",
23961                        "signal_name": "increment",
23962                        "workflow_sequence": 3,
23963                        "payload_codec": DEFAULT_CODEC,
23964                        "arguments": fixture_envelope(json!([5])),
23965                    }),
23966                ),
23967                history_event(
23968                    "SignalReceived",
23969                    json!({
23970                        "signal_id": "finish",
23971                        "signal_name": "finish",
23972                        "workflow_sequence": 4,
23973                        "payload_codec": DEFAULT_CODEC,
23974                        "arguments": fixture_envelope(json!([])),
23975                    }),
23976                ),
23977                history_event(
23978                    "SignalApplied",
23979                    json!({
23980                        "sequence": 1,
23981                        "signal_id": "finish",
23982                        "signal_name": "finish",
23983                        "payload_codec": DEFAULT_CODEC,
23984                        "value": fixture_envelope(json!([])),
23985                    }),
23986                ),
23987                history_event(
23988                    "SideEffectRecorded",
23989                    json!({"sequence": 5, "result": marker}),
23990                ),
23991            ],
23992            DEFAULT_CODEC,
23993        );
23994
23995        for _original_or_cold_worker in 0..2 {
23996            let commands = worker()
23997                .execute_workflow_task(task.clone())
23998                .expect("signal gaps preserve deterministic replay");
23999            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
24000            assert_eq!(commands[0]["type"], "complete_workflow");
24001            assert_eq!(
24002                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24003                json!("finished")
24004            );
24005        }
24006    }
24007
24008    #[test]
24009    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
24010        let ctx = workflow_context(Vec::new());
24011        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
24012        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24013        assert!(matches!(
24014            sleep.as_mut().poll(&mut task_context),
24015            Poll::Ready(Err(Error::TimerDurationOverflow))
24016        ));
24017        assert!(ctx.take_commands().expect("commands").is_empty());
24018    }
24019
24020    #[test]
24021    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
24022        let entries = AvroValue::Map(BTreeMap::from([
24023            ("text".to_string(), AvroValue::String("same".to_string())),
24024            (
24025                "nested".to_string(),
24026                AvroValue::Map(BTreeMap::from([
24027                    ("beta".to_string(), AvroValue::Long(2)),
24028                    ("alpha".to_string(), AvroValue::Long(1)),
24029                ])),
24030            ),
24031            ("long".to_string(), AvroValue::Long(7)),
24032            ("double".to_string(), AvroValue::Double(7.0)),
24033            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
24034        ]));
24035        let ctx = workflow_context(Vec::new());
24036        ctx.upsert_memo(entries.clone()).expect("valid memo update");
24037        let commands = ctx.take_commands().expect("commands");
24038
24039        assert_eq!(commands.len(), 1);
24040        assert_eq!(commands[0]["type"], "upsert_memo");
24041        let server_entries = json!({
24042            "codec": "avro",
24043            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
24044        });
24045        assert_eq!(
24046            commands[0]["entries"]
24047                .as_object()
24048                .expect("entries envelope")
24049                .keys()
24050                .collect::<Vec<_>>(),
24051            vec!["blob", "codec"]
24052        );
24053        assert_eq!(commands[0]["entries"], server_entries);
24054        let wire_entries =
24055            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
24056        assert_eq!(wire_entries, entries);
24057
24058        let history = vec![history_event(
24059            "MemoUpserted",
24060            json!({
24061                "sequence": 1,
24062                "entries": server_entries.clone(),
24063                "merged": server_entries,
24064            }),
24065        )];
24066        let replay = workflow_context(history.clone());
24067        replay
24068            .upsert_memo(entries.clone())
24069            .expect("matching replay identity");
24070        assert!(replay.take_commands().expect("replay commands").is_empty());
24071
24072        let changed_types = AvroValue::Map(BTreeMap::from([
24073            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
24074            (
24075                "nested".to_string(),
24076                AvroValue::Map(BTreeMap::from([
24077                    ("alpha".to_string(), AvroValue::Long(1)),
24078                    ("beta".to_string(), AvroValue::Long(2)),
24079                ])),
24080            ),
24081            ("long".to_string(), AvroValue::Double(7.0)),
24082            ("double".to_string(), AvroValue::Long(7)),
24083            ("binary".to_string(), AvroValue::String("same".to_string())),
24084        ]));
24085        let error = workflow_context(history)
24086            .upsert_memo(changed_types)
24087            .expect_err("memo replay identity must preserve Avro value types");
24088        assert!(matches!(
24089            error,
24090            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24091        ));
24092    }
24093
24094    #[test]
24095    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
24096        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
24097            .expect("memo envelope");
24098        let replay = workflow_context(vec![history_event(
24099            "MemoUpserted",
24100            json!({
24101                "sequence": 1,
24102                "entries": original.clone(),
24103                "merged": original
24104            }),
24105        )]);
24106        let error = replay
24107            .upsert_memo(json!({"stage": "changed"}))
24108            .expect_err("changed memo update must fail replay");
24109        assert!(matches!(
24110            error,
24111            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24112        ));
24113
24114        let invalid = workflow_context(Vec::new())
24115            .upsert_memo(
24116                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
24117            )
24118            .expect_err("oversized key");
24119        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
24120    }
24121
24122    #[test]
24123    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
24124        let negative_zero = AvroValue::Map(BTreeMap::from([(
24125            "reading".to_string(),
24126            AvroValue::Double(-0.0),
24127        )]));
24128        let negative_zero_envelope =
24129            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
24130        let history = vec![history_event(
24131            "MemoUpserted",
24132            json!({
24133                "sequence": 1,
24134                "entries": negative_zero_envelope.clone(),
24135                "merged": negative_zero_envelope,
24136            }),
24137        )];
24138
24139        workflow_context(history.clone())
24140            .upsert_memo(negative_zero)
24141            .expect("matching negative-zero history identity");
24142
24143        let error = workflow_context(history)
24144            .upsert_memo(AvroValue::Map(BTreeMap::from([(
24145                "reading".to_string(),
24146                AvroValue::Double(0.0),
24147            )])))
24148            .expect_err("positive zero must not consume negative-zero memo history");
24149        assert!(matches!(
24150            error,
24151            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24152        ));
24153    }
24154
24155    #[test]
24156    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
24157        let supported = json!({
24158            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
24159            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
24160        });
24161        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
24162        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
24163            "workflow_memo_updates": {"supported": false},
24164            "supported_workflow_task_commands": ["upsert_memo"]
24165        }))));
24166        assert!(commands_use_workflow_memo_updates(&[json!({
24167            "type": "upsert_memo",
24168            "entries": {"stage": "processing"}
24169        })]));
24170    }
24171
24172    #[test]
24173    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
24174        let client = Client::new("http://127.0.0.1:8080").expect("client");
24175        let mut worker = Worker::new(client, "rust-workers");
24176        worker.register_workflow("rust.timer", |ctx, _input| async move {
24177            ctx.sleep(Duration::from_secs(5)).await?;
24178            ctx.activity("after-timer", json!([])).await
24179        });
24180
24181        let task = |history_events| WorkflowTask {
24182            task_id: "wft-rust-timer-1".to_string(),
24183            workflow_command_id: None,
24184            workflow_id: Some("wf-rust-timer".to_string()),
24185            run_id: Some("run-rust-timer".to_string()),
24186            workflow_type: "rust.timer".to_string(),
24187            cancel_requested: false,
24188            payload_codec: DEFAULT_CODEC.to_string(),
24189            arguments: Some(
24190                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24191            ),
24192            history_events,
24193            total_history_events: None,
24194            history_size_bytes: None,
24195            continue_as_new_recommended: None,
24196            history_budget_pressure: None,
24197            next_history_page_token: None,
24198            workflow_task_attempt: 1,
24199            workflow_signal_id: None,
24200            signal_name: None,
24201            signal_arguments: None,
24202            workflow_update_id: None,
24203            update_name: None,
24204            lease_owner: Some("rust-worker".to_string()),
24205        };
24206
24207        let initial = worker
24208            .execute_workflow_task(task(Vec::new()))
24209            .expect("initial timer task");
24210        assert_eq!(
24211            initial,
24212            vec![json!({"type": "start_timer", "delay_seconds": 5})]
24213        );
24214
24215        let activity_result =
24216            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
24217        let replayed = worker
24218            .execute_workflow_task(task(vec![
24219                history_event(
24220                    "TimerScheduled",
24221                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24222                ),
24223                history_event(
24224                    "TimerFired",
24225                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24226                ),
24227                history_event(
24228                    "ActivityCompleted",
24229                    json!({
24230                        "sequence": 2,
24231                        "activity_type": "after-timer",
24232                        "payload_codec": DEFAULT_CODEC,
24233                        "result": activity_result,
24234                    }),
24235                ),
24236            ]))
24237            .expect("replayed workflow task");
24238        assert_eq!(replayed.len(), 1);
24239        assert_eq!(replayed[0]["type"], "complete_workflow");
24240        assert_eq!(
24241            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
24242            json!("done")
24243        );
24244    }
24245
24246    #[test]
24247    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
24248        let client = Client::new("http://127.0.0.1:8080").expect("client");
24249        let mut worker = Worker::new(client, "rust-workers");
24250        worker.register_workflow("rust.continue", |ctx, _input| async move {
24251            ctx.continue_as_new_with_options(
24252                ContinueAsNewOptions::new()
24253                    .workflow_type("rust.next")
24254                    .task_queue("next-workers"),
24255                json!([2, {"cursor": "next"}]),
24256            )
24257        });
24258
24259        let commands = worker
24260            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
24261            .expect("continue-as-new command");
24262
24263        assert_eq!(commands.len(), 1);
24264        assert_eq!(commands[0]["type"], "continue_as_new");
24265        assert_eq!(commands[0]["workflow_type"], "rust.next");
24266        assert_eq!(commands[0]["queue"], "next-workers");
24267        assert_eq!(
24268            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
24269                .expect("continue-as-new arguments"),
24270            json!([2, {"cursor": "next"}])
24271        );
24272    }
24273
24274    #[test]
24275    fn continue_as_new_preserves_typed_arguments() {
24276        let client = Client::new("http://127.0.0.1:8080").expect("client");
24277        let mut worker = Worker::new(client, "rust-workers");
24278        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
24279            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
24280            unreachable!("continue-as-new returns a control-flow error")
24281        });
24282
24283        let commands = worker
24284            .execute_workflow_task(workflow_task(
24285                "rust.typed-continue",
24286                Vec::new(),
24287                DEFAULT_CODEC,
24288            ))
24289            .expect("typed continue-as-new command");
24290
24291        assert_eq!(commands[0]["type"], "continue_as_new");
24292        assert_eq!(
24293            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
24294                .expect("typed continue arguments"),
24295            AvroValue::Array(vec![typed_fidelity_probe()])
24296        );
24297    }
24298
24299    #[test]
24300    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
24301        let client = Client::new("http://127.0.0.1:8080").expect("client");
24302        let mut worker = Worker::new(client, "rust-workers");
24303        worker.register_workflow("rust.continue", |ctx, _input| async move {
24304            ctx.continue_as_new(json!([2]))
24305        });
24306        let task = workflow_task(
24307            "rust.continue",
24308            vec![history_event(
24309                "WorkflowContinuedAsNew",
24310                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
24311            )],
24312            DEFAULT_CODEC,
24313        );
24314
24315        for _worker_restart_or_redelivery in 0..2 {
24316            let commands = worker
24317                .execute_workflow_task(task.clone())
24318                .expect("recorded transition replays");
24319            assert!(
24320                commands.is_empty(),
24321                "replay must not emit another successor"
24322            );
24323        }
24324    }
24325
24326    #[test]
24327    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
24328        let ctx = workflow_context(Vec::new());
24329        let error = ctx
24330            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
24331            .expect_err("blank queue must be rejected");
24332
24333        let Error::InvalidContinueAsNewOptions(error) = error else {
24334            panic!("expected typed continue-as-new validation error");
24335        };
24336        assert_eq!(error.field, "task_queue");
24337        assert!(ctx.take_commands().expect("commands").is_empty());
24338    }
24339
24340    #[test]
24341    fn workflow_context_exposes_server_history_budget() {
24342        let client = Client::new("http://127.0.0.1:8080").expect("client");
24343        let mut worker = Worker::new(client, "rust-workers");
24344        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
24345            let budget = ctx.history_budget()?;
24346            Ok(json!({
24347                "events": budget.event_count,
24348                "bytes": budget.size_bytes,
24349                "recommended": budget.continue_as_new_recommended,
24350                "pressure": budget.pressure,
24351            }))
24352        });
24353        let task: WorkflowTask = serde_json::from_value(json!({
24354            "task_id": "task-history-budget",
24355            "workflow_type": "rust.history-budget",
24356            "payload_codec": DEFAULT_CODEC,
24357            "history_events": [],
24358            "total_history_events": 480,
24359            "history_size_bytes": 1_048_576,
24360            "continue_as_new_recommended": true,
24361            "history_budget_pressure": "continue_as_new_recommended",
24362        }))
24363        .expect("published workflow task");
24364
24365        let commands = worker
24366            .execute_workflow_task(task)
24367            .expect("history-budget workflow");
24368        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
24369        assert_eq!(result["events"], 480);
24370        assert_eq!(result["bytes"], 1_048_576);
24371        assert_eq!(result["recommended"], true);
24372        assert_eq!(result["pressure"], "continue_as_new_recommended");
24373    }
24374
24375    #[test]
24376    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
24377        let client = Client::new("http://127.0.0.1:8080").expect("client");
24378        let mut worker = Worker::new(client, "rust-workers");
24379        worker.register_workflow("rust.failing", |_ctx, _input| async move {
24380            Err(Error::Codec("rust_conformance_failure".to_string()))
24381        });
24382        let task = WorkflowTask {
24383            task_id: "wft-rust-failing-1".to_string(),
24384            workflow_command_id: None,
24385            workflow_id: Some("wf-rust-failing".to_string()),
24386            run_id: Some("run-rust-failing".to_string()),
24387            workflow_type: "rust.failing".to_string(),
24388            cancel_requested: false,
24389            payload_codec: DEFAULT_CODEC.to_string(),
24390            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24391            history_events: Vec::new(),
24392            total_history_events: Some(0),
24393            history_size_bytes: None,
24394            continue_as_new_recommended: None,
24395            history_budget_pressure: None,
24396            next_history_page_token: None,
24397            workflow_task_attempt: 1,
24398            workflow_signal_id: None,
24399            signal_name: None,
24400            signal_arguments: None,
24401            workflow_update_id: None,
24402            update_name: None,
24403            lease_owner: Some("rust-worker".to_string()),
24404        };
24405
24406        let commands = worker
24407            .execute_workflow_task(task)
24408            .expect("handler failure becomes a workflow command");
24409
24410        assert_eq!(commands.len(), 1);
24411        assert_eq!(commands[0]["type"], "fail_workflow");
24412        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
24413        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
24414        assert_eq!(commands[0]["non_retryable"], false);
24415        assert_eq!(
24416            commands[0]["message"],
24417            "codec error: rust_conformance_failure"
24418        );
24419        assert_eq!(
24420            commands[0]["exception"]["message"],
24421            "codec error: rust_conformance_failure"
24422        );
24423    }
24424
24425    #[test]
24426    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
24427        let client = Client::new("http://127.0.0.1:8080").expect("client");
24428        let mut worker = Worker::new(client, "rust-workers");
24429        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
24430            let _: String = ctx.side_effect(|| "captured".to_string())?;
24431            Err(Error::WorkerLoop("application failure".to_string()))
24432        });
24433
24434        let commands = worker
24435            .execute_workflow_task(workflow_task(
24436                "rust.failing-after-side-effect",
24437                Vec::new(),
24438                DEFAULT_CODEC,
24439            ))
24440            .expect("ordinary failure remains a workflow decision");
24441
24442        assert_eq!(commands.len(), 2);
24443        assert_eq!(commands[0]["type"], "record_side_effect");
24444        assert_eq!(commands[1]["type"], "fail_workflow");
24445    }
24446
24447    #[test]
24448    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
24449        let client = Client::new("http://127.0.0.1:8080").expect("client");
24450        let mut worker = Worker::new(client, "rust-workers");
24451        worker.register_workflow("rust.redrive", |ctx, _input| async move {
24452            ctx.activity("greet", json!([])).await?;
24453            Ok(Value::Null)
24454        });
24455        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
24456            match ctx.activity("greet", json!([])).await {
24457                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
24458                result => result,
24459            }
24460        });
24461
24462        let failed = history_event(
24463            "ActivityFailed",
24464            json!({
24465                "sequence": 1,
24466                "activity_type": "greet",
24467                "activity_execution_id": "activity-1",
24468                "message": "failed"
24469            }),
24470        );
24471        let commands = worker
24472            .execute_workflow_task(workflow_task(
24473                "rust.redrive",
24474                vec![failed.clone()],
24475                DEFAULT_CODEC,
24476            ))
24477            .expect("recorded failure becomes a workflow command");
24478        assert_eq!(commands[0]["type"], "fail_workflow");
24479        assert_eq!(commands[0]["failed_step_sequence"], 1);
24480        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
24481
24482        let translated = worker
24483            .execute_workflow_task(workflow_task(
24484                "rust.redrive-translated",
24485                vec![failed],
24486                DEFAULT_CODEC,
24487            ))
24488            .expect("translated failure becomes a workflow command");
24489        assert_eq!(translated[0]["type"], "fail_workflow");
24490        assert!(translated[0].get("failed_step_sequence").is_none());
24491        assert!(translated[0].get("failed_activity_execution_id").is_none());
24492
24493        let without_identity = worker
24494            .execute_workflow_task(workflow_task(
24495                "rust.redrive",
24496                vec![history_event(
24497                    "ActivityFailed",
24498                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
24499                )],
24500                DEFAULT_CODEC,
24501            ))
24502            .expect("incomplete identity still fails the workflow");
24503        assert!(without_identity[0].get("failed_step_sequence").is_none());
24504
24505        let timed_out = worker
24506            .execute_workflow_task(workflow_task(
24507                "rust.redrive",
24508                vec![history_event(
24509                    "ActivityTimedOut",
24510                    json!({
24511                        "sequence": 1,
24512                        "activity_type": "greet",
24513                        "activity_execution_id": "activity-timeout",
24514                    }),
24515                )],
24516                DEFAULT_CODEC,
24517            ))
24518            .expect("timeout still fails the workflow");
24519        assert!(timed_out[0].get("failed_step_sequence").is_none());
24520    }
24521
24522    #[test]
24523    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
24524        let client = Client::new("http://127.0.0.1:8080").expect("client");
24525        let mut worker = Worker::new(client, "rust-workers");
24526        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
24527            let first = ctx.activity("first", json!([])).await?;
24528            let second = ctx.activity("second", json!([first.clone()])).await?;
24529            Ok(json!({"first": first, "second": second}))
24530        });
24531        let first = history_event(
24532            "ActivityCompleted",
24533            json!({
24534                "sequence": 1,
24535                "activity_type": "first",
24536                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
24537                "payload_codec": DEFAULT_CODEC,
24538                "reused_from_run_id": "failed-run",
24539                "reused_activity_execution_id": "original-first",
24540            }),
24541        );
24542
24543        let retry = worker
24544            .execute_workflow_task(workflow_task(
24545                "rust.redrive-successor",
24546                vec![first.clone()],
24547                DEFAULT_CODEC,
24548            ))
24549            .expect("reused result replays before failed step");
24550        assert_eq!(retry.len(), 1);
24551        assert_eq!(retry[0]["type"], "schedule_activity");
24552        assert_eq!(retry[0]["activity_type"], "second");
24553        assert_eq!(
24554            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
24555            json!(["recorded"]),
24556        );
24557
24558        let second = history_event(
24559            "ActivityCompleted",
24560            json!({
24561                "sequence": 2,
24562                "activity_type": "second",
24563                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
24564                "payload_codec": DEFAULT_CODEC,
24565            }),
24566        );
24567        let completed = worker
24568            .execute_workflow_task(workflow_task(
24569                "rust.redrive-successor",
24570                vec![first, second],
24571                DEFAULT_CODEC,
24572            ))
24573            .expect("retried step completes the successor");
24574        assert_eq!(completed.len(), 1);
24575        assert_eq!(completed[0]["type"], "complete_workflow");
24576        assert_eq!(
24577            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
24578            json!({"first": "recorded", "second": "retried"}),
24579        );
24580    }
24581
24582    #[test]
24583    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
24584        let client = Client::new("http://127.0.0.1:8080").expect("client");
24585        let mut worker = Worker::new(client, "rust-workers");
24586        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
24587            Err(Error::WorkerLoop("application failure".to_string()))
24588        });
24589        let result =
24590            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
24591
24592        let error = worker
24593            .execute_workflow_task(workflow_task(
24594                "rust.removed-side-effect",
24595                vec![history_event(
24596                    "SideEffectRecorded",
24597                    json!({"sequence": 1, "result": result}),
24598                )],
24599                DEFAULT_CODEC,
24600            ))
24601            .expect_err("removed committed history must not become fail_workflow");
24602
24603        let Error::NonDeterministicReplay(failure) = error else {
24604            panic!("expected typed replay failure");
24605        };
24606        assert_eq!(failure.reason, "recorded_commands_unconsumed");
24607        assert_eq!(failure.sequence, Some(1));
24608        assert_eq!(failure.expected.as_deref(), Some("side effect"));
24609    }
24610
24611    #[test]
24612    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
24613        let client = Client::new("http://127.0.0.1:8080").expect("client");
24614        let mut worker = Worker::new(client, "rust-workers");
24615        worker.register_workflow(
24616            "rust.side-effect-before-marker-error",
24617            |ctx, _input| async move {
24618                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
24619                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
24620                ctx.get_version("restart-safe", 2, 2)?;
24621                Ok(Value::Null)
24622            },
24623        );
24624
24625        let error = worker
24626            .execute_workflow_task(workflow_task(
24627                "rust.side-effect-before-marker-error",
24628                vec![history_event(
24629                    "VersionMarkerRecorded",
24630                    json!({
24631                        "sequence": 1,
24632                        "change_id": "restart-safe",
24633                        "version": 1,
24634                        "min_supported": 1,
24635                        "max_supported": 1,
24636                    }),
24637                )],
24638                DEFAULT_CODEC,
24639            ))
24640            .expect_err("replay error must return no queued workflow commands");
24641
24642        let Error::NonDeterministicReplay(failure) = error else {
24643            panic!("expected typed replay failure");
24644        };
24645        assert_eq!(failure.reason, "version_marker_incompatible_range");
24646        assert_eq!(failure.sequence, Some(1));
24647    }
24648
24649    #[test]
24650    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
24651        let client = Client::new("http://127.0.0.1:8080").expect("client");
24652        let mut worker = Worker::new(client, "rust-workers");
24653        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
24654            ctx.sleep(Duration::from_secs(5)).await?;
24655            Ok(json!({"status": "timer fired"}))
24656        });
24657
24658        let task = WorkflowTask {
24659            task_id: "wft-rust-timer-pending".to_string(),
24660            workflow_command_id: None,
24661            workflow_id: Some("wf-rust-timer".to_string()),
24662            run_id: Some("run-rust-timer".to_string()),
24663            workflow_type: "rust.timer.pending".to_string(),
24664            cancel_requested: false,
24665            payload_codec: DEFAULT_CODEC.to_string(),
24666            arguments: Some(
24667                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24668            ),
24669            history_events: vec![history_event(
24670                "TimerScheduled",
24671                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24672            )],
24673            total_history_events: Some(1),
24674            history_size_bytes: None,
24675            continue_as_new_recommended: None,
24676            history_budget_pressure: None,
24677            next_history_page_token: None,
24678            workflow_task_attempt: 1,
24679            workflow_signal_id: None,
24680            signal_name: None,
24681            signal_arguments: None,
24682            workflow_update_id: None,
24683            update_name: None,
24684            lease_owner: Some("rust-worker".to_string()),
24685        };
24686
24687        for _redelivery_or_restart in 0..2 {
24688            let commands = worker
24689                .execute_workflow_task(task.clone())
24690                .expect("recorded timer remains pending");
24691            assert!(
24692                commands.is_empty(),
24693                "recorded timer must not be rescheduled"
24694            );
24695        }
24696    }
24697
24698    #[test]
24699    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
24700        let client = Client::new("http://127.0.0.1:8080").expect("client");
24701        let mut worker = Worker::new(client, "rust-workers");
24702        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
24703            Ok(json!({"status": "completed"}))
24704        });
24705        let task = WorkflowTask {
24706            task_id: "wft-rust-timer-removed".to_string(),
24707            workflow_command_id: None,
24708            workflow_id: Some("wf-rust-timer".to_string()),
24709            run_id: Some("run-rust-timer".to_string()),
24710            workflow_type: "rust.timer.removed".to_string(),
24711            cancel_requested: false,
24712            payload_codec: DEFAULT_CODEC.to_string(),
24713            arguments: Some(
24714                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24715            ),
24716            history_events: vec![
24717                history_event(
24718                    "TimerScheduled",
24719                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24720                ),
24721                history_event(
24722                    "TimerFired",
24723                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24724                ),
24725            ],
24726            total_history_events: Some(2),
24727            history_size_bytes: None,
24728            continue_as_new_recommended: None,
24729            history_budget_pressure: None,
24730            next_history_page_token: None,
24731            workflow_task_attempt: 1,
24732            workflow_signal_id: None,
24733            signal_name: None,
24734            signal_arguments: None,
24735            workflow_update_id: None,
24736            update_name: None,
24737            lease_owner: Some("rust-worker".to_string()),
24738        };
24739
24740        let Error::NonDeterministicReplay(failure) = worker
24741            .execute_workflow_task(task)
24742            .expect_err("removed timer must fail replay")
24743        else {
24744            panic!("expected typed replay failure");
24745        };
24746        assert_eq!(failure.reason, "recorded_commands_unconsumed");
24747        assert_eq!(failure.sequence, Some(1));
24748    }
24749
24750    #[test]
24751    fn workflow_context_emits_explicit_child_workflow_contract() {
24752        let ctx = WorkflowContext {
24753            cancellation_scope_id: "root".into(),
24754            state: Arc::new(Mutex::new(
24755                WorkflowState::new_with_identity(
24756                    Vec::new(),
24757                    Some("wf-parent".to_string()),
24758                    Some("run-parent".to_string()),
24759                    "parent-workers".to_string(),
24760                    DEFAULT_CODEC.to_string(),
24761                    None,
24762                )
24763                .expect("workflow state"),
24764            )),
24765        };
24766        let options = ChildWorkflowOptions::new("python-workers")
24767            .parent_close_policy(ParentClosePolicy::RequestCancel)
24768            .retry_policy(ChildWorkflowRetryPolicy {
24769                max_attempts: Some(3),
24770                backoff_seconds: vec![1, 5],
24771                non_retryable_error_types: vec!["ValidationError".to_string()],
24772            })
24773            .execution_timeout_seconds(600)
24774            .run_timeout_seconds(120);
24775        let mut call = Box::pin(ctx.start_child_workflow(
24776            "python.fulfil-order",
24777            options,
24778            json!([{"order_id": "order-42"}]),
24779        ));
24780        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24781
24782        assert!(matches!(
24783            call.as_mut().poll(&mut task_context),
24784            Poll::Pending
24785        ));
24786        let commands = ctx.take_commands().expect("commands");
24787        assert_eq!(commands.len(), 1);
24788        let command = &commands[0];
24789        assert_eq!(command["type"], "start_child_workflow");
24790        assert_eq!(command["workflow_type"], "python.fulfil-order");
24791        assert_eq!(command["queue"], "python-workers");
24792        assert_eq!(command["parent_close_policy"], "request_cancel");
24793        assert_eq!(command["retry_policy"]["max_attempts"], 3);
24794        assert_eq!(command["execution_timeout_seconds"], 600);
24795        assert_eq!(command["run_timeout_seconds"], 120);
24796        assert_eq!(
24797            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
24798            json!([{"order_id": "order-42"}])
24799        );
24800    }
24801
24802    fn child_parent_worker() -> Worker {
24803        let client = Client::new("http://127.0.0.1:8080").expect("client");
24804        let mut worker = Worker::new(client, "rust-parent-workers");
24805        worker.register_workflow("rust.parent", |ctx, _input| async move {
24806            let child = ctx
24807                .start_child_workflow(
24808                    "python.child",
24809                    ChildWorkflowOptions::new("python-child-workers")
24810                        .parent_close_policy(ParentClosePolicy::Terminate),
24811                    json!([{"codec_probe": [1, true, "rust"]}]),
24812                )
24813                .await?;
24814            Ok(json!({
24815                "parent_workflow_id": child.parent.workflow_id,
24816                "parent_run_id": child.parent.run_id,
24817                "child_workflow_id": child.child.workflow_id,
24818                "child_run_id": child.child.run_id,
24819                "child_workflow_type": child.child_workflow_type,
24820                "result": child.result,
24821            }))
24822        });
24823        worker
24824    }
24825
24826    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
24827        WorkflowTask {
24828            task_id: "wft-child-parent".to_string(),
24829            workflow_command_id: None,
24830            workflow_id: Some("wf-parent".to_string()),
24831            run_id: Some("run-parent".to_string()),
24832            workflow_type: "rust.parent".to_string(),
24833            cancel_requested: false,
24834            payload_codec: DEFAULT_CODEC.to_string(),
24835            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24836            history_events: vec![
24837                HistoryEvent {
24838                    event_type: "ChildWorkflowScheduled".to_string(),
24839                    payload: json!({
24840                        "sequence": 1,
24841                        "child_call_id": "call-child",
24842                        "child_workflow_instance_id": "wf-child",
24843                        "child_workflow_run_id": "run-child",
24844                        "child_workflow_type": "python.child",
24845                        "parent_close_policy": "terminate",
24846                    }),
24847                    raw: HashMap::new(),
24848                },
24849                HistoryEvent {
24850                    event_type: event_type.to_string(),
24851                    payload,
24852                    raw: HashMap::new(),
24853                },
24854            ],
24855            total_history_events: Some(2),
24856            history_size_bytes: None,
24857            continue_as_new_recommended: None,
24858            history_budget_pressure: None,
24859            next_history_page_token: None,
24860            workflow_task_attempt: 1,
24861            workflow_signal_id: None,
24862            signal_name: None,
24863            signal_arguments: None,
24864            workflow_update_id: None,
24865            update_name: None,
24866            lease_owner: Some("rust-worker".to_string()),
24867        }
24868    }
24869
24870    #[test]
24871    fn committed_child_result_replays_without_starting_a_duplicate() {
24872        let worker = child_parent_worker();
24873        let task = child_parent_task(
24874            "ChildRunCompleted",
24875            json!({
24876                "sequence": 1,
24877                "child_call_id": "call-child",
24878                "child_workflow_instance_id": "wf-child",
24879                "child_workflow_run_id": "run-child",
24880                "child_workflow_type": "python.child",
24881                "payload_codec": DEFAULT_CODEC,
24882                "result": fixture_envelope(json!({"from":"python","ok":true})),
24883            }),
24884        );
24885
24886        for _restart in 0..2 {
24887            let commands = worker
24888                .execute_workflow_task(task.clone())
24889                .expect("replayed parent task");
24890            assert_eq!(commands.len(), 1);
24891            assert_eq!(commands[0]["type"], "complete_workflow");
24892            assert!(!commands
24893                .iter()
24894                .any(|command| command["type"] == "start_child_workflow"));
24895            let output =
24896                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
24897            assert_eq!(output["parent_workflow_id"], "wf-parent");
24898            assert_eq!(output["parent_run_id"], "run-parent");
24899            assert_eq!(output["child_workflow_id"], "wf-child");
24900            assert_eq!(output["child_run_id"], "run-child");
24901            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
24902        }
24903    }
24904
24905    #[test]
24906    fn typed_child_arguments_and_results_survive_replay() {
24907        let client = Client::new("http://127.0.0.1:8080").expect("client");
24908        let mut worker = Worker::new(client, "rust-parent-workers");
24909        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
24910            let child = ctx
24911                .start_child_workflow_avro_value(
24912                    "python.typed-child",
24913                    ChildWorkflowOptions::new("python-workers"),
24914                    AvroValue::Array(vec![typed_fidelity_probe()]),
24915                )
24916                .await?;
24917            Ok(child.result)
24918        });
24919
24920        let initial = worker
24921            .execute_workflow_task(workflow_task(
24922                "rust.typed-parent",
24923                Vec::new(),
24924                DEFAULT_CODEC,
24925            ))
24926            .expect("typed child start");
24927        assert_eq!(initial[0]["type"], "start_child_workflow");
24928        assert_eq!(
24929            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
24930                .expect("typed child arguments"),
24931            AvroValue::Array(vec![typed_fidelity_probe()])
24932        );
24933
24934        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
24935            .expect("typed child result");
24936        let task = workflow_task(
24937            "rust.typed-parent",
24938            vec![
24939                history_event(
24940                    "ChildWorkflowScheduled",
24941                    json!({
24942                        "sequence": 1,
24943                        "child_call_id": "call-typed",
24944                        "child_workflow_instance_id": "wf-child",
24945                        "child_workflow_run_id": "run-child",
24946                        "child_workflow_type": "python.typed-child",
24947                    }),
24948                ),
24949                history_event(
24950                    "ChildRunCompleted",
24951                    json!({
24952                        "sequence": 1,
24953                        "child_call_id": "call-typed",
24954                        "child_workflow_instance_id": "wf-child",
24955                        "child_workflow_run_id": "run-child",
24956                        "child_workflow_type": "python.typed-child",
24957                        "payload_codec": DEFAULT_CODEC,
24958                        "result": result,
24959                    }),
24960                ),
24961            ],
24962            DEFAULT_CODEC,
24963        );
24964
24965        let commands = worker
24966            .execute_workflow_task(task)
24967            .expect("typed child replay");
24968        assert_eq!(commands[0]["type"], "complete_workflow");
24969        assert_eq!(
24970            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
24971                .expect("typed parent result"),
24972            typed_fidelity_probe()
24973        );
24974    }
24975
24976    #[test]
24977    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
24978        let worker = child_parent_worker();
24979        let mut task = child_parent_task("unused", Value::Null);
24980        task.history_events.truncate(1);
24981        task.total_history_events = Some(1);
24982
24983        for _redelivery_or_restart in 0..2 {
24984            let commands = worker
24985                .execute_workflow_task(task.clone())
24986                .expect("recorded child remains pending");
24987            assert!(
24988                commands.is_empty(),
24989                "recorded pending child must not be started again"
24990            );
24991        }
24992    }
24993
24994    #[test]
24995    fn child_cancellation_becomes_stable_parent_failure_command() {
24996        let worker = child_parent_worker();
24997        let task = child_parent_task(
24998            "ChildRunCancelled",
24999            json!({
25000                "sequence": 1,
25001                "child_workflow_instance_id": "wf-child",
25002                "child_workflow_run_id": "run-child",
25003                "child_workflow_type": "python.child",
25004                "failure_id": "failure-child",
25005                "failure_category": "cancelled",
25006                "message": "cancelled by parent-close policy",
25007            }),
25008        );
25009
25010        let commands = worker
25011            .execute_workflow_task(task)
25012            .expect("parent settlement");
25013        assert_eq!(commands.len(), 1);
25014        assert_eq!(commands[0]["type"], "fail_workflow");
25015        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
25016        assert_eq!(
25017            commands[0]["exception"]["properties"]["reason"],
25018            "cancelled"
25019        );
25020        assert_eq!(
25021            commands[0]["exception"]["properties"]["child_workflow_run_id"],
25022            "run-child"
25023        );
25024    }
25025
25026    #[test]
25027    fn workflow_can_handle_typed_child_failure() {
25028        let client = Client::new("http://127.0.0.1:8080").expect("client");
25029        let mut worker = Worker::new(client, "rust-parent-workers");
25030        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
25031            match ctx
25032                .start_child_workflow(
25033                    "python.child",
25034                    ChildWorkflowOptions::new("python-child-workers"),
25035                    json!([]),
25036                )
25037                .await
25038            {
25039                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
25040                    "reason": failure.reason,
25041                    "failure_id": failure.failure_id,
25042                    "exception_class": failure.exception_class,
25043                    "child_run_id": failure.child_workflow_run_id,
25044                })),
25045                Err(error) => Err(error),
25046                Ok(_) => Err(Error::WorkerLoop(
25047                    "child unexpectedly succeeded".to_string(),
25048                )),
25049            }
25050        });
25051        let mut task = child_parent_task(
25052            "ChildRunFailed",
25053            json!({
25054                "sequence": 1,
25055                "child_workflow_instance_id": "wf-child",
25056                "child_workflow_run_id": "run-child",
25057                "child_workflow_type": "python.child",
25058                "failure_id": "failure-child",
25059                "failure_category": "child_workflow",
25060                "message": "payment rejected",
25061                "exception": {
25062                    "type": "PaymentRejected",
25063                    "class": "payments.PaymentRejected",
25064                    "message": "payment rejected"
25065                }
25066            }),
25067        );
25068        task.workflow_type = "rust.handled-parent".to_string();
25069        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
25070
25071        let commands = worker.execute_workflow_task(task).expect("handled failure");
25072        assert_eq!(commands[0]["type"], "complete_workflow");
25073        let output =
25074            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25075        assert_eq!(output["reason"], "child_workflow");
25076        assert_eq!(output["failure_id"], "failure-child");
25077        assert_eq!(output["exception_class"], "payments.PaymentRejected");
25078        assert_eq!(output["child_run_id"], "run-child");
25079    }
25080
25081    #[test]
25082    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
25083        let client = Client::new("http://127.0.0.1:8080").expect("client");
25084        let mut worker = Worker::new(client, "rust-workers");
25085
25086        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
25087            let signal = ctx.wait_signal("start").await?;
25088            let name = signal
25089                .first()
25090                .and_then(|value| value.as_str())
25091                .unwrap_or("world");
25092            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
25093            Ok(json!({
25094                "greeting": greeting,
25095                "language": "rust"
25096            }))
25097        });
25098
25099        let signal_arguments =
25100            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
25101        let task = WorkflowTask {
25102            task_id: "wft-rust-signal-1".to_string(),
25103            workflow_command_id: None,
25104            workflow_id: Some("wf-rust-hello".to_string()),
25105            run_id: Some("run-rust-hello".to_string()),
25106            workflow_type: "rust.hello_workflow".to_string(),
25107            cancel_requested: false,
25108            payload_codec: DEFAULT_CODEC.to_string(),
25109            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25110            history_events: vec![HistoryEvent {
25111                event_type: "SignalReceived".to_string(),
25112                payload: json!({
25113                    "signal_id": "sig-rust-1",
25114                    "signal_name": "start"
25115                }),
25116                raw: HashMap::new(),
25117            }],
25118            total_history_events: Some(1),
25119            history_size_bytes: None,
25120            continue_as_new_recommended: None,
25121            history_budget_pressure: None,
25122            next_history_page_token: None,
25123            workflow_task_attempt: 1,
25124            workflow_signal_id: Some("sig-rust-1".to_string()),
25125            signal_name: Some("start".to_string()),
25126            signal_arguments: Some(signal_arguments),
25127            workflow_update_id: None,
25128            update_name: None,
25129            lease_owner: Some("rust-worker".to_string()),
25130        };
25131
25132        let commands = worker.execute_workflow_task(task).expect("workflow task");
25133
25134        assert_eq!(commands.len(), 1);
25135        assert_eq!(commands[0]["type"], "schedule_activity");
25136        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
25137        assert_eq!(
25138            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
25139            json!(["Rust"])
25140        );
25141    }
25142
25143    #[test]
25144    fn workflow_task_appends_paginated_history_events() {
25145        let mut task = WorkflowTask {
25146            task_id: "wft-rust-pages-1".to_string(),
25147            workflow_command_id: None,
25148            workflow_id: Some("wf-rust-pages".to_string()),
25149            run_id: Some("run-rust-pages".to_string()),
25150            workflow_type: "rust.hello_workflow".to_string(),
25151            cancel_requested: false,
25152            payload_codec: DEFAULT_CODEC.to_string(),
25153            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25154            history_events: vec![HistoryEvent {
25155                event_type: "WorkflowStarted".to_string(),
25156                payload: json!({}),
25157                raw: HashMap::new(),
25158            }],
25159            total_history_events: Some(3),
25160            history_size_bytes: None,
25161            continue_as_new_recommended: None,
25162            history_budget_pressure: None,
25163            next_history_page_token: Some("MQ==".to_string()),
25164            workflow_task_attempt: 1,
25165            workflow_signal_id: None,
25166            signal_name: None,
25167            signal_arguments: None,
25168            workflow_update_id: None,
25169            update_name: None,
25170            lease_owner: Some("rust-worker".to_string()),
25171        };
25172
25173        task.append_history_page(WorkflowTaskHistoryPage {
25174            history_events: vec![
25175                HistoryEvent {
25176                    event_type: "SignalReceived".to_string(),
25177                    payload: json!({
25178                        "signal_id": "sig-rust-1",
25179                        "signal_name": "start",
25180                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
25181                            .expect("signal arguments")
25182                    }),
25183                    raw: HashMap::new(),
25184                },
25185                HistoryEvent {
25186                    event_type: "MarkerRecorded".to_string(),
25187                    payload: json!({"sequence": 3}),
25188                    raw: HashMap::new(),
25189                },
25190            ],
25191            total_history_events: Some(3),
25192            next_history_page_token: None,
25193        });
25194
25195        assert_eq!(task.history_events.len(), 3);
25196        assert_eq!(task.total_history_events, Some(3));
25197        assert_eq!(task.next_history_page_token, None);
25198
25199        let signal = task
25200            .history_events
25201            .iter()
25202            .find(|event| event.event_type == "SignalReceived")
25203            .expect("signal event");
25204        assert_eq!(
25205            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
25206            vec![AvroValue::String("Rust".to_string())]
25207        );
25208    }
25209
25210    #[tokio::test]
25211    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
25212        let client = Client::new("http://127.0.0.1:8080").expect("client");
25213        let mut worker = Worker::new(client, "rust-workers");
25214        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25215        worker.register_query("counter", "current", |ctx, _args| async move {
25216            let mut count = 0_i64;
25217            for signal in ctx.signal_events() {
25218                let value = signal
25219                    .arguments
25220                    .first()
25221                    .and_then(Value::as_i64)
25222                    .unwrap_or_default();
25223                match signal.name.as_str() {
25224                    "increment" => count += value,
25225                    "set" => count = value,
25226                    _ => {}
25227                }
25228            }
25229            Ok(json!(count))
25230        });
25231
25232        let task = QueryTask {
25233            query_task_id: "query-rust-counter".to_string(),
25234            query_task_attempt: 1,
25235            lease_owner: Some("rust-worker".to_string()),
25236            workflow_id: Some("counter-1".to_string()),
25237            run_id: Some("run-counter-1".to_string()),
25238            workflow_type: "counter".to_string(),
25239            query_name: "current".to_string(),
25240            payload_codec: DEFAULT_CODEC.to_string(),
25241            workflow_arguments: Some(
25242                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25243            ),
25244            query_arguments: Some(
25245                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
25246            ),
25247            history_events: vec![
25248                HistoryEvent {
25249                    event_type: "SignalReceived".to_string(),
25250                    payload: json!({
25251                        "signal_id": "php-signal-1",
25252                        "signal_name": "increment",
25253                        "workflow_sequence": 1,
25254                        "payload_codec": DEFAULT_CODEC,
25255                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
25256                    }),
25257                    raw: HashMap::new(),
25258                },
25259                HistoryEvent {
25260                    event_type: "SignalReceived".to_string(),
25261                    payload: json!({
25262                        "signal_id": "python-signal-2",
25263                        "signal_name": "increment",
25264                        "workflow_sequence": 2,
25265                        "payload_codec": DEFAULT_CODEC,
25266                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
25267                    }),
25268                    raw: HashMap::new(),
25269                },
25270                HistoryEvent {
25271                    event_type: "SignalReceived".to_string(),
25272                    payload: json!({
25273                        "signal_id": "rust-signal-3",
25274                        "signal_name": "set",
25275                        "workflow_sequence": 3,
25276                        "payload_codec": DEFAULT_CODEC,
25277                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
25278                    }),
25279                    raw: HashMap::new(),
25280                },
25281            ],
25282            history_export: None,
25283            run_status: Some("completed".to_string()),
25284        };
25285
25286        let result = worker.execute_query_task(task).await.expect("query result");
25287        assert_eq!(result.into_json().expect("query projection"), json!(0));
25288    }
25289
25290    #[tokio::test]
25291    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
25292        let worker = replay_counter_worker();
25293        let running_history = json!([
25294            {
25295                "type": "ActivityCompleted",
25296                "payload": {
25297                    "sequence": 1,
25298                    "activity_type": "load-counter",
25299                    "payload_codec": DEFAULT_CODEC,
25300                    "result": fixture_envelope(json!("loaded"))
25301                }
25302            },
25303            {
25304                "type": "SignalWaitOpened",
25305                "payload": {
25306                    "sequence": 3,
25307                    "signal_name": "increment"
25308                }
25309            },
25310            {
25311                "type": "SignalReceived",
25312                "payload": {
25313                    "signal_id": "signal-3",
25314                    "signal_name": "increment",
25315                    "workflow_sequence": 2,
25316                    "payload_codec": DEFAULT_CODEC,
25317                    "arguments": fixture_envelope(json!([3]))
25318                }
25319            },
25320            {
25321                "type": "SignalApplied",
25322                "payload": {
25323                    "sequence": 3,
25324                    "signal_id": "signal-3",
25325                    "signal_name": "increment",
25326                    "payload_codec": DEFAULT_CODEC,
25327                    "value": fixture_envelope(json!([3]))
25328                }
25329            }
25330        ]);
25331
25332        let running = worker
25333            .execute_query_task(replay_counter_query(
25334                "current",
25335                running_history.clone(),
25336                "running",
25337            ))
25338            .await
25339            .expect("running replay query");
25340        assert_eq!(
25341            running.clone().into_json().expect("query projection"),
25342            json!({"loaded": "loaded", "count": 3, "finished": false})
25343        );
25344
25345        let detached = worker
25346            .execute_query_task(replay_counter_query(
25347                "detached-mutation",
25348                running_history.clone(),
25349                "running",
25350            ))
25351            .await
25352            .expect("query mutates only its detached state clone");
25353        assert_eq!(detached.into_json().expect("query projection"), json!(999));
25354        let failed = worker
25355            .execute_query_task(replay_counter_query(
25356                "failed-mutation",
25357                running_history.clone(),
25358                "running",
25359            ))
25360            .await
25361            .expect_err("failed query");
25362        assert_eq!(failed.reason, "query_rejected");
25363        let unchanged = worker
25364            .execute_query_task(replay_counter_query("current", running_history, "running"))
25365            .await
25366            .expect("later query reconstructs unchanged state");
25367        assert_eq!(unchanged, running);
25368
25369        let restarted_worker = replay_counter_worker();
25370        let empty_arguments = fixture_envelope(json!([]));
25371        let loaded_result = fixture_envelope(json!("loaded"));
25372        let signal_three = fixture_blob(json!([3]));
25373        let signal_five = fixture_blob(json!([5]));
25374        let restarted_task: QueryTask = serde_json::from_value(json!({
25375            "query_task_id": "query-after-restart",
25376            "workflow_id": "counter-1",
25377            "run_id": "run-counter-1",
25378            "workflow_type": "replay-counter",
25379            "query_name": "current",
25380            "payload_codec": DEFAULT_CODEC,
25381            "workflow_arguments": empty_arguments.clone(),
25382            "query_arguments": empty_arguments,
25383            "history_events": [],
25384            "history_export": {
25385                "payloads": {"codec": DEFAULT_CODEC},
25386                "history_events": [
25387                    {
25388                        "type": "ActivityCompleted",
25389                        "payload": {
25390                            "sequence": 1,
25391                            "activity_type": "load-counter",
25392                            "payload_codec": DEFAULT_CODEC,
25393                            "result": null
25394                        }
25395                    },
25396                    {
25397                        "type": "SignalWaitOpened",
25398                        "payload": {
25399                            "sequence": 3,
25400                            "signal_name": "increment"
25401                        }
25402                    },
25403                    {
25404                        "type": "SignalReceived",
25405                        "payload": {
25406                            "signal_id": "signal-3",
25407                            "signal_name": "increment",
25408                            "workflow_sequence": 2
25409                        }
25410                    },
25411                    {
25412                        "type": "SignalApplied",
25413                        "payload": {
25414                            "sequence": 3,
25415                            "signal_id": "signal-3",
25416                            "signal_name": "increment"
25417                        }
25418                    },
25419                    {
25420                        "type": "SignalWaitOpened",
25421                        "payload": {
25422                            "sequence": 5,
25423                            "signal_name": "increment"
25424                        }
25425                    },
25426                    {
25427                        "type": "SignalReceived",
25428                        "payload": {
25429                            "signal_id": "signal-5",
25430                            "signal_name": "increment",
25431                            "workflow_sequence": 4
25432                        }
25433                    },
25434                    {
25435                        "type": "SignalApplied",
25436                        "payload": {
25437                            "sequence": 5,
25438                            "signal_id": "signal-5",
25439                            "signal_name": "increment"
25440                        }
25441                    }
25442                ],
25443                "activities": [{
25444                    "sequence": 1,
25445                    "activity_type": "load-counter",
25446                    "payload_codec": DEFAULT_CODEC,
25447                    "result": loaded_result
25448                }],
25449                "signals": [
25450                    {
25451                        "id": "signal-3",
25452                        "name": "increment",
25453                        "workflow_sequence": 2,
25454                        "payload_codec": DEFAULT_CODEC,
25455                        "arguments": signal_three
25456                    },
25457                    {
25458                        "id": "signal-5",
25459                        "name": "increment",
25460                        "workflow_sequence": 4,
25461                        "payload_codec": DEFAULT_CODEC,
25462                        "arguments": signal_five
25463                    }
25464                ]
25465            },
25466            "run_status": "completed"
25467        }))
25468        .expect("cold replay query task");
25469        let completed = restarted_worker
25470            .execute_query_task(restarted_task)
25471            .await
25472            .expect("completed cold replay query");
25473        assert_eq!(
25474            completed.into_json().expect("query projection"),
25475            json!({"loaded": "loaded", "count": 8, "finished": true})
25476        );
25477    }
25478
25479    #[tokio::test]
25480    async fn replayed_query_replay_failures_are_machine_readable() {
25481        let worker = replay_counter_worker();
25482        let task = replay_counter_query(
25483            "current",
25484            json!([{
25485                "type": "ActivityCompleted",
25486                "payload": {
25487                    "sequence": 1,
25488                    "payload_codec": DEFAULT_CODEC,
25489                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
25490                }
25491            }]),
25492            "running",
25493        );
25494        let failure = worker
25495            .execute_query_task(task)
25496            .await
25497            .expect_err("invalid replay history payload");
25498        assert_eq!(failure.reason, "query_payload_decode_failed");
25499        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
25500        assert!(failure.message.contains("invalid_payload_framing"));
25501    }
25502
25503    #[tokio::test]
25504    async fn query_task_restores_compact_history_from_export() {
25505        let client = Client::new("http://127.0.0.1:8080").expect("client");
25506        let mut worker = Worker::new(client, "rust-workers");
25507        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25508        worker.register_query("counter", "current", |ctx, _args| async move {
25509            Ok(json!(ctx.signals("increment")[0][0]))
25510        });
25511        let empty_arguments = fixture_envelope(json!([]));
25512        let exported_signal = fixture_blob(json!([9]));
25513        let task: QueryTask = serde_json::from_value(json!({
25514            "query_task_id": "query-export",
25515            "workflow_type": "counter",
25516            "query_name": "current",
25517            "payload_codec": DEFAULT_CODEC,
25518            "workflow_arguments": empty_arguments.clone(),
25519            "query_arguments": empty_arguments,
25520            "history_events": [],
25521            "history_export": {
25522                "payloads": {"codec": DEFAULT_CODEC},
25523                "history_events": [{
25524                    "type": "SignalReceived",
25525                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
25526                }],
25527                "signals": [{
25528                    "id": "signal-export",
25529                    "name": "increment",
25530                    "status": "applied",
25531                    "workflow_sequence": 1,
25532                    "payload_codec": DEFAULT_CODEC,
25533                    "arguments": exported_signal
25534                }]
25535            }
25536        }))
25537        .expect("query task");
25538
25539        let result = worker.execute_query_task(task).await.expect("query result");
25540        assert_eq!(result.into_json().expect("query projection"), json!(9));
25541    }
25542
25543    #[tokio::test]
25544    async fn query_task_failures_have_stable_reasons() {
25545        let client = Client::new("http://127.0.0.1:8080").expect("client");
25546        let mut worker = Worker::new(client, "rust-workers");
25547        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25548        worker.register_query(
25549            "counter",
25550            "current",
25551            |_ctx, _args| async move { Ok(json!(0)) },
25552        );
25553
25554        let base_task = QueryTask {
25555            query_task_id: "query-errors".to_string(),
25556            query_task_attempt: 1,
25557            lease_owner: None,
25558            workflow_id: Some("counter-errors".to_string()),
25559            run_id: Some("run-errors".to_string()),
25560            workflow_type: "counter".to_string(),
25561            query_name: "missing".to_string(),
25562            payload_codec: DEFAULT_CODEC.to_string(),
25563            workflow_arguments: Some(fixture_envelope(json!([]))),
25564            query_arguments: Some(fixture_envelope(json!([]))),
25565            history_events: Vec::new(),
25566            history_export: None,
25567            run_status: Some("running".to_string()),
25568        };
25569
25570        let unknown = worker
25571            .execute_query_task(base_task.clone())
25572            .await
25573            .expect_err("unknown query");
25574        assert_eq!(unknown.reason, "rejected_unknown_query");
25575
25576        let mut malformed = base_task;
25577        malformed.query_name = "current".to_string();
25578        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
25579        let malformed = worker
25580            .execute_query_task(malformed)
25581            .await
25582            .expect_err("malformed payload");
25583        assert_eq!(malformed.reason, "query_payload_decode_failed");
25584
25585        let client = Client::new("http://127.0.0.1:8080").expect("client");
25586        let mut unavailable_worker = Worker::new(client, "rust-workers");
25587        unavailable_worker
25588            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25589        let empty_arguments = fixture_envelope(json!([]));
25590        let unavailable_task: QueryTask = serde_json::from_value(json!({
25591            "query_task_id": "query-unavailable",
25592            "workflow_type": "counter",
25593            "query_name": "current",
25594            "payload_codec": DEFAULT_CODEC,
25595            "workflow_arguments": empty_arguments.clone(),
25596            "query_arguments": empty_arguments
25597        }))
25598        .expect("query task");
25599        let unavailable = unavailable_worker
25600            .execute_query_task(unavailable_task)
25601            .await
25602            .expect_err("query handler unavailable");
25603        assert_eq!(unavailable.reason, "query_handler_unavailable");
25604    }
25605
25606    #[tokio::test]
25607    async fn client_query_decodes_result_and_typed_failure() {
25608        let server = MockWorkerServer::start();
25609        let client = Client::builder(server.base_url())
25610            .timeout(Duration::from_secs(2))
25611            .build()
25612            .expect("client");
25613
25614        let result = client
25615            .query_workflow("counter-1", "current", json!([]))
25616            .await
25617            .expect("query result");
25618        assert_eq!(result, json!({"count": 8}));
25619
25620        let error = client
25621            .query_workflow("counter-1", "missing", json!([]))
25622            .await
25623            .expect_err("unknown query");
25624        let Error::QueryFailed(failure) = error else {
25625            panic!("expected typed query failure");
25626        };
25627        assert_eq!(failure.status, 404);
25628        assert_eq!(failure.reason, "rejected_unknown_query");
25629    }
25630
25631    #[tokio::test]
25632    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
25633        let server = MockWorkerServer::start();
25634        let client = Client::builder(server.base_url())
25635            .timeout(Duration::from_secs(2))
25636            .build()
25637            .expect("client");
25638        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
25639
25640        client
25641            .start_workflow(
25642                "typed.echo",
25643                "rust-workers",
25644                "typed-start",
25645                arguments.clone(),
25646            )
25647            .await
25648            .expect("typed workflow start");
25649        assert_eq!(
25650            decode_wire_avro_value(
25651                &server.request_body("/api/workflows")["input"],
25652                DEFAULT_CODEC,
25653            )
25654            .expect("typed start input"),
25655            arguments
25656        );
25657
25658        client
25659            .signal_workflow("typed-1", "changed", arguments.clone())
25660            .await
25661            .expect("typed signal");
25662        assert_eq!(
25663            decode_wire_avro_value(
25664                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
25665                DEFAULT_CODEC,
25666            )
25667            .expect("typed signal input"),
25668            arguments
25669        );
25670
25671        assert_eq!(
25672            client
25673                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
25674                .await
25675                .expect("typed query"),
25676            typed_fidelity_probe()
25677        );
25678        assert_eq!(
25679            decode_wire_avro_value(
25680                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
25681                DEFAULT_CODEC,
25682            )
25683            .expect("typed query input"),
25684            arguments
25685        );
25686
25687        assert_eq!(
25688            client
25689                .update_workflow_avro_value(
25690                    "typed-1",
25691                    "replace",
25692                    arguments.clone(),
25693                    Some("typed-request"),
25694                )
25695                .await
25696                .expect("typed update"),
25697            typed_fidelity_probe()
25698        );
25699        let update = server.request_body("/api/workflows/typed-1/update/replace");
25700        assert_eq!(update["request_id"], "typed-request");
25701        assert_eq!(
25702            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
25703            arguments
25704        );
25705
25706        let handle = WorkflowHandle {
25707            client: client.clone(),
25708            workflow_id: "typed-1".to_string(),
25709            run_id: Some("run-typed-1".to_string()),
25710            workflow_type: "typed.echo".to_string(),
25711        };
25712        assert_eq!(
25713            handle
25714                .result_avro_value(WorkflowResultOptions::default())
25715                .await
25716                .expect("typed workflow result"),
25717            typed_fidelity_probe()
25718        );
25719
25720        client
25721            .complete_activity_task(
25722                "activity-typed",
25723                "attempt-typed",
25724                "rust-worker",
25725                typed_fidelity_probe(),
25726                DEFAULT_CODEC,
25727            )
25728            .await
25729            .expect("typed activity completion");
25730        assert_eq!(
25731            decode_wire_avro_value(
25732                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
25733                    ["result"],
25734                DEFAULT_CODEC,
25735            )
25736            .expect("typed activity result"),
25737            typed_fidelity_probe()
25738        );
25739        client
25740            .fail_activity_task(
25741                "activity-typed",
25742                "attempt-typed",
25743                "rust-worker",
25744                "typed failure",
25745                true,
25746            )
25747            .await
25748            .expect("activity failure");
25749    }
25750
25751    #[tokio::test]
25752    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
25753        let server = MockWorkerServer::start();
25754        let client = Client::builder(server.base_url())
25755            .timeout(Duration::from_secs(2))
25756            .build()
25757            .expect("client");
25758
25759        let options = WorkflowCommandOptions::new()
25760            .reason("cleanup requested")
25761            .request_id("cancel-17");
25762        let cancelled = client
25763            .cancel_workflow("wf-lifecycle", options)
25764            .await
25765            .expect("instance cancellation");
25766        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
25767        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
25768        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
25769        assert_eq!(
25770            server.request_body("/api/workflows/wf-lifecycle/cancel"),
25771            json!({"reason":"cleanup requested","request_id":"cancel-17"})
25772        );
25773
25774        let terminated = client
25775            .terminate_workflow(
25776                "wf-lifecycle",
25777                WorkflowCommandOptions::new().reason("forced stop"),
25778            )
25779            .await
25780            .expect("instance termination");
25781        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
25782        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
25783
25784        client
25785            .cancel_workflow_run(
25786                "wf-lifecycle",
25787                "run-current",
25788                WorkflowCommandOptions::default(),
25789            )
25790            .await
25791            .expect("selected run cancellation");
25792        client
25793            .terminate_workflow_run(
25794                "wf-lifecycle",
25795                "run-current",
25796                WorkflowCommandOptions::default(),
25797            )
25798            .await
25799            .expect("selected run termination");
25800
25801        for (command, error) in [
25802            (
25803                WorkflowCommandKind::Cancel,
25804                client
25805                    .cancel_workflow_run(
25806                        "wf-lifecycle",
25807                        "run-stale",
25808                        WorkflowCommandOptions::default(),
25809                    )
25810                    .await
25811                    .expect_err("stale cancellation must be rejected"),
25812            ),
25813            (
25814                WorkflowCommandKind::Terminate,
25815                client
25816                    .terminate_workflow_run(
25817                        "wf-lifecycle",
25818                        "run-stale",
25819                        WorkflowCommandOptions::default(),
25820                    )
25821                    .await
25822                    .expect_err("stale termination must be rejected"),
25823            ),
25824        ] {
25825            let Error::WorkflowCommandRejected(rejection) = error else {
25826                panic!("expected typed command rejection");
25827            };
25828            assert_eq!(rejection.command, command);
25829            assert_eq!(rejection.status, 409);
25830            assert_eq!(rejection.reason, "historical_run_command_rejected");
25831            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
25832            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
25833        }
25834    }
25835
25836    #[tokio::test]
25837    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
25838        let server = MockWorkerServer::start();
25839        let client = Client::builder(server.base_url())
25840            .timeout(Duration::from_secs(2))
25841            .build()
25842            .expect("client");
25843
25844        let result = client
25845            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
25846            .await
25847            .expect("redrive accepted");
25848        assert_eq!(result.workflow_id, "wf-lifecycle");
25849        assert_eq!(result.source_run_id, "run-failed");
25850        assert_eq!(result.run_id, "run-successor");
25851        assert_eq!(result.resume_step_sequence, 2);
25852        assert_eq!(
25853            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
25854            json!({"request_id":"retry-1"})
25855        );
25856
25857        let repeated = client
25858            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
25859            .await
25860            .expect("idempotent redrive response accepted");
25861        assert_eq!(repeated.run_id, "run-successor");
25862
25863        let error = client
25864            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
25865            .await
25866            .expect_err("completed run must be rejected");
25867        let Error::Http { status, body } = error else {
25868            panic!("expected HTTP redrive rejection");
25869        };
25870        assert_eq!(status.as_u16(), 409);
25871        assert!(body.contains("run_not_failed"));
25872        assert_eq!(
25873            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
25874            json!({})
25875        );
25876
25877        let handle = WorkflowHandle {
25878            client: client.clone(),
25879            workflow_id: "wf-lifecycle".to_string(),
25880            run_id: Some("run-failed".to_string()),
25881            workflow_type: "test".to_string(),
25882        };
25883        assert_eq!(
25884            handle.redrive(None).await.expect("handle redrive").run_id,
25885            "run-successor"
25886        );
25887        let missing_run = WorkflowHandle {
25888            run_id: None,
25889            ..handle
25890        };
25891        assert!(matches!(
25892            missing_run.redrive(None).await,
25893            Err(Error::Codec(_))
25894        ));
25895    }
25896
25897    #[tokio::test]
25898    async fn workflow_start_options_send_server_enforced_deadlines() {
25899        let server = MockWorkerServer::start();
25900        let client = Client::builder(server.base_url())
25901            .timeout(Duration::from_secs(2))
25902            .build()
25903            .expect("client");
25904
25905        let handle = client
25906            .start_workflow_with_options(
25907                "rust.timeout",
25908                "rust-timeouts",
25909                "wf-start-options",
25910                WorkflowStartOptions::new()
25911                    .execution_timeout_seconds(30)
25912                    .run_timeout_seconds(1),
25913                json!([]),
25914            )
25915            .await
25916            .expect("workflow start");
25917
25918        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
25919        let body = server.request_body("/api/workflows");
25920        assert_eq!(body["execution_timeout_seconds"], 30);
25921        assert_eq!(body["run_timeout_seconds"], 1);
25922
25923        let invalid = client
25924            .start_workflow_with_options(
25925                "rust.timeout",
25926                "rust-timeouts",
25927                "wf-invalid-options",
25928                WorkflowStartOptions::new()
25929                    .execution_timeout_seconds(1)
25930                    .run_timeout_seconds(2),
25931                json!([]),
25932            )
25933            .await
25934            .expect_err("invalid deadline ordering");
25935        assert!(invalid
25936            .to_string()
25937            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
25938    }
25939
25940    #[tokio::test]
25941    async fn workflow_result_returns_each_typed_terminal_outcome() {
25942        let server = MockWorkerServer::start();
25943        let client = Client::builder(server.base_url())
25944            .timeout(Duration::from_secs(2))
25945            .build()
25946            .expect("client");
25947        let options = WorkflowResultOptions {
25948            poll_interval: Duration::ZERO,
25949            timeout: Duration::from_secs(1),
25950        };
25951
25952        let failed = WorkflowHandle {
25953            client: client.clone(),
25954            workflow_id: "wf-failed".to_string(),
25955            run_id: Some("run-failed".to_string()),
25956            workflow_type: "failure".to_string(),
25957        }
25958        .result(options)
25959        .await
25960        .expect_err("failed outcome");
25961        let Error::WorkflowFailed(failure) = failed else {
25962            panic!("expected WorkflowFailed");
25963        };
25964        assert_eq!(failure.workflow_id, "wf-failed");
25965        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
25966        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
25967        assert_eq!(failure.failure_category.as_deref(), Some("application"));
25968        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
25969        assert_eq!(
25970            failure.exception_class.as_deref(),
25971            Some("billing::PaymentError")
25972        );
25973        assert_eq!(failure.non_retryable, Some(true));
25974
25975        for (workflow_id, expected_kind, expected_reason) in [
25976            (
25977                "wf-cancelled",
25978                WorkflowTerminalKind::Cancelled,
25979                "cleanup requested",
25980            ),
25981            (
25982                "wf-terminated",
25983                WorkflowTerminalKind::Terminated,
25984                "forced stop",
25985            ),
25986            (
25987                "wf-timed-out",
25988                WorkflowTerminalKind::TimedOut,
25989                "run_timeout",
25990            ),
25991        ] {
25992            let error = WorkflowHandle {
25993                client: client.clone(),
25994                workflow_id: workflow_id.to_string(),
25995                run_id: None,
25996                workflow_type: "terminal".to_string(),
25997            }
25998            .result(options)
25999            .await
26000            .expect_err("typed terminal outcome");
26001            let outcome = match error {
26002                Error::WorkflowCancelled(outcome) => outcome,
26003                Error::WorkflowTerminated(outcome) => outcome,
26004                Error::WorkflowTimedOut(outcome) => outcome,
26005                other => panic!("unexpected terminal error: {other}"),
26006            };
26007            assert_eq!(outcome.kind, expected_kind);
26008            assert_eq!(outcome.workflow_id, workflow_id);
26009            assert_eq!(outcome.reason, expected_reason);
26010        }
26011
26012        let wait_timeout = WorkflowHandle {
26013            client,
26014            workflow_id: "wf-waiting".to_string(),
26015            run_id: Some("run-waiting".to_string()),
26016            workflow_type: "waiting".to_string(),
26017        }
26018        .result(WorkflowResultOptions {
26019            poll_interval: Duration::ZERO,
26020            timeout: Duration::ZERO,
26021        })
26022        .await
26023        .expect_err("client wait timeout");
26024        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
26025            panic!("expected typed client timeout");
26026        };
26027        assert_eq!(timeout.reason, "result_wait_timeout");
26028        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
26029        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
26030    }
26031
26032    #[tokio::test]
26033    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
26034        let server = MockWorkerServer::start();
26035        let client = Client::builder(server.base_url())
26036            .timeout(Duration::from_secs(2))
26037            .build()
26038            .expect("client");
26039
26040        let handle = WorkflowHandle {
26041            client,
26042            workflow_id: "wf-selected".to_string(),
26043            run_id: Some("run-selected".to_string()),
26044            workflow_type: "selected".to_string(),
26045        };
26046        let options = WorkflowResultOptions {
26047            poll_interval: Duration::ZERO,
26048            timeout: Duration::from_secs(1),
26049        };
26050
26051        let current = handle
26052            .result(options)
26053            .await
26054            .expect("instance result follows the current run");
26055        assert_eq!(current, json!("current run output"));
26056
26057        let error = handle
26058            .result_selected_run(options)
26059            .await
26060            .expect_err("the selected run is cancelled even though the current run completed");
26061
26062        let Error::WorkflowCancelled(outcome) = error else {
26063            panic!("expected selected run cancellation");
26064        };
26065        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
26066        assert_eq!(outcome.reason, "selected run cancelled");
26067        assert_eq!(
26068            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
26069            1
26070        );
26071        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
26072    }
26073
26074    #[tokio::test]
26075    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
26076        let server = MockWorkerServer::draining_polls();
26077        let client = Client::builder(server.base_url())
26078            .timeout(Duration::from_secs(2))
26079            .build()
26080            .expect("client");
26081
26082        let workflow = client
26083            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
26084            .await
26085            .expect("workflow drain response");
26086        let activity = client
26087            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
26088            .await
26089            .expect("activity drain response");
26090        let query = client
26091            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
26092            .await
26093            .expect("query drain response");
26094
26095        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
26096            assert_eq!(
26097                outcome,
26098                WorkerPollOutcome::Stop {
26099                    poll_status: Some("draining".to_string()),
26100                    reason: Some("worker_draining".to_string()),
26101                }
26102            );
26103        }
26104
26105        assert!(client
26106            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
26107            .await
26108            .expect("compatibility poll")
26109            .is_none());
26110    }
26111
26112    #[tokio::test]
26113    async fn managed_worker_honors_drain_stop_for_every_task_family() {
26114        let server = MockWorkerServer::draining_polls();
26115        let client = Client::builder(server.base_url())
26116            .timeout(Duration::from_secs(2))
26117            .build()
26118            .expect("client");
26119
26120        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
26121            .worker_id("draining-workflow-worker")
26122            .poll_timeout(Duration::ZERO);
26123        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
26124        workflow_worker
26125            .run()
26126            .await
26127            .expect("workflow drain is a clean stop");
26128
26129        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
26130            .worker_id("draining-activity-worker")
26131            .poll_timeout(Duration::ZERO);
26132        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
26133        activity_worker
26134            .run()
26135            .await
26136            .expect("activity drain is a clean stop");
26137
26138        let mut query_worker = Worker::new(client, "rust-workers")
26139            .worker_id("draining-query-worker")
26140            .poll_timeout(Duration::ZERO);
26141        query_worker.register_query("counter", "current", |_ctx, _args| async {
26142            Ok(Value::Null)
26143        });
26144        query_worker
26145            .run()
26146            .await
26147            .expect("query drain is a clean stop");
26148    }
26149
26150    #[tokio::test]
26151    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
26152        let server = MockWorkerServer::start();
26153        let client = Client::builder(server.base_url())
26154            .timeout(Duration::from_secs(2))
26155            .build()
26156            .expect("client");
26157
26158        let details: Value = serde_json::from_str(include_str!(
26159            "../tests/fixtures/activity-heartbeat-progress.json"
26160        ))
26161        .expect("heartbeat progress fixture");
26162        // Every individual field fits Server's progress contract, while the
26163        // obsolete encoded envelope exceeded its 191-character string limit.
26164        assert!(
26165            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
26166                .unwrap()["blob"]
26167                .as_str()
26168                .unwrap()
26169                .len()
26170                > 191
26171        );
26172        let heartbeat = client
26173            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
26174            .await
26175            .expect("cancellation heartbeat");
26176        assert!(heartbeat.cancel_requested);
26177        assert!(heartbeat.should_stop());
26178        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
26179        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
26180        let heartbeat_body =
26181            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
26182        assert_eq!(heartbeat_body["details"], details);
26183        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
26184        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
26185
26186        let error = client
26187            .complete_activity_task(
26188                "activity-cancel",
26189                "attempt-cancel",
26190                "rust-worker",
26191                json!({"late":true}),
26192                DEFAULT_CODEC,
26193            )
26194            .await
26195            .expect_err("late completion must be refused");
26196        assert!(activity_task_rejection_is_final(&error));
26197        let Error::ActivityTaskRejected(rejection) = error else {
26198            panic!("expected typed activity rejection");
26199        };
26200        assert_eq!(rejection.status, 409);
26201        assert_eq!(rejection.reason, "run_cancelled");
26202        assert!(rejection.cancel_requested);
26203        assert_eq!(rejection.can_continue, Some(false));
26204    }
26205
26206    #[tokio::test]
26207    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
26208        let server = MockWorkerServer::cancelled_activity();
26209        let client = Client::builder(server.base_url())
26210            .timeout(Duration::from_secs(2))
26211            .build()
26212            .expect("client");
26213        let cancellation_observed = Arc::new(AtomicBool::new(false));
26214        let observed = Arc::clone(&cancellation_observed);
26215        let mut worker = Worker::new(client.clone(), "rust-workers")
26216            .worker_id("rust-cancel-worker")
26217            .poll_timeout(Duration::from_millis(10));
26218        worker.register_activity("cancel-aware", move |ctx, _args| {
26219            let observed = Arc::clone(&observed);
26220            async move {
26221                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
26222                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
26223                Ok(json!({"late":"completion"}))
26224            }
26225        });
26226
26227        assert_eq!(
26228            worker.run_once().await.expect("cancelled attempt handled"),
26229            1
26230        );
26231        assert!(cancellation_observed.load(Ordering::SeqCst));
26232        assert_eq!(
26233            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
26234            1
26235        );
26236
26237        let mut restarted = Worker::new(client, "rust-workers")
26238            .worker_id("rust-cancel-worker-restarted")
26239            .poll_timeout(Duration::from_millis(10));
26240        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
26241        assert_eq!(
26242            restarted
26243                .run_once()
26244                .await
26245                .expect("replacement worker continues polling"),
26246            0
26247        );
26248    }
26249
26250    #[tokio::test]
26251    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
26252        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"}"#;
26253        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
26254        let client = Client::builder(server.base_url())
26255            .timeout(Duration::from_secs(2))
26256            .build()
26257            .expect("client");
26258
26259        let direct_error = client
26260            .complete_workflow_task(
26261                "workflow-timeout-task",
26262                "timeout-worker",
26263                3,
26264                vec![json!({
26265                    "type": "complete_workflow",
26266                    "result": fixture_envelope(Value::Null)
26267                })],
26268            )
26269            .await
26270            .expect_err("the low-level client preserves the completion rejection");
26271        let Error::Http { status, body } = direct_error else {
26272            panic!("expected the original HTTP completion rejection");
26273        };
26274        assert_eq!(status, reqwest::StatusCode::CONFLICT);
26275        assert_eq!(
26276            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
26277            "run_timed_out"
26278        );
26279
26280        let mut worker = Worker::new(client, "rust-workers")
26281            .worker_id("timeout-worker")
26282            .poll_timeout(Duration::from_millis(10));
26283        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26284            Ok(json!({"late": "result"}))
26285        });
26286
26287        assert_eq!(
26288            worker
26289                .run_once()
26290                .await
26291                .expect("authoritative selected-run timeout settles the tick"),
26292            1
26293        );
26294        assert_eq!(
26295            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
26296            2,
26297            "both the direct client proof and managed worker must see the rejection"
26298        );
26299    }
26300
26301    #[tokio::test]
26302    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
26303        for (name, status, response) in [
26304            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
26305            (
26306                "command was recorded",
26307                "409 Conflict",
26308                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26309            ),
26310            (
26311                "lease conflict",
26312                "409 Conflict",
26313                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
26314            ),
26315            (
26316                "nonterminal run",
26317                "409 Conflict",
26318                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
26319            ),
26320            (
26321                "different selected run",
26322                "409 Conflict",
26323                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"}"#,
26324            ),
26325            (
26326                "different task attempt",
26327                "409 Conflict",
26328                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26329            ),
26330            (
26331                "authentication failure",
26332                "401 Unauthorized",
26333                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26334            ),
26335            (
26336                "authorization failure",
26337                "403 Forbidden",
26338                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26339            ),
26340            (
26341                "protocol failure",
26342                "400 Bad Request",
26343                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
26344            ),
26345            (
26346                "malformed command",
26347                "422 Unprocessable Entity",
26348                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26349            ),
26350            (
26351                "transient server failure",
26352                "503 Service Unavailable",
26353                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26354            ),
26355        ] {
26356            let server = MockWorkerServer::workflow_completion(status, response);
26357            let client = Client::builder(server.base_url())
26358                .timeout(Duration::from_secs(2))
26359                .build()
26360                .expect("client");
26361            let mut worker = Worker::new(client, "rust-workers")
26362                .worker_id("timeout-worker")
26363                .poll_timeout(Duration::from_millis(10));
26364            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26365                Ok(json!({"late": "result"}))
26366            });
26367
26368            let error = worker
26369                .run_once()
26370                .await
26371                .expect_err(&format!("{name} must remain an error"));
26372            assert!(
26373                matches!(error, Error::Http { .. } | Error::Protocol(_)),
26374                "{name} returned an unexpected error variant: {error}"
26375            );
26376        }
26377    }
26378
26379    #[tokio::test]
26380    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
26381        let server = MockWorkerServer::start();
26382        let client = Client::builder(server.base_url())
26383            .worker_token(Some("worker-secret".to_string()))
26384            .namespace("orders")
26385            .timeout(Duration::from_secs(2))
26386            .build()
26387            .expect("client");
26388        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
26389
26390        let result = client
26391            .deregister_worker_registration("worker/α space")
26392            .await
26393            .expect("deregister worker registration");
26394
26395        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
26396        assert_eq!(
26397            server.worker_protocol_for(path).as_deref(),
26398            Some(WORKER_PROTOCOL_VERSION)
26399        );
26400        assert_eq!(server.control_protocol_for(path), None);
26401        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
26402        assert_eq!(
26403            server.authorization_for(path).as_deref(),
26404            Some("Bearer worker-secret")
26405        );
26406        assert_eq!(
26407            result,
26408            WorkerDeregistrationEnvelope {
26409                worker_id: "deregistered-worker".to_string(),
26410                outcome: "deregistered".to_string(),
26411                recovered_workflow_task_count: 2,
26412            }
26413        );
26414    }
26415
26416    #[tokio::test]
26417    async fn low_level_registration_rejects_update_validators_before_transport() {
26418        let server = MockWorkerServer::start();
26419        let client = Client::builder(server.base_url())
26420            .timeout(Duration::from_secs(2))
26421            .build()
26422            .expect("client");
26423
26424        for update_validators in [json!(["approve"]), json!("approve")] {
26425            let error = client
26426                .register_worker_with_command_contracts(
26427                    "validator-claiming-worker",
26428                    "rust-workers",
26429                    vec!["orders".to_string()],
26430                    vec![],
26431                    1,
26432                    1,
26433                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
26434                    json!({
26435                        "orders": {
26436                            "queries": ["current"],
26437                            "updates": ["approve"],
26438                            "update_validators": update_validators,
26439                        },
26440                    }),
26441                )
26442                .await
26443                .expect_err("unsupported validator claims must fail before registration");
26444
26445            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
26446                panic!("expected typed unsupported-validator failure");
26447            };
26448            assert_eq!(workflow_type, "orders");
26449        }
26450        assert_eq!(server.request_count("/api/worker/register"), 0);
26451    }
26452
26453    #[tokio::test]
26454    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
26455        let server = MockWorkerServer::start();
26456        let client = Client::builder(server.base_url())
26457            .timeout(Duration::from_secs(2))
26458            .build()
26459            .expect("client");
26460        let mut worker = Worker::new(client, "rust-workers");
26461        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
26462        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
26463        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
26464        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
26465        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
26466        worker
26467            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
26468            .expect("declare workflow signals");
26469
26470        worker.register().await.expect("register handler contracts");
26471
26472        let declaration =
26473            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
26474        let expected_contracts = json!([
26475            {
26476                "name": "a-avro",
26477                "parameters": [{
26478                    "name": "args", "position": 0, "required": false,
26479                    "variadic": true, "type": null, "allows_null": true,
26480                    "default_available": false, "default": null,
26481                }],
26482            },
26483            {
26484                "name": "z-json",
26485                "parameters": [{
26486                    "name": "args", "position": 0, "required": false,
26487                    "variadic": true, "type": null, "allows_null": true,
26488                    "default_available": false, "default": null,
26489                }],
26490            },
26491        ]);
26492        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
26493        assert_eq!(declaration["query_contracts"], expected_contracts);
26494        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
26495        assert_eq!(declaration["update_contracts"], expected_contracts);
26496        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
26497        assert_eq!(declaration["signal_contracts"], expected_contracts);
26498        assert_eq!(declaration["update_validators"], json!([]));
26499    }
26500
26501    #[tokio::test]
26502    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
26503        let server = MockWorkerServer::start();
26504        let client = Client::new(server.base_url()).expect("client");
26505        let mut worker = Worker::new(client, "rust-workers");
26506        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
26507        assert!(worker
26508            .declare_workflow_signals("missing", &["finish"])
26509            .is_err());
26510        worker
26511            .declare_workflow_signals("orders", &["finish"])
26512            .unwrap();
26513        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
26514            assert!(worker.declare_workflow_signals("orders", names).is_err());
26515        }
26516        worker.register().await.unwrap();
26517        assert_eq!(
26518            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
26519                ["signals"],
26520            json!(["finish"])
26521        );
26522        worker.declare_workflow_signals("orders", &[]).unwrap();
26523        worker.register().await.unwrap();
26524        let registrations = server.request_bodies("/api/worker/register");
26525        assert_eq!(
26526            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
26527            json!([])
26528        );
26529        assert_eq!(
26530            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
26531            json!([])
26532        );
26533    }
26534
26535    #[tokio::test]
26536    async fn low_level_registration_preserves_query_and_update_contracts() {
26537        let server = MockWorkerServer::start();
26538        let client = Client::builder(server.base_url())
26539            .timeout(Duration::from_secs(2))
26540            .build()
26541            .expect("client");
26542        let contracts = json!({
26543            "orders": {
26544                "queries": ["current"],
26545                "updates": ["approve"],
26546                "update_validators": [],
26547            },
26548            "payments": {
26549                "queries": ["status"],
26550                "updates": ["capture"],
26551            },
26552        });
26553
26554        client
26555            .register_worker_with_command_contracts(
26556                "command-worker",
26557                "rust-workers",
26558                vec!["orders".to_string(), "payments".to_string()],
26559                vec![],
26560                1,
26561                1,
26562                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
26563                contracts.clone(),
26564            )
26565            .await
26566            .expect("query and update contracts must remain supported");
26567
26568        assert_eq!(
26569            server.request_body("/api/worker/register")["workflow_command_contracts"],
26570            contracts
26571        );
26572        assert!(server
26573            .request_body("/api/worker/register")
26574            .get("workflow_definition_fingerprints")
26575            .is_none());
26576    }
26577
26578    #[tokio::test]
26579    async fn rust_worker_advertises_source_backed_definition_and_clears_it_on_reregistration() {
26580        let server = MockWorkerServer::start();
26581        let client = Client::builder(server.base_url())
26582            .timeout(Duration::from_secs(2))
26583            .build()
26584            .expect("client");
26585        let mut worker = Worker::new(client, "rust-workers");
26586        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
26587
26588        assert!(worker
26589            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
26590            .is_err());
26591        assert!(worker
26592            .set_workflow_definition_sources("orders", &[])
26593            .is_err());
26594        worker
26595            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
26596            .expect("embed workflow source");
26597        worker.register().await.expect("register worker");
26598        let first = server.request_bodies("/api/worker/register")[0]
26599            ["workflow_definition_fingerprints"]["orders"]
26600            .as_str()
26601            .expect("source-backed fingerprint")
26602            .to_string();
26603        assert!(first.starts_with("sha256:"));
26604
26605        worker
26606            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
26607            .expect("change embedded helper source");
26608        worker.register().await.expect("register changed source");
26609        let changed = server.request_bodies("/api/worker/register")[1]
26610            ["workflow_definition_fingerprints"]["orders"]
26611            .as_str()
26612            .expect("changed fingerprint")
26613            .to_string();
26614        assert_ne!(first, changed);
26615
26616        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
26617        worker
26618            .register()
26619            .await
26620            .expect("register replacement handler");
26621        assert_eq!(
26622            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
26623            json!({})
26624        );
26625    }
26626
26627    #[tokio::test]
26628    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
26629        let server = MockWorkerServer::start();
26630        let control_only = Client::builder(server.base_url())
26631            .control_token(Some("control-secret".to_string()))
26632            .build()
26633            .expect("control client");
26634
26635        let error = control_only
26636            .register_worker("worker", "queue", vec![], vec![], 1, 1)
26637            .await
26638            .expect_err("control token must not authorize a worker request");
26639        assert!(matches!(
26640            error,
26641            Error::MissingRoleCredentials { role: "worker", .. }
26642        ));
26643        assert_eq!(server.request_count("/api/worker/register"), 0);
26644
26645        let worker_only = Client::builder(server.base_url())
26646            .worker_token(Some("worker-secret".to_string()))
26647            .build()
26648            .expect("worker client");
26649        let error = worker_only
26650            .health()
26651            .await
26652            .expect_err("worker token must not authorize a control request");
26653        assert!(matches!(
26654            error,
26655            Error::MissingRoleCredentials {
26656                role: "control",
26657                ..
26658            }
26659        ));
26660        assert_eq!(server.request_count("/api/health"), 0);
26661    }
26662
26663    #[tokio::test]
26664    async fn shared_token_supports_worker_and_control_planes() {
26665        let server = MockWorkerServer::start();
26666        let client = Client::builder(server.base_url())
26667            .token(Some("shared-secret".to_string()))
26668            .build()
26669            .expect("client");
26670
26671        client.health().await.expect("control request");
26672        client
26673            .register_worker("worker", "queue", vec![], vec![], 1, 1)
26674            .await
26675            .expect("worker request");
26676
26677        assert_eq!(
26678            server.authorization_for("/api/health").as_deref(),
26679            Some("Bearer shared-secret")
26680        );
26681        assert_eq!(
26682            server.control_protocol_for("/api/health").as_deref(),
26683            Some(CONTROL_PLANE_VERSION)
26684        );
26685        assert_eq!(
26686            server.authorization_for("/api/worker/register").as_deref(),
26687            Some("Bearer shared-secret")
26688        );
26689        assert_eq!(
26690            server
26691                .worker_protocol_for("/api/worker/register")
26692                .as_deref(),
26693            Some(WORKER_PROTOCOL_VERSION)
26694        );
26695    }
26696
26697    #[tokio::test]
26698    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
26699        let server = MockWorkerServer::start();
26700        let client = Client::builder(server.base_url())
26701            .timeout(Duration::from_secs(2))
26702            .build()
26703            .expect("client");
26704
26705        client
26706            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
26707            .await
26708            .expect("register");
26709        client
26710            .heartbeat_worker("capture-worker", 1, 1)
26711            .await
26712            .expect("heartbeat");
26713        client
26714            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
26715            .await
26716            .expect("workflow poll");
26717        client
26718            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
26719            .await
26720            .expect("activity poll");
26721
26722        for path in [
26723            "/api/worker/register",
26724            "/api/worker/heartbeat",
26725            "/api/worker/workflow-tasks/poll",
26726            "/api/worker/activity-tasks/poll",
26727        ] {
26728            assert_eq!(
26729                server.worker_protocol_for(path).as_deref(),
26730                Some(WORKER_PROTOCOL_VERSION),
26731                "unexpected protocol for {path}"
26732            );
26733        }
26734
26735        assert_eq!(
26736            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
26737            1
26738        );
26739        assert_eq!(
26740            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
26741            500
26742        );
26743        assert_eq!(
26744            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
26745            1
26746        );
26747        assert!(
26748            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
26749                .as_str()
26750                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
26751        );
26752        assert!(
26753            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
26754                .as_str()
26755                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
26756        );
26757    }
26758
26759    #[tokio::test]
26760    async fn query_task_endpoints_send_the_query_feature_protocol() {
26761        let server = MockWorkerServer::start();
26762        let client = Client::builder(server.base_url())
26763            .timeout(Duration::from_secs(2))
26764            .build()
26765            .expect("client");
26766
26767        client
26768            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26769            .await
26770            .expect("query poll");
26771        client
26772            .complete_query_task(
26773                "query-capture",
26774                "capture-worker",
26775                1,
26776                json!(8),
26777                DEFAULT_CODEC,
26778            )
26779            .await
26780            .expect("query complete");
26781        client
26782            .fail_query_task(
26783                "query-capture",
26784                "capture-worker",
26785                1,
26786                "failed",
26787                "query_rejected",
26788                "QueryFailed",
26789            )
26790            .await
26791            .expect("query fail");
26792
26793        for path in [
26794            "/api/worker/query-tasks/poll",
26795            "/api/worker/query-tasks/query-capture/complete",
26796            "/api/worker/query-tasks/query-capture/fail",
26797        ] {
26798            assert_eq!(
26799                server.worker_protocol_for(path).as_deref(),
26800                Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
26801                "unexpected protocol for {path}"
26802            );
26803        }
26804
26805        assert_eq!(
26806            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
26807            1
26808        );
26809        assert!(
26810            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
26811                .as_str()
26812                .is_some_and(|id| id.starts_with("rust-query-poll-"))
26813        );
26814    }
26815
26816    #[tokio::test]
26817    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
26818        let server = MockWorkerServer::transient_worker_failures();
26819        let client = Client::builder(server.base_url())
26820            .timeout(Duration::from_secs(2))
26821            .build()
26822            .expect("client");
26823
26824        client
26825            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
26826            .await
26827            .expect("workflow poll retry");
26828        client
26829            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
26830            .await
26831            .expect("activity poll retry");
26832        client
26833            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
26834            .await
26835            .expect("query poll retry");
26836
26837        for path in [
26838            "/api/worker/workflow-tasks/poll",
26839            "/api/worker/activity-tasks/poll",
26840            "/api/worker/query-tasks/poll",
26841        ] {
26842            let bodies = server.request_bodies(path);
26843            assert_eq!(bodies.len(), 2, "{path} must be retried once");
26844            assert_eq!(
26845                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
26846                "{path} must preserve the request binding across retry"
26847            );
26848        }
26849    }
26850
26851    #[tokio::test]
26852    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
26853        let server = MockWorkerServer::consecutive_poll_failures(2);
26854        let client = Client::builder(server.base_url())
26855            .timeout(Duration::from_secs(2))
26856            .build()
26857            .expect("client");
26858        let mut worker = Worker::new(client, "capture")
26859            .worker_id("capture-worker")
26860            .poll_timeout(Duration::from_millis(10))
26861            .retry_policy(WorkerRetryPolicy {
26862                max_retries: 2,
26863                initial_backoff: Duration::from_millis(1),
26864                max_backoff: Duration::from_millis(1),
26865            });
26866        worker.register_workflow(
26867            "capture.workflow",
26868            |_ctx, _input| async move { Ok(Value::Null) },
26869        );
26870        worker.register_activity(
26871            "capture.activity",
26872            |_ctx, _input| async move { Ok(Value::Null) },
26873        );
26874        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
26875            Ok(Value::Null)
26876        });
26877
26878        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
26879
26880        for path in [
26881            "/api/worker/workflow-tasks/poll",
26882            "/api/worker/activity-tasks/poll",
26883            "/api/worker/query-tasks/poll",
26884        ] {
26885            let bodies = server.request_bodies(path);
26886            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
26887            assert!(
26888                bodies
26889                    .iter()
26890                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
26891                "{path} must preserve one request binding across every retry"
26892            );
26893        }
26894    }
26895
26896    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
26897        let reason = if unavailable {
26898            "storage_admission_unavailable"
26899        } else {
26900            "storage_pressure"
26901        };
26902        let mut body = json!({
26903            "reason": reason,
26904            "storage_state": if unavailable { "fenced" } else { "draining" },
26905            "retryable": true,
26906            "retry_after_seconds": 1,
26907        });
26908        if !mid_poll {
26909            body["request_admitted"] = json!(false);
26910        }
26911        if let Some(id) = poll_id {
26912            body["task"] = Value::Null;
26913            body["poll_status"] = json!(reason);
26914            body["poll_request_id"] = json!(id);
26915            body["retry_same_poll_request_id"] = json!(true);
26916            body["claim_admitted"] = json!(false);
26917        }
26918        body
26919    }
26920
26921    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
26922        let operation = match path {
26923            "/api/worker/register" => "register_worker",
26924            "/api/worker/heartbeat" => "heartbeat_worker",
26925            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
26926            "/api/worker/activity-tasks/poll" => "poll_activity_task",
26927            "/api/worker/query-tasks/poll" => "poll_query_task",
26928            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
26929            _ => return None,
26930        };
26931        let request: Value = serde_json::from_str(request).ok()?;
26932        let mut response = json!({
26933            "reason": "backend_unavailable",
26934            "operation": operation,
26935            "outcome": "unknown",
26936            "retryable": true,
26937            "retry_after_seconds": 1,
26938            "worker_id": request["worker_id"],
26939            "task_queue": request.get("task_queue"),
26940        });
26941        if path.ends_with("/poll") {
26942            response["task"] = Value::Null;
26943            response["poll_status"] = json!("backend_unavailable");
26944            response["poll_request_id"] = request["poll_request_id"].clone();
26945            response["retry_same_poll_request_id"] = json!(true);
26946        }
26947        Some(response)
26948    }
26949
26950    fn backend_retry_override(
26951        path: &str,
26952        request: &str,
26953        number: usize,
26954    ) -> Option<(&'static str, String)> {
26955        if number > 8 {
26956            return None;
26957        }
26958        Some((
26959            "503 Service Unavailable",
26960            backend_refusal(path, request)?.to_string(),
26961        ))
26962    }
26963
26964    fn backend_unavailable_override(
26965        path: &str,
26966        request: &str,
26967        _number: usize,
26968    ) -> Option<(&'static str, String)> {
26969        Some((
26970            "503 Service Unavailable",
26971            backend_refusal(path, request)?.to_string(),
26972        ))
26973    }
26974
26975    fn storage_worker(server: &MockWorkerServer) -> Worker {
26976        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
26977            .worker_id("storage-worker")
26978            .retry_policy(WorkerRetryPolicy {
26979                max_retries: 1,
26980                initial_backoff: Duration::from_millis(1),
26981                max_backoff: Duration::from_millis(1),
26982            })
26983    }
26984
26985    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
26986        let requests = server.requests.lock().expect("requests");
26987        let bodies: Vec<_> = requests
26988            .iter()
26989            .filter(|request| request.path == path)
26990            .map(|request| &request.body)
26991            .collect();
26992        assert_eq!(bodies.len(), count, "{path}");
26993        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
26994    }
26995
26996    #[test]
26997    fn backend_recovery_requires_the_explicit_worker_contract() {
26998        for (path, operation) in [
26999            ("/worker/register", "register_worker"),
27000            ("/worker/heartbeat", "heartbeat_worker"),
27001            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
27002            ("/worker/activity-tasks/poll", "poll_activity_task"),
27003            ("/worker/query-tasks/poll", "poll_query_task"),
27004            (
27005                "/worker/update-validation-tasks/poll",
27006                "poll_update_validation_task",
27007            ),
27008        ] {
27009            let poll_id = path.ends_with("/poll").then_some("same-poll");
27010            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
27011            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
27012                .expect("worker operation");
27013            assert_eq!(body["operation"], operation);
27014            let error = Error::Http {
27015                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27016                body: body.to_string(),
27017            };
27018            assert_eq!(
27019                worker_backend_unavailable_retry_after(&error, path, poll_id),
27020                Some(Duration::from_secs(1))
27021            );
27022            assert!(!worker_operation_is_retryable(&error));
27023            for (field, value) in [
27024                ("operation", json!("wrong_operation")),
27025                ("outcome", json!("completed")),
27026                ("retryable", json!(false)),
27027                ("retry_after_seconds", json!(0)),
27028                ("worker_id", json!("")),
27029            ] {
27030                let mut invalid = body.clone();
27031                invalid[field] = value;
27032                let error = Error::Http {
27033                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27034                    body: invalid.to_string(),
27035                };
27036                assert!(
27037                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
27038                    "{path}: {field}"
27039                );
27040                assert!(!worker_operation_is_retryable(&error));
27041            }
27042            if let Some(poll_id) = poll_id {
27043                for (field, value) in [
27044                    ("poll_request_id", json!("wrong-poll")),
27045                    ("poll_status", json!("empty")),
27046                    ("task", json!({"task_id":"claimed"})),
27047                    ("retry_same_poll_request_id", json!(false)),
27048                ] {
27049                    let mut invalid = body.clone();
27050                    invalid[field] = value;
27051                    let error = Error::Http {
27052                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27053                        body: invalid.to_string(),
27054                    };
27055                    assert!(
27056                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
27057                            .is_none(),
27058                        "{path}: {field}"
27059                    );
27060                }
27061            }
27062            let error = Error::Http {
27063                status: reqwest::StatusCode::UNAUTHORIZED,
27064                body: body.to_string(),
27065            };
27066            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
27067            assert!(!worker_operation_is_retryable(&error));
27068        }
27069    }
27070
27071    #[tokio::test]
27072    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
27073        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27074            request_override: Some(backend_retry_override),
27075            ..MockWorkerBehavior::default()
27076        });
27077        let mut worker =
27078            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27079        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27080        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
27081        worker.register_query("backend.workflow", "state", |_, _| async {
27082            Ok(Value::Null)
27083        });
27084        worker.register().await.expect("registration recovery");
27085        worker
27086            .client
27087            .heartbeat_worker("storage-worker", 1, 1)
27088            .await
27089            .expect("heartbeat recovery");
27090        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
27091        for path in [
27092            "/api/worker/register",
27093            "/api/worker/heartbeat",
27094            "/api/worker/workflow-tasks/poll",
27095            "/api/worker/activity-tasks/poll",
27096            "/api/worker/query-tasks/poll",
27097        ] {
27098            assert_identical_requests(&server, path, 9);
27099        }
27100    }
27101
27102    #[tokio::test]
27103    async fn backend_recovery_wait_stops_with_worker() {
27104        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27105            request_override: Some(backend_unavailable_override),
27106            ..MockWorkerBehavior::default()
27107        });
27108        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
27109            max_retries: 1,
27110            initial_backoff: Duration::from_secs(2),
27111            max_backoff: Duration::from_secs(2),
27112        });
27113        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27114        let started = tokio::time::Instant::now();
27115        let _ = tokio::time::timeout(
27116            Duration::from_secs(1),
27117            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
27118        )
27119        .await
27120        .expect("shutdown interrupts backend wait");
27121        assert!(started.elapsed() < Duration::from_secs(1));
27122        assert!(server.request_count("/api/worker/register") >= 1);
27123    }
27124
27125    #[test]
27126    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
27127        for unavailable in [false, true] {
27128            for mid_poll in [false, true] {
27129                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
27130                let error = Error::Http {
27131                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27132                    body: body.to_string(),
27133                };
27134                assert_eq!(
27135                    worker_storage_admission_retry_after(&error, Some("same-poll")),
27136                    Some(Duration::from_secs(1))
27137                );
27138                assert!(
27139                    !worker_operation_is_retryable(&error),
27140                    "storage is not a bounded generic retry"
27141                );
27142                for (field, value) in [
27143                    ("poll_request_id", json!("wrong-poll")),
27144                    ("task", json!({"task_id":"claimed"})),
27145                    ("retryable", json!(false)),
27146                    ("retry_after_seconds", json!(0)),
27147                    ("retry_after_seconds", json!(true)),
27148                    ("retry_after_seconds", json!(1.0)),
27149                    ("storage_state", json!("normal")),
27150                    ("poll_status", json!("empty")),
27151                    ("claim_admitted", json!(true)),
27152                    ("retry_same_poll_request_id", json!(false)),
27153                    ("request_admitted", json!(true)),
27154                ] {
27155                    let mut invalid = body.clone();
27156                    invalid[field] = value;
27157                    let error = Error::Http {
27158                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27159                        body: invalid.to_string(),
27160                    };
27161                    assert!(
27162                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
27163                        "{field}"
27164                    );
27165                }
27166            }
27167        }
27168        let body = storage_refusal(None, false, false);
27169        let error = Error::Http {
27170            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27171            body: body.to_string(),
27172        };
27173        assert!(worker_storage_admission_retry_after(&error, None).is_some());
27174        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
27175        let error = Error::Http {
27176            status: reqwest::StatusCode::FORBIDDEN,
27177            body: body.to_string(),
27178        };
27179        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27180        let body = storage_refusal(None, false, true);
27181        let error = Error::Http {
27182            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27183            body: body.to_string(),
27184        };
27185        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27186    }
27187
27188    #[tokio::test]
27189    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
27190        for unavailable in [false, true] {
27191            for mid_poll in [false, true] {
27192                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27193                    poll_failures_per_path: 1,
27194                    storage_refusals: 7,
27195                    storage_path: Some("/poll"),
27196                    storage_unavailable: unavailable,
27197                    storage_mid_poll: mid_poll,
27198                    ..MockWorkerBehavior::default()
27199                });
27200                let mut worker = storage_worker(&server);
27201                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
27202                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
27203                for path in [
27204                    "/api/worker/workflow-tasks/poll",
27205                    "/api/worker/activity-tasks/poll",
27206                    "/api/worker/query-tasks/poll",
27207                ] {
27208                    assert_identical_requests(&server, path, 9);
27209                }
27210            }
27211        }
27212    }
27213
27214    #[tokio::test]
27215    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
27216        struct CountedBody(Arc<AtomicUsize>);
27217        impl Serialize for CountedBody {
27218            fn serialize<S: Serializer>(
27219                &self,
27220                serializer: S,
27221            ) -> std::result::Result<S::Ok, S::Error> {
27222                let count = self.0.fetch_add(1, Ordering::SeqCst);
27223                json!({"serialization":count,"lease_owner":"worker","attempt":7})
27224                    .serialize(serializer)
27225            }
27226        }
27227        for path in [
27228            "/api/worker/register",
27229            "/api/worker/heartbeat",
27230            "/api/worker/workflow-tasks/storage-task/complete",
27231            "/api/worker/workflow-tasks/storage-task/fail",
27232            "/api/worker/activity-tasks/storage-task/complete",
27233            "/api/worker/activity-tasks/storage-task/fail",
27234            "/api/worker/activity-tasks/storage-task/heartbeat",
27235            "/api/worker/query-tasks/storage-task/complete",
27236            "/api/worker/query-tasks/storage-task/fail",
27237        ] {
27238            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27239                storage_refusals: 7,
27240                storage_path: Some(path),
27241                ..MockWorkerBehavior::default()
27242            });
27243            let worker =
27244                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27245            let calls = Arc::new(AtomicUsize::new(0));
27246            let _: Value = worker
27247                .client
27248                .request_json(
27249                    reqwest::Method::POST,
27250                    &path[4..],
27251                    RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
27252                    Some(&CountedBody(Arc::clone(&calls))),
27253                )
27254                .await
27255                .expect("prepared request recovery");
27256            assert_eq!(calls.load(Ordering::SeqCst), 1);
27257            assert_identical_requests(&server, path, 8);
27258        }
27259        for worker_scope in [false, true] {
27260            let path = if worker_scope {
27261                "/api/health"
27262            } else {
27263                "/api/worker/register"
27264            };
27265            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27266                storage_refusals: usize::MAX,
27267                storage_path: Some(path),
27268                ..MockWorkerBehavior::default()
27269            });
27270            let worker = storage_worker(&server);
27271            let client = worker.client.clone();
27272            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
27273            let error = if worker_scope {
27274                worker
27275                    .client
27276                    .health()
27277                    .await
27278                    .expect_err("control plane is not retried")
27279            } else {
27280                client
27281                    .request_json::<Value, Value>(
27282                        reqwest::Method::POST,
27283                        "/worker/register",
27284                        RequestProtocol::Worker(WORKER_PROTOCOL_VERSION),
27285                        Some(&json!({})),
27286                    )
27287                    .await
27288                    .expect_err("direct client is not retried")
27289            };
27290            assert!(worker_storage_admission_body(&error).is_some());
27291            assert_eq!(server.request_count(path), 1);
27292        }
27293    }
27294
27295    #[tokio::test]
27296    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
27297        for fail in [false, true] {
27298            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27299                storage_activity: true,
27300                storage_refusals: 7,
27301                storage_path: Some("/storage-activity/"),
27302                ..MockWorkerBehavior::default()
27303            });
27304            let mut worker = storage_worker(&server);
27305            let calls = Arc::new(AtomicUsize::new(0));
27306            let observed = Arc::clone(&calls);
27307            worker.register_activity("storage.activity", move |ctx, _| {
27308                let calls = Arc::clone(&observed);
27309                async move {
27310                    calls.fetch_add(1, Ordering::SeqCst);
27311                    ctx.heartbeat(json!({"step":2})).await?;
27312                    if fail {
27313                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
27314                    } else {
27315                        Ok(json!({"receipt":true}))
27316                    }
27317                }
27318            });
27319            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
27320            assert_eq!(calls.load(Ordering::SeqCst), 1);
27321            assert_identical_requests(
27322                &server,
27323                "/api/worker/activity-tasks/storage-activity/heartbeat",
27324                8,
27325            );
27326            let suffix = if fail { "fail" } else { "complete" };
27327            assert_identical_requests(
27328                &server,
27329                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
27330                8,
27331            );
27332            let other = if fail { "complete" } else { "fail" };
27333            assert_eq!(
27334                server.request_count(&format!(
27335                    "/api/worker/activity-tasks/storage-activity/{other}"
27336                )),
27337                0
27338            );
27339        }
27340    }
27341
27342    #[tokio::test]
27343    async fn storage_waits_are_interruptible_without_false_activity_failure() {
27344        for path in [
27345            "/api/worker/register",
27346            "/api/worker/heartbeat",
27347            "/api/worker/activity-tasks/poll",
27348            "/api/worker/activity-tasks/storage-activity/heartbeat",
27349            "/api/worker/activity-tasks/storage-activity/complete",
27350        ] {
27351            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27352                storage_activity: true,
27353                storage_refusals: usize::MAX,
27354                storage_path: Some(path),
27355                ..MockWorkerBehavior::default()
27356            });
27357            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
27358            worker.register_activity("storage.activity", |ctx, _| async move {
27359                ctx.heartbeat(json!({"step":2})).await?;
27360                Ok(json!({"receipt":true}))
27361            });
27362            let shutdown = async {
27363                while server.request_count(path) == 0 {
27364                    tokio::time::sleep(Duration::from_millis(1)).await;
27365                }
27366            };
27367            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
27368                .await
27369                .expect("shutdown interrupts admission");
27370            assert!(
27371                result.is_err(),
27372                "a refused operation must not appear acknowledged: {path}, {result:?}"
27373            );
27374            assert_eq!(server.request_count(path), 1);
27375            assert_eq!(
27376                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
27377                0
27378            );
27379            assert_eq!(
27380                server.request_count("/api/worker/registrations/mock-worker"),
27381                usize::from(!path.ends_with("/register"))
27382            );
27383        }
27384    }
27385
27386    #[tokio::test]
27387    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
27388        for fail in [false, true] {
27389            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27390                storage_query: true,
27391                storage_refusals: 7,
27392                storage_path: Some("/storage-query/"),
27393                ..MockWorkerBehavior::default()
27394            });
27395            let mut worker = storage_worker(&server);
27396            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
27397            let calls = Arc::new(AtomicUsize::new(0));
27398            let observed = Arc::clone(&calls);
27399            worker.register_query("storage.workflow", "state", move |_, _| {
27400                let calls = Arc::clone(&observed);
27401                async move {
27402                    calls.fetch_add(1, Ordering::SeqCst);
27403                    if fail {
27404                        Err(Error::WorkerLoop("intentional query failure".to_string()))
27405                    } else {
27406                        Ok(json!({"state":"waiting"}))
27407                    }
27408                }
27409            });
27410            assert_eq!(worker.run_once().await.expect("query settled"), 1);
27411            assert_eq!(calls.load(Ordering::SeqCst), 1);
27412            let suffix = if fail { "fail" } else { "complete" };
27413            assert_identical_requests(
27414                &server,
27415                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
27416                8,
27417            );
27418            let other = if fail { "complete" } else { "fail" };
27419            assert_eq!(
27420                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
27421                0
27422            );
27423        }
27424    }
27425
27426    #[tokio::test]
27427    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
27428        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27429            storage_refusals: 7,
27430            storage_path: Some("/poll"),
27431            unauthorized_polls: true,
27432            ..MockWorkerBehavior::default()
27433        });
27434        let error = storage_worker(&server)
27435            .run_once()
27436            .await
27437            .expect_err("auth remains terminal");
27438        assert!(matches!(
27439            error,
27440            Error::Http {
27441                status: reqwest::StatusCode::UNAUTHORIZED,
27442                ..
27443            }
27444        ));
27445        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
27446
27447        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27448            storage_refusals: 7,
27449            storage_path: Some("/activity-cancel/complete"),
27450            ..MockWorkerBehavior::default()
27451        });
27452        let worker =
27453            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27454        let error = worker
27455            .client
27456            .complete_activity_task(
27457                "activity-cancel",
27458                "attempt-cancel",
27459                "worker",
27460                json!({}),
27461                DEFAULT_CODEC,
27462            )
27463            .await
27464            .expect_err("cancellation remains terminal");
27465        assert!(activity_task_rejection_is_final(&error));
27466        assert_identical_requests(
27467            &server,
27468            "/api/worker/activity-tasks/activity-cancel/complete",
27469            8,
27470        );
27471
27472        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27473            storage_refusals: usize::MAX,
27474            storage_path: Some("/poll"),
27475            storage_wrong_poll_id: true,
27476            ..MockWorkerBehavior::default()
27477        });
27478        assert!(storage_worker(&server).run_once().await.is_err());
27479        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27480    }
27481
27482    #[tokio::test]
27483    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
27484        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27485            storage_refusals: usize::MAX,
27486            storage_path: Some("/poll"),
27487            ..MockWorkerBehavior::default()
27488        });
27489        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
27490        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
27491        let run = tokio::spawn(async move { worker.run().await });
27492        tokio::time::timeout(Duration::from_secs(2), async {
27493            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
27494                tokio::time::sleep(Duration::from_millis(1)).await;
27495            }
27496        })
27497        .await
27498        .expect("poll started");
27499        run.abort();
27500        assert!(run.await.expect_err("cancelled run").is_cancelled());
27501        tokio::time::sleep(Duration::from_millis(250)).await;
27502        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
27503    }
27504
27505    #[tokio::test]
27506    async fn query_protocol_rejection_from_older_server_is_typed() {
27507        let server = MockWorkerServer::reject_query_protocol();
27508        let client = Client::builder(server.base_url())
27509            .timeout(Duration::from_secs(2))
27510            .build()
27511            .expect("client");
27512
27513        let error = client
27514            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27515            .await
27516            .expect_err("server below query protocol floor must reject");
27517        let Error::Protocol(failure) = error else {
27518            panic!("expected typed protocol failure");
27519        };
27520
27521        assert_eq!(failure.status, 400);
27522        assert_eq!(failure.reason, "unsupported_protocol_version");
27523        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
27524        assert_eq!(
27525            failure.requested_version.as_deref(),
27526            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
27527        );
27528        assert_eq!(
27529            server
27530                .worker_protocol_for("/api/worker/query-tasks/poll")
27531                .as_deref(),
27532            Some(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION)
27533        );
27534    }
27535
27536    #[tokio::test]
27537    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
27538        let server = MockWorkerServer::reject_query_protocol();
27539        let client = Client::builder(server.base_url())
27540            .timeout(Duration::from_secs(2))
27541            .build()
27542            .expect("client");
27543        let mut worker = Worker::new(client, "rust-workers")
27544            .worker_id("baseline-worker")
27545            .poll_timeout(Duration::from_millis(10));
27546
27547        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
27548            Ok(Value::Null)
27549        });
27550
27551        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
27552        assert_eq!(
27553            server
27554                .worker_protocol_for("/api/worker/workflow-tasks/poll")
27555                .as_deref(),
27556            Some(WORKER_PROTOCOL_VERSION)
27557        );
27558        assert_eq!(
27559            server.worker_protocol_for("/api/worker/query-tasks/poll"),
27560            None,
27561            "a worker without query handlers must not use the query-task endpoint"
27562        );
27563    }
27564
27565    #[tokio::test]
27566    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
27567        let server = MockWorkerServer::reject_query_completion();
27568        let client = Client::builder(server.base_url())
27569            .timeout(Duration::from_secs(2))
27570            .build()
27571            .expect("client");
27572
27573        let error = client
27574            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
27575            .await
27576            .expect_err("expired completion must be rejected");
27577        let Error::QueryFailed(failure) = error else {
27578            panic!("expected typed query failure");
27579        };
27580        assert_eq!(failure.status, 409);
27581        assert_eq!(failure.reason, "query_task_timed_out");
27582
27583        let mut worker = Worker::new(client, "rust-workers")
27584            .worker_id("late-worker")
27585            .poll_timeout(Duration::from_millis(10));
27586        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27587        worker.register_query(
27588            "counter",
27589            "current",
27590            |_ctx, _args| async move { Ok(json!(8)) },
27591        );
27592
27593        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
27594        assert_eq!(
27595            worker
27596                .run_once()
27597                .await
27598                .expect("worker continues after late completion"),
27599            0
27600        );
27601        assert_eq!(
27602            server.request_count("/api/worker/query-tasks/query-late/complete"),
27603            2
27604        );
27605        assert_eq!(
27606            server.request_count("/api/worker/query-tasks/query-late/fail"),
27607            0,
27608            "a server completion rejection must not be reported as an encoding failure"
27609        );
27610    }
27611
27612    #[tokio::test]
27613    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
27614        let server = MockWorkerServer::start();
27615        let client = Client::builder(server.base_url())
27616            .timeout(Duration::from_secs(2))
27617            .build()
27618            .expect("client");
27619        let mut worker = Worker::new(client, "rust-workers")
27620            .worker_id("joined-worker")
27621            .poll_timeout(Duration::from_millis(10));
27622        worker.register_workflow(
27623            "joined.workflow",
27624            |_ctx, _input| async move { Ok(Value::Null) },
27625        );
27626        worker.register_activity(
27627            "joined.activity",
27628            |_ctx, _input| async move { Ok(Value::Null) },
27629        );
27630        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
27631            Ok(Value::Null)
27632        });
27633
27634        worker
27635            .run_until(tokio::time::sleep(Duration::from_millis(20)))
27636            .await
27637            .expect("normal shutdown");
27638
27639        let deregistration_path = "/api/worker/registrations/mock-worker";
27640        assert_eq!(server.request_count(deregistration_path), 1);
27641        for poll_path in [
27642            "/api/worker/workflow-tasks/poll",
27643            "/api/worker/activity-tasks/poll",
27644            "/api/worker/query-tasks/poll",
27645        ] {
27646            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
27647        }
27648        assert_eq!(
27649            server.captured_paths().last().map(String::as_str),
27650            Some(deregistration_path),
27651            "deregistration must start only after every poller has joined"
27652        );
27653    }
27654
27655    #[tokio::test]
27656    async fn registration_failure_does_not_deregister() {
27657        let server = MockWorkerServer::rejected_registration();
27658        let client = Client::builder(server.base_url())
27659            .timeout(Duration::from_secs(2))
27660            .build()
27661            .expect("client");
27662        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
27663
27664        let error = worker
27665            .run_until(async {})
27666            .await
27667            .expect_err("registration must fail");
27668        assert!(matches!(
27669            error,
27670            Error::Http {
27671                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27672                ..
27673            }
27674        ));
27675        assert!(server
27676            .captured_paths()
27677            .iter()
27678            .all(|path| !path.starts_with("/api/worker/registrations/")));
27679    }
27680
27681    #[tokio::test]
27682    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
27683        let server = MockWorkerServer::rejected_registration_protocol();
27684        let client = Client::builder(server.base_url())
27685            .timeout(Duration::from_secs(2))
27686            .build()
27687            .expect("client");
27688        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
27689
27690        let error = worker
27691            .run_until(async {})
27692            .await
27693            .expect_err("a protocol 1.16 server must reject this worker");
27694        let Error::Protocol(failure) = error else {
27695            panic!("expected typed protocol rejection");
27696        };
27697        assert_eq!(failure.reason, "unsupported_protocol_version");
27698        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
27699        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
27700        assert_eq!(
27701            server
27702                .worker_protocol_for("/api/worker/register")
27703                .as_deref(),
27704            Some(WORKER_PROTOCOL_VERSION)
27705        );
27706    }
27707
27708    #[tokio::test]
27709    async fn declined_registration_does_not_deregister() {
27710        let server = MockWorkerServer::declined_registration();
27711        let client = Client::builder(server.base_url())
27712            .timeout(Duration::from_secs(2))
27713            .build()
27714            .expect("client");
27715        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
27716
27717        let error = worker
27718            .run_until(async {})
27719            .await
27720            .expect_err("declined registration must fail");
27721        assert!(matches!(error, Error::WorkerLoop(_)));
27722        assert!(error.to_string().contains("was not accepted"));
27723        assert!(server
27724            .captured_paths()
27725            .iter()
27726            .all(|path| !path.starts_with("/api/worker/registrations/")));
27727    }
27728
27729    #[tokio::test]
27730    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
27731        let server = MockWorkerServer::rejected_deregistration();
27732        let client = Client::builder(server.base_url())
27733            .timeout(Duration::from_secs(2))
27734            .build()
27735            .expect("client");
27736        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
27737
27738        let error = worker
27739            .run_until(async {})
27740            .await
27741            .expect_err("deregistration must fail");
27742        assert!(matches!(
27743            error,
27744            Error::Http {
27745                status: reqwest::StatusCode::FORBIDDEN,
27746                ..
27747            }
27748        ));
27749        assert_eq!(
27750            server.request_count("/api/worker/registrations/mock-worker"),
27751            1
27752        );
27753    }
27754
27755    #[tokio::test]
27756    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
27757        let server = MockWorkerServer::rejected_deregistration_protocol();
27758        let client = Client::builder(server.base_url())
27759            .timeout(Duration::from_secs(2))
27760            .build()
27761            .expect("client");
27762        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
27763
27764        let error = worker
27765            .run_until(async {})
27766            .await
27767            .expect_err("protocol rejection must fail shutdown");
27768        let Error::Protocol(failure) = error else {
27769            panic!("expected typed protocol failure");
27770        };
27771        assert_eq!(failure.reason, "unsupported_protocol_version");
27772        assert_eq!(
27773            failure.requested_version.as_deref(),
27774            Some(WORKER_PROTOCOL_VERSION)
27775        );
27776        assert_eq!(
27777            server.request_count("/api/worker/registrations/mock-worker"),
27778            1
27779        );
27780    }
27781
27782    #[tokio::test]
27783    async fn primary_poller_error_retains_deregistration_failure_context() {
27784        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
27785        let client = Client::builder(server.base_url())
27786            .timeout(Duration::from_secs(2))
27787            .build()
27788            .expect("client");
27789        let mut worker = Worker::new(client, "rust-workers")
27790            .worker_id("combined-failure")
27791            .poll_timeout(Duration::from_millis(10));
27792        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
27793            Ok(Value::Null)
27794        });
27795
27796        let error = worker
27797            .run()
27798            .await
27799            .expect_err("worker and cleanup must fail");
27800        let summary = error.to_string();
27801        assert!(summary.contains("authentication_failed"));
27802        assert!(summary.contains("worker cannot deregister"));
27803        let Error::WorkerShutdown {
27804            primary,
27805            deregistration,
27806        } = error
27807        else {
27808            panic!("expected combined worker shutdown error");
27809        };
27810        assert!(matches!(
27811            *primary,
27812            Error::Http {
27813                status: reqwest::StatusCode::UNAUTHORIZED,
27814                ..
27815            }
27816        ));
27817        assert!(matches!(
27818            *deregistration,
27819            Error::Http {
27820                status: reqwest::StatusCode::FORBIDDEN,
27821                ..
27822            }
27823        ));
27824        assert_eq!(
27825            server.request_count("/api/worker/registrations/mock-worker"),
27826            1
27827        );
27828    }
27829
27830    #[tokio::test]
27831    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
27832        let server = MockWorkerServer::start();
27833        let client = Client::builder(server.base_url())
27834            .timeout(Duration::from_secs(2))
27835            .build()
27836            .expect("client");
27837        let mut worker = Worker::new(client, "rust-workers")
27838            .worker_id("activity-only-worker")
27839            .poll_timeout(Duration::from_millis(10));
27840
27841        worker.register_activity(
27842            "activity.only",
27843            |_ctx, _args| async move { Ok(Value::Null) },
27844        );
27845
27846        worker.run_until(async {}).await.expect("run worker");
27847    }
27848
27849    #[tokio::test]
27850    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
27851        let server = MockWorkerServer::start();
27852        let client = Client::builder(server.base_url())
27853            .timeout(Duration::from_secs(2))
27854            .build()
27855            .expect("client");
27856        let mut worker = Worker::new(client, "rust-workers")
27857            .worker_id("workflow-only-worker")
27858            .poll_timeout(Duration::from_millis(10));
27859
27860        worker.register_workflow(
27861            "workflow.only",
27862            |_ctx, _input| async move { Ok(Value::Null) },
27863        );
27864
27865        worker.run_until(async {}).await.expect("run worker");
27866    }
27867
27868    #[tokio::test]
27869    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
27870        let server = MockWorkerServer::start();
27871        let client = Client::builder(server.base_url())
27872            .timeout(Duration::from_secs(2))
27873            .build()
27874            .expect("client");
27875        let observations = Arc::new(Mutex::new(Vec::new()));
27876        let observed = Arc::clone(&observations);
27877        let mut worker = Worker::new(client, "rust-workers")
27878            .worker_id("observed-heartbeat-worker")
27879            .poll_timeout(Duration::from_millis(10))
27880            .on_worker_heartbeat(move |observation| {
27881                observed
27882                    .lock()
27883                    .expect("heartbeat observations")
27884                    .push(observation.clone());
27885            });
27886
27887        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
27888            Ok(Value::Null)
27889        });
27890        let acknowledged = Arc::clone(&observations);
27891        worker
27892            .run_until(async move {
27893                tokio::time::timeout(Duration::from_secs(2), async move {
27894                    loop {
27895                        if !acknowledged
27896                            .lock()
27897                            .expect("heartbeat observations")
27898                            .is_empty()
27899                        {
27900                            break;
27901                        }
27902                        tokio::time::sleep(Duration::from_millis(1)).await;
27903                    }
27904                })
27905                .await
27906                .expect("heartbeat acknowledgement within timeout");
27907            })
27908            .await
27909            .expect("run worker");
27910
27911        let observations = observations.lock().expect("heartbeat observations");
27912        let first = observations.first().expect("heartbeat acknowledgement");
27913        assert_eq!(first.worker_id, "observed-heartbeat-worker");
27914        assert_eq!(first.task_queue, "rust-workers");
27915        assert!(first.acknowledged_at_unix_millis > 0);
27916        assert_eq!(first.acknowledgement, json!({}));
27917    }
27918
27919    #[tokio::test]
27920    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
27921        let server = MockWorkerServer::delayed_heartbeat_worker();
27922        let client = Client::builder(server.base_url())
27923            .timeout(Duration::from_secs(3))
27924            .build()
27925            .expect("client");
27926        let observations = Arc::new(Mutex::new(Vec::new()));
27927        let observed = Arc::clone(&observations);
27928        let mut worker = Worker::new(client, "rust-snapshot-workers")
27929            .worker_id("rust-snapshot-worker")
27930            .poll_timeout(Duration::from_millis(10))
27931            .on_worker_heartbeat(move |observation| {
27932                observed
27933                    .lock()
27934                    .expect("heartbeat observations")
27935                    .push(observation.clone());
27936            });
27937
27938        worker.register_workflow("snapshot", |ctx, _input| async move {
27939            ctx.wait_signal("finish").await?;
27940            Ok(json!({"status": "finished"}))
27941        });
27942        worker.register_query("snapshot", "current", |ctx, _args| async move {
27943            Ok(json!(ctx
27944                .signals("increment")
27945                .iter()
27946                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
27947                .sum::<i64>()))
27948        });
27949        worker.register_activity("cancel-aware", |_ctx, _args| async move {
27950            Ok(json!({"late": "completion"}))
27951        });
27952
27953        worker
27954            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
27955            .await
27956            .expect("delayed heartbeat must allow a clean worker shutdown");
27957
27958        let observations = observations.lock().expect("heartbeat observations");
27959        assert!(
27960            observations.len() >= 3,
27961            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
27962        );
27963        assert!(
27964            observations.windows(2).all(|pair| {
27965                pair[1].acknowledged_at_unix_millis
27966                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
27967                    >= 850
27968            }),
27969            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
27970        );
27971        drop(observations);
27972
27973        let heartbeat_times = server.request_times("/api/worker/heartbeat");
27974        let delayed_request_at = *heartbeat_times
27975            .get(1)
27976            .expect("intentionally delayed heartbeat request");
27977        let delay_window_start = delayed_request_at + Duration::from_millis(100);
27978        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
27979        for path in [
27980            "/api/worker/workflow-tasks/poll",
27981            "/api/worker/activity-tasks/poll",
27982            "/api/worker/query-tasks/poll",
27983        ] {
27984            assert!(
27985                server
27986                    .request_times(path)
27987                    .iter()
27988                    .any(|received_at| *received_at >= delay_window_start
27989                        && *received_at <= delay_window_end),
27990                "{path} must keep polling while a heartbeat acknowledgement is delayed"
27991            );
27992        }
27993        assert!(
27994            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
27995            "workflow work must be settled"
27996        );
27997        assert!(
27998            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
27999            "activity work must be settled"
28000        );
28001        assert!(
28002            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
28003            "query work must be settled"
28004        );
28005    }
28006
28007    #[tokio::test]
28008    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
28009        let server = MockWorkerServer::heartbeat_retry_worker();
28010        let client = Client::builder(server.base_url())
28011            .timeout(Duration::from_secs(2))
28012            .build()
28013            .expect("client");
28014        let observations = Arc::new(Mutex::new(Vec::new()));
28015        let observed = Arc::clone(&observations);
28016        let worker = Worker::new(client, "rust-workers")
28017            .worker_id("heartbeat-retry-worker")
28018            .retry_policy(WorkerRetryPolicy {
28019                max_retries: 1,
28020                initial_backoff: Duration::from_millis(300),
28021                max_backoff: Duration::from_millis(300),
28022            })
28023            .on_worker_heartbeat(move |observation| {
28024                observed
28025                    .lock()
28026                    .expect("heartbeat observations")
28027                    .push(observation.clone());
28028            });
28029
28030        worker
28031            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
28032            .await
28033            .expect("retryable heartbeat failure must remain bounded and recover");
28034
28035        let observations = observations.lock().expect("heartbeat observations");
28036        assert!(observations.len() >= 3, "heartbeat retry must recover");
28037        assert!(
28038            observations.windows(2).all(|pair| {
28039                pair[1]
28040                    .acknowledged_at_unix_millis
28041                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28042                    >= 850
28043            }),
28044            "a successful retry must start a fresh advertised cadence: {observations:?}"
28045        );
28046        assert_eq!(
28047            server.request_count("/api/worker/heartbeat"),
28048            observations.len() + 1,
28049            "one retryable failure must add exactly one bounded request"
28050        );
28051    }
28052
28053    #[tokio::test]
28054    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
28055        let server = MockWorkerServer::waiting_query_worker();
28056        let client = Client::builder(server.base_url())
28057            .timeout(Duration::from_secs(2))
28058            .build()
28059            .expect("client");
28060        let observations = Arc::new(Mutex::new(Vec::new()));
28061        let observed = Arc::clone(&observations);
28062        let mut worker = Worker::new(client, "rust-snapshot-workers")
28063            .worker_id("rust-snapshot-worker")
28064            .poll_timeout(Duration::from_millis(10))
28065            .on_worker_heartbeat(move |observation| {
28066                observed
28067                    .lock()
28068                    .expect("heartbeat observations")
28069                    .push(observation.clone());
28070            });
28071
28072        worker.register_workflow("snapshot", |ctx, _input| async move {
28073            ctx.wait_signal("finish").await?;
28074            Ok(json!({"status": "finished"}))
28075        });
28076        worker.register_query("snapshot", "current", |ctx, _args| async move {
28077            let current = ctx
28078                .signals("increment")
28079                .iter()
28080                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28081                .sum::<i64>();
28082            Ok(json!(current))
28083        });
28084        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
28085        worker
28086            .declare_workflow_signals("snapshot", &["finish"])
28087            .expect("declare finish signal");
28088
28089        worker
28090            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
28091            .await
28092            .expect("pending workflow and query poller must remain live until shutdown");
28093
28094        assert!(
28095            observations.lock().expect("heartbeat observations").len() >= 4,
28096            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
28097        );
28098        assert!(
28099            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
28100            "workflow polling must continue after empty replay acknowledgements"
28101        );
28102        assert!(
28103            server.request_count("/api/worker/query-tasks/poll") >= 2,
28104            "query polling must continue after serving the current query"
28105        );
28106        assert_eq!(
28107            server.request_body("/api/worker/register")["capabilities"],
28108            json!([
28109                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
28110                DURABLE_SELECTION_CAPABILITY,
28111                MEMO_UPSERTS_CAPABILITY,
28112                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
28113                QUERY_TASKS_CAPABILITY,
28114                WORKFLOW_UPDATES_CAPABILITY,
28115                MESSAGE_STREAMS_CAPABILITY
28116            ])
28117        );
28118        assert_eq!(
28119            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
28120            json!({
28121                "queries": ["current"],
28122                "query_contracts": [{
28123                    "name": "current",
28124                    "parameters": [{
28125                        "name": "args", "position": 0, "required": false,
28126                        "variadic": true, "type": null, "allows_null": true,
28127                        "default_available": false, "default": null,
28128                    }],
28129                }],
28130                "signals": ["finish"],
28131                "signal_contracts": [{
28132                    "name": "finish",
28133                    "parameters": [{
28134                        "name": "args", "position": 0, "required": false,
28135                        "variadic": true, "type": null, "allows_null": true,
28136                        "default_available": false, "default": null,
28137                    }],
28138                }],
28139                "updates": ["replace"],
28140                "update_contracts": [{
28141                    "name": "replace",
28142                    "parameters": [{
28143                        "name": "args", "position": 0, "required": false,
28144                        "variadic": true, "type": null, "allows_null": true,
28145                        "default_available": false, "default": null,
28146                    }],
28147                }],
28148                "update_validators": [],
28149            })
28150        );
28151
28152        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
28153        assert_eq!(
28154            opened["commands"],
28155            json!([{
28156                "type": "open_signal_wait",
28157                "signal_name": "finish",
28158            }])
28159        );
28160
28161        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
28162            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
28163            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
28164            let failure = server.request_body(&fail_path);
28165            assert_eq!(
28166                failure["failure"]["type"],
28167                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
28168            );
28169            assert_eq!(server.request_count(&completion_path), 0);
28170        }
28171
28172        let query_completion =
28173            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
28174        assert_eq!(query_completion["result"], json!(8));
28175
28176        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
28177        assert_eq!(
28178            server.request_count(terminal_path),
28179            1,
28180            "the matching signal must settle the workflow exactly once"
28181        );
28182        let terminal = server.request_body(terminal_path);
28183        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
28184        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
28185        assert_eq!(
28186            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
28187                .expect("terminal workflow result"),
28188            json!({"status": "finished"})
28189        );
28190    }
28191
28192    #[tokio::test]
28193    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
28194        let server = MockWorkerServer::transient_worker_failures();
28195        let client = Client::builder(server.base_url())
28196            .timeout(Duration::from_secs(2))
28197            .build()
28198            .expect("client");
28199        let mut worker = Worker::new(client, "rust-workers")
28200            .worker_id("retry-worker")
28201            .poll_timeout(Duration::from_millis(10))
28202            .retry_policy(WorkerRetryPolicy {
28203                max_retries: 2,
28204                initial_backoff: Duration::from_millis(1),
28205                max_backoff: Duration::from_millis(1),
28206            });
28207        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28208        worker.register_activity(
28209            "counter.activity",
28210            |_ctx, _input| async move { Ok(Value::Null) },
28211        );
28212        worker.register_query(
28213            "counter",
28214            "current",
28215            |_ctx, _args| async move { Ok(json!(8)) },
28216        );
28217
28218        worker
28219            .run_until(tokio::time::sleep(Duration::from_millis(75)))
28220            .await
28221            .expect("transient failures must not stop the worker");
28222
28223        for path in [
28224            "/api/worker/heartbeat",
28225            "/api/worker/workflow-tasks/poll",
28226            "/api/worker/activity-tasks/poll",
28227            "/api/worker/query-tasks/poll",
28228        ] {
28229            assert!(
28230                server.request_count(path) >= 2,
28231                "{path} must continue after its transient failure"
28232            );
28233        }
28234    }
28235
28236    #[tokio::test]
28237    async fn worker_continues_after_long_poll_capacity_backpressure() {
28238        let server = MockWorkerServer::capacity_limited_activity_poll();
28239        let client = Client::builder(server.base_url())
28240            .timeout(Duration::from_secs(2))
28241            .build()
28242            .expect("client");
28243        let mut worker = Worker::new(client, "rust-workers")
28244            .worker_id("capacity-worker")
28245            .poll_timeout(Duration::from_millis(10))
28246            .retry_policy(WorkerRetryPolicy {
28247                max_retries: 0,
28248                initial_backoff: Duration::from_millis(1),
28249                max_backoff: Duration::from_millis(1),
28250            });
28251        worker.register_activity("capacity.activity", |_ctx, _input| async move {
28252            Ok(json!({"handled": true}))
28253        });
28254
28255        worker
28256            .run_until(tokio::time::sleep(Duration::from_millis(50)))
28257            .await
28258            .expect("capacity backpressure must not stop the worker");
28259
28260        assert!(
28261            server.request_count("/api/worker/activity-tasks/poll") >= 2,
28262            "the activity poller must continue after capacity backpressure"
28263        );
28264        assert_eq!(
28265            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
28266            1,
28267            "the worker must complete work returned after capacity recovers"
28268        );
28269    }
28270
28271    #[test]
28272    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
28273        let capacity = Error::Http {
28274            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28275            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
28276        };
28277        assert_eq!(
28278            worker_poll_capacity_retry_after(&capacity),
28279            Some(Duration::from_secs(3))
28280        );
28281
28282        let rejected_capacity = Error::Http {
28283            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28284            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
28285        };
28286        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
28287        assert!(!worker_operation_is_retryable(&rejected_capacity));
28288
28289        let ordinary_rate_limit = Error::Http {
28290            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28291            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
28292                .to_string(),
28293        };
28294        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
28295        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
28296    }
28297
28298    #[tokio::test]
28299    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
28300        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28301            poll_failures_per_path: 8,
28302            heartbeat_failures: 8,
28303            ..MockWorkerBehavior::default()
28304        });
28305        let client = Client::builder(server.base_url())
28306            .timeout(Duration::from_secs(2))
28307            .build()
28308            .expect("client");
28309        let acknowledgements = Arc::new(AtomicUsize::new(0));
28310        let observed = Arc::clone(&acknowledgements);
28311        let mut worker = Worker::new(client, "rust-workers")
28312            .recover_transient_outages(true)
28313            .poll_timeout(Duration::from_millis(10))
28314            .retry_policy(WorkerRetryPolicy {
28315                max_retries: 2,
28316                initial_backoff: Duration::from_millis(2),
28317                max_backoff: Duration::from_millis(5),
28318            })
28319            .on_worker_heartbeat(move |_| {
28320                observed.fetch_add(1, Ordering::SeqCst);
28321            });
28322        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28323        worker.register_activity(
28324            "counter.activity",
28325            |_ctx, _input| async move { Ok(Value::Null) },
28326        );
28327        worker.register_query("counter", "current", |_ctx, _args| async move {
28328            Ok(Value::Null)
28329        });
28330
28331        worker
28332            .run_until(tokio::time::sleep(Duration::from_millis(500)))
28333            .await
28334            .expect("a recoverable outage must not stop the service worker");
28335
28336        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
28337        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
28338        for path in [
28339            "/api/worker/workflow-tasks/poll",
28340            "/api/worker/activity-tasks/poll",
28341            "/api/worker/query-tasks/poll",
28342        ] {
28343            let bodies = server.request_bodies(path);
28344            assert!(bodies.len() >= 10, "{path} must resume after recovery");
28345            let first = &bodies[0]["poll_request_id"];
28346            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
28347            for body in &bodies[..9] {
28348                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
28349            }
28350            assert_ne!(&bodies[9]["poll_request_id"], first);
28351            let times = server.request_times(path);
28352            for pair in times[..9].windows(2) {
28353                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
28354            }
28355        }
28356    }
28357
28358    #[tokio::test]
28359    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
28360        for heartbeat_outage in [false, true] {
28361            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28362                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
28363                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
28364                ..MockWorkerBehavior::default()
28365            });
28366            let client = Client::builder(server.base_url()).build().expect("client");
28367            let mut worker = Worker::new(client, "rust-workers")
28368                .recover_transient_outages(true)
28369                .retry_policy(WorkerRetryPolicy {
28370                    max_retries: 1,
28371                    initial_backoff: Duration::from_secs(5),
28372                    max_backoff: Duration::from_secs(5),
28373                });
28374            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28375            let started = Instant::now();
28376            worker
28377                .run_until(tokio::time::sleep(Duration::from_millis(200)))
28378                .await
28379                .expect("shutdown during an outage is a normal stop");
28380            assert!(started.elapsed() < Duration::from_secs(1));
28381            let path = if heartbeat_outage {
28382                "/api/worker/heartbeat"
28383            } else {
28384                "/api/worker/workflow-tasks/poll"
28385            };
28386            assert_eq!(server.request_count(path), 1);
28387            assert_eq!(
28388                server.request_count("/api/worker/registrations/mock-worker"),
28389                1
28390            );
28391        }
28392    }
28393
28394    #[tokio::test]
28395    async fn worker_outage_recovery_keeps_run_once_bounded() {
28396        let server = MockWorkerServer::unavailable_polls();
28397        let client = Client::builder(server.base_url()).build().expect("client");
28398        let mut worker = Worker::new(client, "rust-workers")
28399            .recover_transient_outages(true)
28400            .retry_policy(WorkerRetryPolicy {
28401                max_retries: 2,
28402                initial_backoff: Duration::from_millis(1),
28403                max_backoff: Duration::from_millis(1),
28404            });
28405        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28406        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
28407        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
28408    }
28409
28410    #[tokio::test]
28411    async fn worker_outage_recovery_respects_disabled_retries() {
28412        let server = MockWorkerServer::unavailable_polls();
28413        let client = Client::builder(server.base_url()).build().expect("client");
28414        let mut worker = Worker::new(client, "rust-workers")
28415            .recover_transient_outages(true)
28416            .retry_policy(WorkerRetryPolicy {
28417                max_retries: 0,
28418                ..WorkerRetryPolicy::default()
28419            });
28420        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28421        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
28422        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28423    }
28424
28425    #[tokio::test]
28426    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
28427        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28428            heartbeat_failures: usize::MAX,
28429            unauthorized_polls: true,
28430            ..MockWorkerBehavior::default()
28431        });
28432        let client = Client::builder(server.base_url()).build().expect("client");
28433        let mut worker = Worker::new(client, "rust-workers")
28434            .recover_transient_outages(true)
28435            .retry_policy(WorkerRetryPolicy {
28436                max_retries: 1,
28437                initial_backoff: Duration::from_secs(5),
28438                max_backoff: Duration::from_secs(5),
28439            });
28440        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28441        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
28442            .await
28443            .expect("fatal poll errors must interrupt heartbeat recovery")
28444            .expect_err("authentication failure is terminal");
28445        assert!(
28446            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
28447        );
28448        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28449    }
28450
28451    #[tokio::test]
28452    async fn worker_bounds_transport_retries() {
28453        let server = MockWorkerServer::unavailable_polls();
28454        let client = Client::builder(server.base_url())
28455            .timeout(Duration::from_secs(2))
28456            .build()
28457            .expect("client");
28458        let mut worker = Worker::new(client, "rust-workers")
28459            .worker_id("bounded-retry-worker")
28460            .poll_timeout(Duration::from_millis(10))
28461            .retry_policy(WorkerRetryPolicy {
28462                max_retries: 2,
28463                initial_backoff: Duration::from_millis(1),
28464                max_backoff: Duration::from_millis(1),
28465            });
28466        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28467
28468        let error = worker.run().await.expect_err("retry bound must terminate");
28469        assert!(matches!(error, Error::Transport(_)));
28470        assert_eq!(
28471            server.request_count("/api/worker/workflow-tasks/poll"),
28472            3,
28473            "one initial request plus exactly two retries"
28474        );
28475    }
28476
28477    #[tokio::test]
28478    async fn worker_retry_policy_can_disable_poll_retries() {
28479        let server = MockWorkerServer::unavailable_polls();
28480        let client = Client::builder(server.base_url())
28481            .timeout(Duration::from_secs(2))
28482            .build()
28483            .expect("client");
28484        let mut worker = Worker::new(client, "rust-workers")
28485            .worker_id("no-retry-worker")
28486            .poll_timeout(Duration::from_millis(10))
28487            .retry_policy(WorkerRetryPolicy {
28488                max_retries: 0,
28489                initial_backoff: Duration::from_millis(1),
28490                max_backoff: Duration::from_millis(1),
28491            });
28492        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28493
28494        let error = worker
28495            .run_once()
28496            .await
28497            .expect_err("disabled retries must return the first transport failure");
28498        assert!(matches!(error, Error::Transport(_)));
28499        assert_eq!(
28500            server.request_count("/api/worker/workflow-tasks/poll"),
28501            1,
28502            "max_retries=0 must send only the initial request"
28503        );
28504    }
28505
28506    #[tokio::test]
28507    async fn worker_does_not_retry_authentication_failures() {
28508        let server = MockWorkerServer::unauthorized_polls();
28509        let client = Client::builder(server.base_url())
28510            .timeout(Duration::from_secs(2))
28511            .build()
28512            .expect("client");
28513        let mut worker = Worker::new(client, "rust-workers")
28514            .worker_id("unauthorized-worker")
28515            .recover_transient_outages(true)
28516            .poll_timeout(Duration::from_millis(10));
28517        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28518
28519        let error = worker
28520            .run()
28521            .await
28522            .expect_err("authentication must terminate");
28523        let Error::Http { status, body } = error else {
28524            panic!("expected stable HTTP authentication error");
28525        };
28526        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
28527        assert!(body.contains("authentication_failed"));
28528        assert_eq!(
28529            server.request_count("/api/worker/workflow-tasks/poll"),
28530            1,
28531            "authentication failures must not be retried"
28532        );
28533    }
28534
28535    #[derive(Clone, Debug)]
28536    struct CapturedRequest {
28537        headers: String,
28538        method: String,
28539        path: String,
28540        authorization: Option<String>,
28541        namespace: Option<String>,
28542        worker_protocol: Option<String>,
28543        control_protocol: Option<String>,
28544        body: String,
28545        received_at: Instant,
28546    }
28547
28548    struct MockWorkerServer {
28549        addr: SocketAddr,
28550        stop: Arc<AtomicBool>,
28551        requests: Arc<Mutex<Vec<CapturedRequest>>>,
28552        thread: Option<thread::JoinHandle<()>>,
28553    }
28554
28555    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
28556
28557    #[derive(Clone, Copy, Default)]
28558    struct MockWorkerBehavior {
28559        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
28560        request_override: Option<RequestOverride>,
28561        storage_refusals: usize,
28562        storage_path: Option<&'static str>,
28563        storage_unavailable: bool,
28564        storage_mid_poll: bool,
28565        storage_activity: bool,
28566        storage_query: bool,
28567        storage_wrong_poll_id: bool,
28568        reject_query_protocol: bool,
28569        reject_query_completion: bool,
28570        waiting_query_worker: bool,
28571        decline_registration: bool,
28572        complete_named_signal: bool,
28573        poll_failures_per_path: usize,
28574        long_poll_capacity_responses_per_path: usize,
28575        heartbeat_failures: usize,
28576        heartbeat_failure_request: Option<usize>,
28577        delayed_heartbeat_request: Option<usize>,
28578        heartbeat_response_delay: Duration,
28579        concurrent_requests: bool,
28580        unauthorized_polls: bool,
28581        reject_registration: bool,
28582        reject_registration_protocol: bool,
28583        reject_deregistration: bool,
28584        reject_deregistration_protocol: bool,
28585        cancelled_activity: bool,
28586        draining_polls: bool,
28587        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
28588        workflow_completion_status: Option<&'static str>,
28589        workflow_completion_body: Option<&'static str>,
28590    }
28591
28592    impl MockWorkerServer {
28593        fn start() -> Self {
28594            Self::start_with_behavior(MockWorkerBehavior::default())
28595        }
28596
28597        fn reject_query_protocol() -> Self {
28598            Self::start_with_behavior(MockWorkerBehavior {
28599                reject_query_protocol: true,
28600                ..MockWorkerBehavior::default()
28601            })
28602        }
28603
28604        fn reject_query_completion() -> Self {
28605            Self::start_with_behavior(MockWorkerBehavior {
28606                reject_query_completion: true,
28607                ..MockWorkerBehavior::default()
28608            })
28609        }
28610
28611        fn waiting_query_worker() -> Self {
28612            Self::start_with_behavior(MockWorkerBehavior {
28613                waiting_query_worker: true,
28614                complete_named_signal: true,
28615                ..MockWorkerBehavior::default()
28616            })
28617        }
28618
28619        fn transient_worker_failures() -> Self {
28620            Self::start_with_behavior(MockWorkerBehavior {
28621                poll_failures_per_path: 1,
28622                heartbeat_failures: 1,
28623                ..MockWorkerBehavior::default()
28624            })
28625        }
28626
28627        fn consecutive_poll_failures(count: usize) -> Self {
28628            Self::start_with_behavior(MockWorkerBehavior {
28629                poll_failures_per_path: count,
28630                ..MockWorkerBehavior::default()
28631            })
28632        }
28633
28634        fn capacity_limited_activity_poll() -> Self {
28635            Self::start_with_behavior(MockWorkerBehavior {
28636                long_poll_capacity_responses_per_path: 1,
28637                ..MockWorkerBehavior::default()
28638            })
28639        }
28640
28641        fn delayed_heartbeat_worker() -> Self {
28642            Self::start_with_behavior(MockWorkerBehavior {
28643                waiting_query_worker: true,
28644                delayed_heartbeat_request: Some(2),
28645                heartbeat_response_delay: Duration::from_millis(1_500),
28646                concurrent_requests: true,
28647                cancelled_activity: true,
28648                ..MockWorkerBehavior::default()
28649            })
28650        }
28651
28652        fn heartbeat_retry_worker() -> Self {
28653            Self::start_with_behavior(MockWorkerBehavior {
28654                waiting_query_worker: true,
28655                heartbeat_failure_request: Some(2),
28656                concurrent_requests: true,
28657                ..MockWorkerBehavior::default()
28658            })
28659        }
28660
28661        fn unavailable_polls() -> Self {
28662            Self::start_with_behavior(MockWorkerBehavior {
28663                poll_failures_per_path: usize::MAX,
28664                ..MockWorkerBehavior::default()
28665            })
28666        }
28667
28668        fn unauthorized_polls() -> Self {
28669            Self::start_with_behavior(MockWorkerBehavior {
28670                unauthorized_polls: true,
28671                ..MockWorkerBehavior::default()
28672            })
28673        }
28674
28675        fn rejected_registration() -> Self {
28676            Self::start_with_behavior(MockWorkerBehavior {
28677                reject_registration: true,
28678                ..MockWorkerBehavior::default()
28679            })
28680        }
28681
28682        fn rejected_registration_protocol() -> Self {
28683            Self::start_with_behavior(MockWorkerBehavior {
28684                reject_registration_protocol: true,
28685                ..MockWorkerBehavior::default()
28686            })
28687        }
28688
28689        fn declined_registration() -> Self {
28690            Self::start_with_behavior(MockWorkerBehavior {
28691                decline_registration: true,
28692                ..MockWorkerBehavior::default()
28693            })
28694        }
28695
28696        fn rejected_deregistration() -> Self {
28697            Self::start_with_behavior(MockWorkerBehavior {
28698                reject_deregistration: true,
28699                ..MockWorkerBehavior::default()
28700            })
28701        }
28702
28703        fn rejected_deregistration_protocol() -> Self {
28704            Self::start_with_behavior(MockWorkerBehavior {
28705                reject_deregistration_protocol: true,
28706                ..MockWorkerBehavior::default()
28707            })
28708        }
28709
28710        fn unauthorized_polls_and_rejected_deregistration() -> Self {
28711            Self::start_with_behavior(MockWorkerBehavior {
28712                unauthorized_polls: true,
28713                reject_deregistration: true,
28714                ..MockWorkerBehavior::default()
28715            })
28716        }
28717
28718        fn cancelled_activity() -> Self {
28719            Self::start_with_behavior(MockWorkerBehavior {
28720                cancelled_activity: true,
28721                ..MockWorkerBehavior::default()
28722            })
28723        }
28724
28725        fn draining_polls() -> Self {
28726            Self::start_with_behavior(MockWorkerBehavior {
28727                draining_polls: true,
28728                ..MockWorkerBehavior::default()
28729            })
28730        }
28731
28732        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
28733            Self::start_with_behavior(MockWorkerBehavior {
28734                invalid_task_payload_codec: Some(codec),
28735                ..MockWorkerBehavior::default()
28736            })
28737        }
28738
28739        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
28740            Self::start_with_behavior(MockWorkerBehavior {
28741                workflow_completion_status: Some(status),
28742                workflow_completion_body: Some(body),
28743                ..MockWorkerBehavior::default()
28744            })
28745        }
28746
28747        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
28748            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
28749            listener
28750                .set_nonblocking(true)
28751                .expect("configure mock listener");
28752            let addr = listener.local_addr().expect("mock server address");
28753            let stop = Arc::new(AtomicBool::new(false));
28754            let server_stop = Arc::clone(&stop);
28755            let requests = Arc::new(Mutex::new(Vec::new()));
28756            let server_requests = Arc::clone(&requests);
28757            let thread = thread::spawn(move || {
28758                let mut request_threads = Vec::new();
28759                while !server_stop.load(Ordering::SeqCst) {
28760                    match listener.accept() {
28761                        Ok((mut stream, _)) => {
28762                            if behavior.concurrent_requests {
28763                                let requests = Arc::clone(&server_requests);
28764                                request_threads.push(thread::spawn(move || {
28765                                    handle_mock_worker_request(&mut stream, &requests, behavior)
28766                                }));
28767                            } else {
28768                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
28769                            }
28770                        }
28771                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
28772                            let mut index = 0;
28773                            while index < request_threads.len() {
28774                                if request_threads[index].is_finished() {
28775                                    request_threads
28776                                        .swap_remove(index)
28777                                        .join()
28778                                        .expect("join mock request");
28779                                } else {
28780                                    index += 1;
28781                                }
28782                            }
28783                            thread::sleep(Duration::from_millis(5));
28784                        }
28785                        Err(_) => break,
28786                    }
28787                }
28788                for request_thread in request_threads {
28789                    request_thread.join().expect("join mock request");
28790                }
28791            });
28792
28793            Self {
28794                addr,
28795                stop,
28796                requests,
28797                thread: Some(thread),
28798            }
28799        }
28800
28801        fn base_url(&self) -> String {
28802            format!("http://{}", self.addr)
28803        }
28804
28805        fn worker_protocol_for(&self, path: &str) -> Option<String> {
28806            self.requests
28807                .lock()
28808                .expect("captured requests")
28809                .iter()
28810                .find(|request| request.path == path)
28811                .and_then(|request| request.worker_protocol.clone())
28812        }
28813
28814        fn control_protocol_for(&self, path: &str) -> Option<String> {
28815            self.requests
28816                .lock()
28817                .expect("captured requests")
28818                .iter()
28819                .find(|request| request.path == path)
28820                .and_then(|request| request.control_protocol.clone())
28821        }
28822
28823        fn method_for(&self, path: &str) -> Option<String> {
28824            self.requests
28825                .lock()
28826                .expect("captured requests")
28827                .iter()
28828                .find(|request| request.path == path)
28829                .map(|request| request.method.clone())
28830        }
28831
28832        fn authorization_for(&self, path: &str) -> Option<String> {
28833            self.requests
28834                .lock()
28835                .expect("captured requests")
28836                .iter()
28837                .find(|request| request.path == path)
28838                .and_then(|request| request.authorization.clone())
28839        }
28840
28841        fn namespace_for(&self, path: &str) -> Option<String> {
28842            self.requests
28843                .lock()
28844                .expect("captured requests")
28845                .iter()
28846                .find(|request| request.path == path)
28847                .and_then(|request| request.namespace.clone())
28848        }
28849
28850        fn request_count(&self, path: &str) -> usize {
28851            self.requests
28852                .lock()
28853                .expect("captured requests")
28854                .iter()
28855                .filter(|request| request.path == path)
28856                .count()
28857        }
28858
28859        fn captured_paths(&self) -> Vec<String> {
28860            self.requests
28861                .lock()
28862                .expect("captured requests")
28863                .iter()
28864                .map(|request| request.path.clone())
28865                .collect()
28866        }
28867
28868        fn request_times(&self, path: &str) -> Vec<Instant> {
28869            self.requests
28870                .lock()
28871                .expect("captured requests")
28872                .iter()
28873                .filter(|request| request.path == path)
28874                .map(|request| request.received_at)
28875                .collect()
28876        }
28877
28878        fn request_body(&self, path: &str) -> Value {
28879            let requests = self.requests.lock().expect("captured requests");
28880            let body = &requests
28881                .iter()
28882                .find(|request| request.path == path)
28883                .unwrap_or_else(|| panic!("missing request for {path}"))
28884                .body;
28885            serde_json::from_str(body).unwrap_or_else(|error| {
28886                panic!("invalid JSON request body for {path}: {error}: {body:?}")
28887            })
28888        }
28889
28890        fn request_bodies(&self, path: &str) -> Vec<Value> {
28891            self.requests
28892                .lock()
28893                .expect("captured requests")
28894                .iter()
28895                .filter(|request| request.path == path)
28896                .map(|request| {
28897                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
28898                        panic!(
28899                            "invalid JSON request body for {path}: {error}: {:?}",
28900                            request.body
28901                        )
28902                    })
28903                })
28904                .collect()
28905        }
28906    }
28907
28908    impl Drop for MockWorkerServer {
28909        fn drop(&mut self) {
28910            self.stop.store(true, Ordering::SeqCst);
28911            let _ = TcpStream::connect(self.addr);
28912
28913            if let Some(thread) = self.thread.take() {
28914                thread.join().expect("join mock server");
28915            }
28916        }
28917    }
28918
28919    fn handle_mock_worker_request(
28920        stream: &mut TcpStream,
28921        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
28922        behavior: MockWorkerBehavior,
28923    ) {
28924        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
28925        let mut buffer = [0_u8; 8192];
28926        let mut request = Vec::new();
28927
28928        loop {
28929            match stream.read(&mut buffer) {
28930                Ok(0) => break,
28931                Ok(read) => {
28932                    request.extend_from_slice(&buffer[..read]);
28933                    if mock_request_is_complete(&request) {
28934                        break;
28935                    }
28936                }
28937                Err(error)
28938                    if matches!(
28939                        error.kind(),
28940                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
28941                    ) =>
28942                {
28943                    break;
28944                }
28945                Err(_) => return,
28946            }
28947        }
28948
28949        let request = String::from_utf8_lossy(&request);
28950        let body = request
28951            .split_once("\r\n\r\n")
28952            .map(|(_, body)| body)
28953            .unwrap_or_default();
28954        let path = request
28955            .lines()
28956            .next()
28957            .and_then(|line| line.split_whitespace().nth(1))
28958            .unwrap_or_default();
28959        let method = request
28960            .lines()
28961            .next()
28962            .and_then(|line| line.split_whitespace().next())
28963            .unwrap_or_default();
28964        let authorization = request.lines().find_map(|line| {
28965            let (name, value) = line.split_once(':')?;
28966            name.eq_ignore_ascii_case("Authorization")
28967                .then(|| value.trim().to_string())
28968        });
28969        let namespace = request.lines().find_map(|line| {
28970            let (name, value) = line.split_once(':')?;
28971            name.eq_ignore_ascii_case("X-Namespace")
28972                .then(|| value.trim().to_string())
28973        });
28974        let worker_protocol = request.lines().find_map(|line| {
28975            let (name, value) = line.split_once(':')?;
28976            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
28977                .then(|| value.trim().to_string())
28978        });
28979        let control_protocol = request.lines().find_map(|line| {
28980            let (name, value) = line.split_once(':')?;
28981            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
28982                .then(|| value.trim().to_string())
28983        });
28984        let request_number = {
28985            let mut requests = requests.lock().expect("captured requests");
28986            requests.push(CapturedRequest {
28987                headers: request
28988                    .split_once("\r\n\r\n")
28989                    .map_or("", |(headers, _)| headers)
28990                    .to_owned(),
28991                method: method.to_string(),
28992                path: path.to_string(),
28993                authorization,
28994                namespace,
28995                worker_protocol: worker_protocol.clone(),
28996                control_protocol,
28997                body: body.to_string(),
28998                received_at: Instant::now(),
28999            });
29000            requests
29001                .iter()
29002                .filter(|request| request.path == path)
29003                .count()
29004        };
29005
29006        if let Some(response) = behavior
29007            .request_override
29008            .and_then(|handler| handler(path, body, request_number))
29009        {
29010            write_mock_response(stream, response.0, &response.1);
29011            return;
29012        }
29013        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
29014            write_mock_response(stream, response.0, &response.1);
29015            return;
29016        }
29017        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
29018            return;
29019        }
29020        let pressure_path = behavior
29021            .storage_path
29022            .is_some_and(|part| path.contains(part));
29023        let prior_failures = if path.ends_with("/poll") {
29024            behavior.poll_failures_per_path
29025        } else {
29026            0
29027        };
29028        if pressure_path
29029            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
29030        {
29031            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
29032            let poll_id = path
29033                .ends_with("/poll")
29034                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
29035            let mut refusal = storage_refusal(
29036                poll_id,
29037                behavior.storage_unavailable,
29038                behavior.storage_mid_poll,
29039            );
29040            if behavior.storage_wrong_poll_id {
29041                refusal["poll_request_id"] = json!("wrong-poll");
29042            }
29043            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
29044            return;
29045        }
29046        if path.contains("/storage-task/")
29047            || path.contains("/storage-activity/")
29048            || path.contains("/storage-query/")
29049        {
29050            write_mock_response(stream, "200 OK", "{}");
29051            return;
29052        }
29053        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
29054            write_mock_response(stream, "200 OK", &json!({"task":{
29055                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
29056                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
29057                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29058                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29059                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
29060            }}).to_string());
29061            return;
29062        }
29063        if behavior.storage_activity
29064            && path == "/api/worker/activity-tasks/poll"
29065            && request_number == 1
29066        {
29067            write_mock_response(stream, "200 OK", &json!({"task":{
29068                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
29069                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29070                "attempt_number":7, "lease_owner":"storage-worker"
29071            }}).to_string());
29072            return;
29073        }
29074
29075        if path == "/api/worker/register" {
29076            if behavior.reject_registration_protocol {
29077                write_mock_response(
29078                    stream,
29079                    "400 Bad Request",
29080                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
29081                );
29082                return;
29083            }
29084            if behavior.reject_registration {
29085                write_mock_response(
29086                    stream,
29087                    "503 Service Unavailable",
29088                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
29089                );
29090                return;
29091            }
29092        }
29093
29094        if path.starts_with("/api/worker/registrations/") {
29095            if behavior.reject_deregistration_protocol {
29096                write_mock_response(
29097                    stream,
29098                    "400 Bad Request",
29099                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.19"}"#,
29100                );
29101            } else if behavior.reject_deregistration {
29102                write_mock_response(
29103                    stream,
29104                    "403 Forbidden",
29105                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
29106                );
29107            } else {
29108                write_mock_response(
29109                    stream,
29110                    "200 OK",
29111                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
29112                );
29113            }
29114            return;
29115        }
29116
29117        let is_poll = matches!(
29118            path,
29119            "/api/worker/workflow-tasks/poll"
29120                | "/api/worker/activity-tasks/poll"
29121                | "/api/worker/query-tasks/poll"
29122        );
29123        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
29124            write_mock_response(
29125                stream,
29126                "429 Too Many Requests",
29127                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
29128            );
29129            return;
29130        }
29131        if is_poll && request_number <= behavior.poll_failures_per_path {
29132            return;
29133        }
29134        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
29135            return;
29136        }
29137        if path == "/api/worker/heartbeat"
29138            && behavior.heartbeat_failure_request == Some(request_number)
29139        {
29140            return;
29141        }
29142        if path == "/api/worker/heartbeat"
29143            && behavior.delayed_heartbeat_request == Some(request_number)
29144        {
29145            thread::sleep(behavior.heartbeat_response_delay);
29146        }
29147        if behavior.unauthorized_polls && is_poll {
29148            write_mock_response(
29149                stream,
29150                "401 Unauthorized",
29151                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
29152            );
29153            return;
29154        }
29155        if behavior.draining_polls && is_poll {
29156            write_mock_response(
29157                stream,
29158                "409 Conflict",
29159                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
29160            );
29161            return;
29162        }
29163
29164        if let Some(codec_case) = behavior.invalid_task_payload_codec {
29165            if is_poll && request_number == 1 {
29166                let mut task = match path {
29167                    "/api/worker/workflow-tasks/poll" => json!({
29168                        "task_id": "codec-workflow",
29169                        "workflow_type": "codec.workflow",
29170                        "payload_codec": DEFAULT_CODEC,
29171                        "workflow_task_attempt": 1,
29172                        "lease_owner": "codec-worker"
29173                    }),
29174                    "/api/worker/activity-tasks/poll" => json!({
29175                        "task_id": "codec-activity",
29176                        "activity_attempt_id": "codec-activity-attempt",
29177                        "activity_type": "codec.activity",
29178                        "payload_codec": DEFAULT_CODEC,
29179                        "attempt_number": 1,
29180                        "lease_owner": "codec-worker"
29181                    }),
29182                    "/api/worker/query-tasks/poll" => json!({
29183                        "query_task_id": "codec-query",
29184                        "query_task_attempt": 1,
29185                        "workflow_type": "codec.workflow",
29186                        "query_name": "known",
29187                        "payload_codec": DEFAULT_CODEC,
29188                        "lease_owner": "codec-worker"
29189                    }),
29190                    _ => unreachable!("is_poll limits task codec probe paths"),
29191                };
29192                codec_case.apply(&mut task);
29193                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
29194                return;
29195            }
29196
29197            if matches!(
29198                path,
29199                "/api/worker/workflow-tasks/codec-workflow/fail"
29200                    | "/api/worker/activity-tasks/codec-activity/fail"
29201                    | "/api/worker/query-tasks/codec-query/fail"
29202            ) {
29203                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
29204                return;
29205            }
29206        }
29207
29208        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
29209            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
29210            let body = format!(
29211                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
29212            );
29213            write_mock_response(stream, "400 Bad Request", &body);
29214            return;
29215        }
29216
29217        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
29218        {
29219            write_mock_response(
29220                stream,
29221                "409 Conflict",
29222                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
29223            );
29224            return;
29225        }
29226
29227        if behavior.workflow_completion_status.is_some()
29228            && path == "/api/worker/workflow-tasks/poll"
29229            && request_number == 1
29230        {
29231            write_mock_response(
29232                stream,
29233                "200 OK",
29234                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"}}"#,
29235            );
29236            return;
29237        }
29238
29239        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
29240            if let (Some(status), Some(body)) = (
29241                behavior.workflow_completion_status,
29242                behavior.workflow_completion_body,
29243            ) {
29244                write_mock_response(stream, status, body);
29245                return;
29246            }
29247        }
29248
29249        if behavior.waiting_query_worker {
29250            if behavior.complete_named_signal
29251                && path == "/api/worker/workflow-tasks/poll"
29252                && request_number == 1
29253            {
29254                let body = json!({
29255                    "task": {
29256                        "task_id": "snapshot-open",
29257                        "workflow_id": "snapshot-1",
29258                        "run_id": "snapshot-run-1",
29259                        "workflow_type": "snapshot",
29260                        "payload_codec": DEFAULT_CODEC,
29261                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29262                            .expect("Avro workflow arguments"),
29263                        "history_events": [],
29264                        "workflow_task_attempt": 1,
29265                        "lease_owner": "rust-snapshot-worker"
29266                    }
29267                })
29268                .to_string();
29269                write_mock_response(stream, "200 OK", &body);
29270                return;
29271            }
29272
29273            let signal_request = request_number - usize::from(behavior.complete_named_signal);
29274            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
29275            if path == "/api/worker/workflow-tasks/poll"
29276                && signal_request >= 1
29277                && signal_request <= signal_request_limit
29278            {
29279                let finish = behavior.complete_named_signal && signal_request == 3;
29280                let amounts = if signal_request == 1 {
29281                    vec![3]
29282                } else {
29283                    vec![3, 5]
29284                };
29285                let task_id = if signal_request == 1 {
29286                    "snapshot-wait-3"
29287                } else if finish {
29288                    "snapshot-finish"
29289                } else {
29290                    "snapshot-wait-5"
29291                };
29292                let mut history_events = std::iter::once(json!({
29293                    "event_type": "SignalWaitOpened",
29294                    "payload": {"sequence": 1, "signal_name": "finish"}
29295                }))
29296                .chain(amounts.iter().enumerate().map(|(index, amount)| {
29297                    json!({
29298                        "event_type": "SignalReceived",
29299                        "payload": {
29300                            "signal_id": format!("increment-{amount}"),
29301                            "signal_name": "increment",
29302                            "workflow_sequence": index + 2,
29303                            "payload_codec": DEFAULT_CODEC,
29304                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29305                                .expect("Avro signal envelope")
29306                        }
29307                    })
29308                }))
29309                .collect::<Vec<_>>();
29310                let (resume_id, resume_name, resume_arguments) = if finish {
29311                    history_events.push(json!({
29312                        "event_type": "SignalReceived",
29313                        "payload": {
29314                            "signal_id": "finish",
29315                            "signal_name": "finish",
29316                            "workflow_sequence": 4,
29317                            "payload_codec": DEFAULT_CODEC,
29318                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29319                                .expect("Avro finish signal envelope")
29320                        }
29321                    }));
29322                    (
29323                        "finish".to_string(),
29324                        "finish".to_string(),
29325                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
29326                            .expect("Avro finish resume signal"),
29327                    )
29328                } else {
29329                    let amount = amounts.last().expect("amount");
29330                    (
29331                        format!("increment-{amount}"),
29332                        "increment".to_string(),
29333                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29334                            .expect("Avro increment resume signal"),
29335                    )
29336                };
29337                let body = json!({
29338                    "task": {
29339                        "task_id": task_id,
29340                        "workflow_id": "snapshot-1",
29341                        "run_id": "snapshot-run-1",
29342                        "workflow_type": "snapshot",
29343                        "payload_codec": DEFAULT_CODEC,
29344                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29345                            .expect("Avro workflow arguments"),
29346                        "history_events": history_events,
29347                        "workflow_task_attempt": 1,
29348                        "workflow_signal_id": resume_id,
29349                        "signal_name": resume_name,
29350                        "signal_arguments": resume_arguments,
29351                        "lease_owner": "rust-snapshot-worker"
29352                    }
29353                })
29354                .to_string();
29355                write_mock_response(stream, "200 OK", &body);
29356                return;
29357            }
29358
29359            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
29360                let history_events = [3, 5]
29361                    .into_iter()
29362                    .enumerate()
29363                    .map(|(index, amount)| {
29364                        json!({
29365                            "event_type": "SignalReceived",
29366                            "payload": {
29367                                "signal_id": format!("increment-{amount}"),
29368                                "signal_name": "increment",
29369                                "workflow_sequence": index + 2,
29370                                "payload_codec": DEFAULT_CODEC,
29371                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29372                                    .expect("Avro query signal envelope")
29373                            }
29374                        })
29375                    })
29376                    .collect::<Vec<_>>();
29377                let body = json!({
29378                    "task": {
29379                        "query_task_id": "snapshot-current",
29380                        "query_task_attempt": 1,
29381                        "lease_owner": "rust-snapshot-worker",
29382                        "workflow_id": "snapshot-1",
29383                        "run_id": "snapshot-run-1",
29384                        "workflow_type": "snapshot",
29385                        "query_name": "current",
29386                        "payload_codec": DEFAULT_CODEC,
29387                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29388                            .expect("Avro workflow arguments"),
29389                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29390                            .expect("Avro query arguments"),
29391                        "history_events": history_events,
29392                        "run_status": "waiting"
29393                    }
29394                })
29395                .to_string();
29396                write_mock_response(stream, "200 OK", &body);
29397                return;
29398            }
29399
29400            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
29401                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
29402            {
29403                write_mock_response(
29404                    stream,
29405                    "200 OK",
29406                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
29407                );
29408                return;
29409            }
29410
29411            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
29412                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
29413                return;
29414            }
29415
29416            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
29417                write_mock_response(
29418                    stream,
29419                    "200 OK",
29420                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
29421                );
29422                return;
29423            }
29424
29425            if path == "/api/worker/query-tasks/snapshot-current/complete" {
29426                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
29427                return;
29428            }
29429        }
29430
29431        if matches!(
29432            path,
29433            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
29434        ) {
29435            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
29436                .expect("typed mock result");
29437            let body = json!({
29438                "result": typed_fidelity_probe().into_json().expect("result projection"),
29439                "result_envelope": result,
29440            })
29441            .to_string();
29442            write_mock_response(stream, "200 OK", &body);
29443            return;
29444        }
29445
29446        if path == "/api/workflows/typed-1" {
29447            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
29448                .expect("typed mock result");
29449            let body = json!({
29450                "workflow_id": "typed-1",
29451                "run_id": "run-typed-1",
29452                "workflow_type": "typed.echo",
29453                "status": "completed",
29454                "output": typed_fidelity_probe().into_json().expect("output projection"),
29455                "output_envelope": result,
29456            })
29457            .to_string();
29458            write_mock_response(stream, "200 OK", &body);
29459            return;
29460        }
29461
29462        let (status, body) = match path {
29463            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
29464            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
29465            "/api/workflows" => (
29466                "201 Created",
29467                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
29468            ),
29469            "/api/worker/register" if behavior.decline_registration => (
29470                "200 OK",
29471                r#"{"worker_id":"declined-worker","registered":false}"#,
29472            ),
29473            "/api/worker/register" if behavior.waiting_query_worker => (
29474                "200 OK",
29475                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
29476            ),
29477            "/api/worker/register" => (
29478                "200 OK",
29479                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
29480            ),
29481            "/api/worker/heartbeat" => ("200 OK", "{}"),
29482            "/api/worker/activity-tasks/poll"
29483                if behavior.cancelled_activity && request_number == 1 =>
29484            {
29485                (
29486                    "200 OK",
29487                    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"}}"#,
29488                )
29489            }
29490            "/api/worker/activity-tasks/poll"
29491                if behavior.long_poll_capacity_responses_per_path > 0
29492                    && request_number
29493                        == behavior
29494                            .long_poll_capacity_responses_per_path
29495                            .saturating_add(1) =>
29496            {
29497                (
29498                    "200 OK",
29499                    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"}}"#,
29500                )
29501            }
29502            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
29503                ("200 OK", r#"{"task":null}"#)
29504            }
29505            "/api/worker/query-tasks/poll"
29506                if behavior.reject_query_completion && request_number == 1 =>
29507            {
29508                (
29509                    "200 OK",
29510                    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"}}"#,
29511                )
29512            }
29513            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
29514            "/api/worker/query-tasks/query-capture/complete"
29515            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
29516            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
29517                "200 OK",
29518                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
29519            ),
29520            "/api/worker/activity-tasks/activity-cancel/complete" => (
29521                "409 Conflict",
29522                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
29523            ),
29524            "/api/worker/activity-tasks/activity-typed/complete"
29525            | "/api/worker/activity-tasks/activity-typed/fail"
29526            | "/api/worker/activity-tasks/capacity-activity/complete"
29527            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
29528            "/api/workflows/counter-1/query/current" => (
29529                "200 OK",
29530                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
29531            ),
29532            "/api/workflows/counter-1/query/missing" => (
29533                "404 Not Found",
29534                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
29535            ),
29536            "/api/workflows/wf-lifecycle/cancel" => (
29537                "200 OK",
29538                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
29539            ),
29540            "/api/workflows/wf-lifecycle/terminate" => (
29541                "200 OK",
29542                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
29543            ),
29544            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
29545                "200 OK",
29546                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
29547            ),
29548            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
29549                "200 OK",
29550                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
29551            ),
29552            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
29553                "202 Accepted",
29554                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
29555            ),
29556            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
29557                "200 OK",
29558                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}"#,
29559            ),
29560            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
29561                "409 Conflict",
29562                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
29563            ),
29564            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
29565            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
29566                "409 Conflict",
29567                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
29568            ),
29569            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
29570                "200 OK",
29571                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"}]}}"#,
29572            ),
29573            "/api/workflows/wf-cancelled" => (
29574                "200 OK",
29575                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
29576            ),
29577            "/api/workflows/wf-terminated" => (
29578                "200 OK",
29579                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
29580            ),
29581            "/api/workflows/wf-timed-out" => (
29582                "200 OK",
29583                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
29584            ),
29585            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
29586                "200 OK",
29587                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
29588            ),
29589            "/api/workflows/wf-selected" => (
29590                "200 OK",
29591                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
29592            ),
29593            "/api/workflows/wf-selected/runs/run-selected" => (
29594                "200 OK",
29595                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
29596            ),
29597            _ => ("404 Not Found", r#"{"message":"not found"}"#),
29598        };
29599        write_mock_response(stream, status, body);
29600    }
29601
29602    fn mock_request_is_complete(request: &[u8]) -> bool {
29603        let Some(header_end) = request
29604            .windows(4)
29605            .position(|window| window == b"\r\n\r\n")
29606            .map(|position| position + 4)
29607        else {
29608            return false;
29609        };
29610        let headers = String::from_utf8_lossy(&request[..header_end]);
29611        let content_length = headers.lines().find_map(|line| {
29612            let (name, value) = line.split_once(':')?;
29613            name.eq_ignore_ascii_case("content-length")
29614                .then(|| value.trim().parse::<usize>().ok())
29615                .flatten()
29616        });
29617
29618        request.len() >= header_end + content_length.unwrap_or(0)
29619    }
29620
29621    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
29622        let response = format!(
29623            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
29624            body.len()
29625        );
29626
29627        let _ = stream.write_all(response.as_bytes());
29628        let _ = stream.flush();
29629    }
29630
29631    fn activity_completion_backend_recovery(
29632        path: &str,
29633        _body: &str,
29634        request_number: usize,
29635    ) -> Option<(&'static str, String)> {
29636        match path {
29637            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
29638                "200 OK",
29639                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(),
29640            )),
29641            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
29642                "503 Service Unavailable",
29643                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(),
29644            )),
29645            "/api/worker/activity-tasks/recover-activity/complete" => Some((
29646                "200 OK",
29647                r#"{"outcome":"completed","recorded":true}"#.to_string(),
29648            )),
29649            _ => None,
29650        }
29651    }
29652
29653    fn workflow_completion_backend_recovery(
29654        path: &str,
29655        _body: &str,
29656        request_number: usize,
29657    ) -> Option<(&'static str, String)> {
29658        match path {
29659            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
29660                "200 OK",
29661                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
29662            )),
29663            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
29664                "503 Service Unavailable",
29665                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(),
29666            )),
29667            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
29668                "200 OK",
29669                r#"{"outcome":"completed","recorded":true}"#.to_string(),
29670            )),
29671            _ => None,
29672        }
29673    }
29674
29675    fn activity_completion_stale_after_backend_recovery(
29676        path: &str,
29677        body: &str,
29678        request_number: usize,
29679    ) -> Option<(&'static str, String)> {
29680        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
29681            return Some((
29682                "409 Conflict",
29683                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(),
29684            ));
29685        }
29686        activity_completion_backend_recovery(path, body, request_number)
29687    }
29688
29689    fn activity_completion_remains_unavailable(
29690        path: &str,
29691        body: &str,
29692        request_number: usize,
29693    ) -> Option<(&'static str, String)> {
29694        if path == "/api/worker/activity-tasks/recover-activity/complete" {
29695            return activity_completion_backend_recovery(path, body, 1);
29696        }
29697        activity_completion_backend_recovery(path, body, request_number)
29698    }
29699
29700    #[tokio::test]
29701    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
29702        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29703            request_override: Some(activity_completion_backend_recovery),
29704            ..MockWorkerBehavior::default()
29705        });
29706        let client = Client::builder(server.base_url())
29707            .timeout(Duration::from_secs(2))
29708            .build()
29709            .expect("client");
29710        let handler_calls = Arc::new(AtomicUsize::new(0));
29711        let mut worker = Worker::new(client, "recover-queue")
29712            .worker_id("recover-worker")
29713            .poll_timeout(Duration::from_millis(10));
29714        worker.register_activity("recover.activity", {
29715            let handler_calls = Arc::clone(&handler_calls);
29716            move |_ctx, _args| {
29717                let handler_calls = Arc::clone(&handler_calls);
29718                async move {
29719                    handler_calls.fetch_add(1, Ordering::SeqCst);
29720                    Ok(json!("done"))
29721                }
29722            }
29723        });
29724
29725        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
29726        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
29727        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
29728        assert_eq!(bodies.len(), 2);
29729        assert_eq!(bodies[0], bodies[1]);
29730    }
29731
29732    #[tokio::test]
29733    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
29734        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29735            request_override: Some(workflow_completion_backend_recovery),
29736            ..MockWorkerBehavior::default()
29737        });
29738        let client = Client::builder(server.base_url())
29739            .timeout(Duration::from_secs(2))
29740            .build()
29741            .expect("client");
29742        let handler_calls = Arc::new(AtomicUsize::new(0));
29743        let mut worker = Worker::new(client, "recover-queue")
29744            .worker_id("recover-worker")
29745            .poll_timeout(Duration::from_millis(10));
29746        worker.register_workflow("recover.workflow", {
29747            let handler_calls = Arc::clone(&handler_calls);
29748            move |_ctx, _args| {
29749                let handler_calls = Arc::clone(&handler_calls);
29750                async move {
29751                    handler_calls.fetch_add(1, Ordering::SeqCst);
29752                    Ok(json!("done"))
29753                }
29754            }
29755        });
29756
29757        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
29758        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
29759        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
29760        assert_eq!(bodies.len(), 2);
29761        assert_eq!(bodies[0], bodies[1]);
29762    }
29763
29764    #[tokio::test]
29765    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
29766        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29767            request_override: Some(activity_completion_stale_after_backend_recovery),
29768            ..MockWorkerBehavior::default()
29769        });
29770        let client = Client::builder(server.base_url())
29771            .timeout(Duration::from_secs(2))
29772            .build()
29773            .expect("client");
29774        let handler_calls = Arc::new(AtomicUsize::new(0));
29775        let mut worker = Worker::new(client, "recover-queue")
29776            .worker_id("recover-worker")
29777            .poll_timeout(Duration::from_millis(10));
29778        worker.register_activity("recover.activity", {
29779            let handler_calls = Arc::clone(&handler_calls);
29780            move |_ctx, _args| {
29781                let handler_calls = Arc::clone(&handler_calls);
29782                async move {
29783                    handler_calls.fetch_add(1, Ordering::SeqCst);
29784                    Ok(json!("done"))
29785                }
29786            }
29787        });
29788
29789        assert_eq!(
29790            worker
29791                .run_once()
29792                .await
29793                .expect("authoritative stale outcome"),
29794            1
29795        );
29796        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
29797        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
29798        assert_eq!(bodies.len(), 2);
29799        assert_eq!(bodies[0], bodies[1]);
29800    }
29801
29802    #[test]
29803    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
29804        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
29805        let response = json!({
29806            "reason":"backend_unavailable", "operation":"complete_activity_task",
29807            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
29808            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
29809            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
29810        });
29811        let path = "/worker/activity-tasks/recover-activity/complete";
29812        let error = |body: Value| Error::Http {
29813            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29814            body: body.to_string(),
29815        };
29816        assert_eq!(
29817            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
29818            Some(Duration::from_secs(1))
29819        );
29820
29821        for (field, invalid) in [
29822            ("operation", json!("poll_activity_task")),
29823            ("outcome", json!("rejected")),
29824            ("worker_id", json!("another-worker")),
29825            ("task_queue", json!("recover-queue")),
29826            ("retryable", json!(false)),
29827            ("retry_after_seconds", json!(0)),
29828            ("task_id", json!("another-task")),
29829            ("lease_owner", json!("another-worker")),
29830            ("activity_attempt_id", json!("another-attempt")),
29831        ] {
29832            let mut invalid_response = response.clone();
29833            invalid_response[field] = invalid;
29834            assert_eq!(
29835                worker_fenced_completion_retry_after(
29836                    &error(invalid_response),
29837                    path,
29838                    Some(&request)
29839                ),
29840                None,
29841                "must not retry mismatched {field}"
29842            );
29843        }
29844        assert_eq!(
29845            worker_fenced_completion_retry_after(&error(response), path, None),
29846            None
29847        );
29848    }
29849
29850    #[tokio::test]
29851    async fn shutdown_interrupts_fenced_completion_backend_wait() {
29852        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29853            request_override: Some(activity_completion_remains_unavailable),
29854            ..MockWorkerBehavior::default()
29855        });
29856        let client = Client::builder(server.base_url())
29857            .timeout(Duration::from_secs(2))
29858            .build()
29859            .expect("client");
29860        let stop = Arc::new(AtomicBool::new(false));
29861        let worker = Worker::new(client, "recover-queue")
29862            .worker_id("recover-worker")
29863            .with_storage_admission(Arc::clone(&stop));
29864        let completion = tokio::spawn(async move {
29865            worker
29866                .client
29867                .complete_activity_task(
29868                    "recover-activity",
29869                    "recover-attempt",
29870                    "recover-worker",
29871                    json!("done"),
29872                    DEFAULT_CODEC,
29873                )
29874                .await
29875        });
29876        let path = "/api/worker/activity-tasks/recover-activity/complete";
29877        tokio::time::timeout(Duration::from_secs(2), async {
29878            while server.request_count(path) == 0 {
29879                tokio::time::sleep(Duration::from_millis(10)).await;
29880            }
29881        })
29882        .await
29883        .expect("first completion request");
29884        stop.store(true, Ordering::SeqCst);
29885        let error = tokio::time::timeout(Duration::from_secs(1), completion)
29886            .await
29887            .expect("shutdown must interrupt retry wait")
29888            .expect("completion task")
29889            .expect_err("backend is still unavailable");
29890        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
29891        assert_eq!(server.request_count(path), 1);
29892    }
29893}