Skip to main content

durable_workflow/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod activity_hydration;
4mod cancellation_context;
5mod cancellation_replay_clock;
6mod cancellation_scope;
7mod cancellation_scope_history;
8mod cancellation_scope_replay;
9mod cooperative_cancellation;
10mod local_activity;
11mod query_authority;
12mod runtime_payloads;
13mod runtime_uploads;
14mod sticky_worker;
15mod sticky_workflow_cache;
16mod worker_session;
17mod workflow_hydration;
18
19pub use cancellation_context::{
20    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
21};
22pub use cancellation_scope::CancellationScopeOpenReceipt;
23#[doc(hidden)]
24pub use cancellation_scope_history::{
25    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
26};
27#[doc(hidden)]
28pub use cancellation_scope_replay::CancellationScopeRequested;
29
30pub use cooperative_cancellation::{
31    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
32    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
33    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
34    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
35};
36
37use std::{
38    any::{type_name, Any, TypeId},
39    collections::{BTreeMap, BTreeSet, HashMap},
40    future::Future,
41    io::{self, Read},
42    pin::Pin,
43    sync::{
44        atomic::{AtomicBool, Ordering},
45        Arc, Mutex, OnceLock,
46    },
47    task::{Context as TaskContext, Poll},
48    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
49};
50
51use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
52use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
53use chrono::DateTime;
54use futures_util::{
55    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
56};
57pub use local_activity::LocalActivityOptions;
58use serde::{
59    de::DeserializeOwned,
60    ser::{SerializeMap, SerializeSeq},
61    Deserialize, Deserializer, Serialize, Serializer,
62};
63pub use serde_json::{json, Value};
64use sha2::{Digest, Sha256};
65pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
66use thiserror::Error;
67pub use uuid::Uuid;
68pub use worker_session::{WorkerSession, WorkerSessionOptions};
69
70pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
71pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
72
73/// Select the worker request protocol without enabling optional capabilities.
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
75#[non_exhaustive]
76pub enum WorkerProtocolVersion {
77    /// Compatibility with Servers that implement only worker protocol 1.19.
78    V119,
79    /// The default worker protocol.
80    #[default]
81    V120,
82}
83
84impl WorkerProtocolVersion {
85    fn as_str(self) -> &'static str {
86        match self {
87            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
88            Self::V120 => WORKER_PROTOCOL_VERSION,
89        }
90    }
91}
92const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
93/// First additive worker protocol that defines portable worker-affinity features.
94pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
95pub const CONTROL_PLANE_VERSION: &str = "2";
96pub const DEFAULT_CODEC: &str = "avro";
97pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
98/// Worker-registration capability for authored condition-wait occurrence identity.
99pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
100    "condition_wait_occurrence_identity";
101/// Worker-registration capability for portable memo upserts.
102pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
103/// Worker-registration capability for server-routed read-only queries.
104pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
105/// Worker-registration capability for canonical typed search attributes.
106pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
107/// Worker-registration capability for synchronous workflow updates.
108pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
109/// Worker-registration capability for durable named input streams.
110pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
111/// Worker-registration capability for persisted first-completion selection.
112pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
113pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
114pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
115pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
116pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
117pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
118/// First additive worker protocol that defines query-task transport.
119pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
120/// First additive worker protocol that defines typed search-attribute upserts.
121pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
122/// First additive worker protocol that defines portable memo upserts.
123pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
124/// First additive worker protocol that preserves declared search-attribute types.
125pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
126/// First additive worker protocol that defines external durable condition waits.
127pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
128/// First additive worker protocol that preserves authored condition-wait occurrences.
129pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
130/// First additive worker protocol that defines durable selection groups.
131pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
132
133pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
134    let Some((major, minor)) = version.split_once('.') else {
135        return false;
136    };
137    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
138}
139
140fn validate_user_signal_name(signal_name: &str) -> Result<()> {
141    if signal_name == MESSAGE_STREAM_SIGNAL {
142        return Err(Error::Codec(format!(
143            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
144        )));
145    }
146    Ok(())
147}
148
149const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
150const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
151    "Workflow task waiting for scheduled history.";
152const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
153const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
154const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
155const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
156const MAX_MEMO_ENTRIES: usize = 100;
157const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
158const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
159
160const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
161    "lease_expired",
162    "query_task_not_found",
163    "query_task_not_leased",
164    "query_task_timed_out",
165    "query_deadline_unavailable",
166    "lease_owner_mismatch",
167    "query_task_attempt_mismatch",
168];
169
170/// Manifest for the default service-worker profile.
171///
172/// Inline local execution is enabled separately by [`Worker::local_activities`].
173/// Local execution, sessions and caching require explicit Worker configuration.
174pub fn portable_worker_affinity_capability_manifest() -> Value {
175    json!({
176        "local_activities": {
177            "supported": false,
178            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
179            "reason": "rust_worker_does_not_execute_record_local_activity",
180        },
181        "worker_sessions": {
182            "supported": false,
183            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
184            "reason": "rust_worker_has_no_typed_session_lifecycle",
185        },
186        "sticky_execution": {
187            "supported": false,
188            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
189            "reason": "rust_worker_uses_complete_durable_history_replay",
190        },
191    })
192}
193
194/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
195pub const AVRO_VALUE_SCHEMA_JSON: &str =
196    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
197pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
198pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
199const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
200
201static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
202static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
203    OnceLock::new();
204
205#[derive(Clone, Copy)]
206enum RequestProtocol {
207    ControlPlane,
208    DefaultWorker,
209    Worker(&'static str),
210}
211
212pub type Result<T> = std::result::Result<T, Error>;
213
214#[derive(Debug, Error)]
215pub enum Error {
216    #[error("transport error: {0}")]
217    Transport(#[from] reqwest::Error),
218    #[error(
219        "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"
220    )]
221    InvalidBaseUrl,
222    #[error("json error: {0}")]
223    Json(#[from] serde_json::Error),
224    #[error("http {status}: {body}")]
225    Http {
226        status: reqwest::StatusCode,
227        body: String,
228    },
229    #[error("codec error: {0}")]
230    Codec(String),
231    #[error(transparent)]
232    QueryFailed(QueryFailure),
233    #[error(transparent)]
234    Protocol(ProtocolFailure),
235    #[error(transparent)]
236    NonDeterministicReplay(ReplayFailure),
237    #[error(transparent)]
238    ChildWorkflowFailed(ChildWorkflowFailure),
239    #[error(transparent)]
240    ActivityFailed(ActivityFailure),
241    #[error(transparent)]
242    ParallelFailed(ParallelFailure),
243    #[error(transparent)]
244    SagaCompensationFailed(SagaCompensationFailure),
245    #[error(transparent)]
246    InvalidParallelGroup(ParallelGroupError),
247    #[error(transparent)]
248    DurableOperationCancelled(DurableOperationCancelled),
249    #[error(transparent)]
250    WorkflowCancellationRequested(WorkflowCancellationRequested),
251    #[error(transparent)]
252    CooperativeCancellationRequested(CooperativeCancellationRequested),
253    #[error(transparent)]
254    CancellationScopeRequested(CancellationScopeRequested),
255    #[error(transparent)]
256    WorkflowCommandRejected(WorkflowCommandRejection),
257    #[error(transparent)]
258    WorkflowFailed(WorkflowTerminalOutcome),
259    #[error(transparent)]
260    WorkflowCancelled(WorkflowTerminalOutcome),
261    #[error(transparent)]
262    WorkflowTerminated(WorkflowTerminalOutcome),
263    #[error(transparent)]
264    WorkflowTimedOut(WorkflowTerminalOutcome),
265    #[error(transparent)]
266    ActivityTaskRejected(ActivityTaskRejection),
267    #[error("workflow handler {0:?} is not registered")]
268    WorkflowNotRegistered(String),
269    #[error("activity handler {0:?} is not registered")]
270    ActivityNotRegistered(String),
271    #[error(
272        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
273    )]
274    HandlerType {
275        handler_kind: HandlerKind,
276        handler_name: String,
277        value_kind: HandlerValueKind,
278        rust_type: &'static str,
279        message: String,
280    },
281    #[error("workflow future yielded without emitting a durable command")]
282    WorkflowYieldedWithoutCommand,
283    #[error(
284        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
285    )]
286    MissingWorkflowCommandIdentity,
287    #[error("workflow state lock is poisoned")]
288    WorkflowStatePoisoned,
289    #[error("timer duration is too large for the worker protocol")]
290    TimerDurationOverflow,
291    #[error(transparent)]
292    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
293    #[error(transparent)]
294    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
295    #[error("operation timed out")]
296    Timeout,
297    #[error(
298        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
299    )]
300    MissingRoleCredentials {
301        role: &'static str,
302        opposite_role: &'static str,
303    },
304    #[error("worker loop error: {0}")]
305    WorkerLoop(String),
306    #[error(
307        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
308    )]
309    UnsupportedUpdateValidators { workflow_type: String },
310    #[error("{primary}; worker deregistration also failed: {deregistration}")]
311    WorkerShutdown {
312        primary: Box<Error>,
313        deregistration: Box<Error>,
314    },
315    #[error("invalid child workflow options: {0}")]
316    InvalidChildWorkflowOptions(String),
317    #[error("invalid workflow memo update: {0}")]
318    InvalidMemoUpdate(String),
319    #[error(
320        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
321    )]
322    WorkflowMemoUpdatesUnavailable,
323    #[error("cooperative cancellation is unavailable: {0}")]
324    CooperativeCancellationUnavailable(String),
325    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
326    CancellationScopeExecutionUnavailable,
327    #[error("invalid cooperative cancellation: {0}")]
328    InvalidCooperativeCancellation(String),
329    #[error("activity execution no longer owns its claim: {0}")]
330    ActivityExecutionAbandoned(String),
331    #[error(transparent)]
332    InvalidActivityOptions(ActivityOptionsError),
333    #[error(transparent)]
334    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
335    #[doc(hidden)]
336    #[error("workflow requested continue as new")]
337    ContinueAsNew(ContinueAsNewRequest),
338}
339
340/// Handler namespaces checked independently within a Worker.
341#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
342pub enum RegistrationKind {
343    Workflow,
344    Activity,
345    Query,
346    Update,
347}
348
349impl std::fmt::Display for RegistrationKind {
350    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        formatter.write_str(match self {
352            Self::Workflow => "workflow",
353            Self::Activity => "activity",
354            Self::Query => "query",
355            Self::Update => "update",
356        })
357    }
358}
359
360/// The authoring adapter and source location of a handler registration.
361#[derive(Clone, Debug, PartialEq, Eq)]
362pub struct HandlerRegistration {
363    pub method: &'static str,
364    pub handler_type: &'static str,
365    pub file: &'static str,
366    pub line: u32,
367    pub column: u32,
368}
369
370impl std::fmt::Display for HandlerRegistration {
371    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372        write!(
373            formatter,
374            "{} at {}:{}:{} ({})",
375            self.method, self.file, self.line, self.column, self.handler_type
376        )
377    }
378}
379
380/// Ambiguous local configuration, rejected before contacting Server.
381#[derive(Clone, Debug, Error, PartialEq, Eq)]
382#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
383pub struct DuplicateRegistrationError {
384    pub handler_kind: RegistrationKind,
385    pub handler_name: String,
386    /// Query/update registrations are scoped to their owning workflow type.
387    pub workflow_type: Option<String>,
388    pub first_definition: HandlerRegistration,
389    pub second_definition: HandlerRegistration,
390}
391
392impl From<DuplicateRegistrationError> for Error {
393    fn from(error: DuplicateRegistrationError) -> Self {
394        Self::WorkerLoop(error.to_string())
395    }
396}
397
398/// Validation failure for a durable condition-wait definition.
399#[derive(Clone, Debug, Error, PartialEq, Eq)]
400pub enum ConditionWaitOptionsError {
401    #[error("condition_key must be non-empty")]
402    EmptyKey,
403    #[error("condition_definition_fingerprint must be non-empty")]
404    EmptyPredicateIdentity,
405    #[error("condition timeout is too large for the worker protocol")]
406    TimeoutOverflow,
407}
408
409/// Stable identity and optional durable timeout for a condition wait.
410///
411/// `predicate_identity` is recorded as the worker protocol's
412/// `condition_definition_fingerprint` and must change whenever predicate
413/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
414/// is written inline; it derives this identity from the predicate tokens.
415#[derive(Clone, Debug, PartialEq, Eq)]
416pub struct ConditionWaitOptions {
417    condition_key: String,
418    predicate_identity: String,
419    timeout: Option<Duration>,
420}
421
422impl ConditionWaitOptions {
423    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
424        Self {
425            condition_key: condition_key.into(),
426            predicate_identity: predicate_identity.into(),
427            timeout: None,
428        }
429    }
430
431    pub fn timeout(mut self, timeout: Duration) -> Self {
432        self.timeout = Some(timeout);
433        self
434    }
435
436    fn validate(
437        &self,
438    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
439        let condition_key = self.condition_key.trim();
440        if condition_key.is_empty() {
441            return Err(ConditionWaitOptionsError::EmptyKey);
442        }
443        let predicate_identity = self.predicate_identity.trim();
444        if predicate_identity.is_empty() {
445            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
446        }
447        let timeout_seconds = self
448            .timeout
449            .map(|timeout| {
450                timeout
451                    .as_secs()
452                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
453                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
454            })
455            .transpose()?;
456
457        Ok(ValidatedConditionWaitOptions {
458            condition_key: condition_key.to_string(),
459            predicate_identity: predicate_identity.to_string(),
460            timeout_seconds,
461        })
462    }
463}
464
465#[derive(Clone, Debug, PartialEq, Eq)]
466struct ValidatedConditionWaitOptions {
467    condition_key: String,
468    predicate_identity: String,
469    timeout_seconds: Option<u64>,
470}
471
472const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
473
474/// Unambiguous terminal result of a durable condition wait.
475#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
476#[serde(rename_all = "snake_case")]
477pub enum ConditionWaitResult {
478    Satisfied,
479    TimedOut,
480}
481
482impl ConditionWaitResult {
483    pub fn is_satisfied(self) -> bool {
484        self == Self::Satisfied
485    }
486
487    pub fn is_timed_out(self) -> bool {
488        self == Self::TimedOut
489    }
490}
491
492/// Build the stable condition definition identity used by [`wait_condition!`].
493#[doc(hidden)]
494pub fn __condition_definition_fingerprint(source: &str) -> String {
495    let mut digest = Sha256::new();
496    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
497    digest.update(source.as_bytes());
498    format!("sha256:{:x}", digest.finalize())
499}
500
501/// Create a durable condition wait whose predicate definition is fingerprinted
502/// from its inline Rust tokens.
503///
504/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
505/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
506#[macro_export]
507macro_rules! wait_condition {
508    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
509        $ctx.wait_condition(
510            $crate::ConditionWaitOptions::new(
511                $key,
512                $crate::__condition_definition_fingerprint(concat!(
513                    module_path!(),
514                    "\0",
515                    stringify!($predicate)
516                )),
517            )
518            .timeout($timeout),
519            $predicate,
520        )
521    }};
522    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
523        $ctx.wait_condition(
524            $crate::ConditionWaitOptions::new(
525                $key,
526                $crate::__condition_definition_fingerprint(concat!(
527                    module_path!(),
528                    "\0",
529                    stringify!($predicate)
530                )),
531            ),
532            $predicate,
533        )
534    }};
535}
536
537const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
538const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
539const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
540const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
541const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
542
543/// Validation failure for a typed workflow search-attribute update.
544#[derive(Clone, Debug, Error, PartialEq, Eq)]
545pub enum SearchAttributeUpdateError {
546    #[error("search-attribute update requires at least one attribute")]
547    Empty,
548    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
549    InvalidKey(String),
550    #[error("search-attribute update exceeds the limit of 100 attributes")]
551    TooManyAttributes,
552    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
553    ValueTooLong {
554        key: String,
555        kind: &'static str,
556        limit: usize,
557    },
558    #[error(
559        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
560    )]
561    EmptyString(String),
562    #[error("search attribute {0:?} has a non-finite float value")]
563    NonFiniteFloat(String),
564    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
565    InvalidDateTime(String),
566    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
567    PayloadTooLarge,
568}
569
570/// One public typed search-attribute value.
571#[derive(Clone, Debug, PartialEq)]
572pub enum SearchAttributeValue {
573    String(String),
574    Keyword(String),
575    KeywordList(Vec<String>),
576    Int(i64),
577    Float(f64),
578    Bool(bool),
579    DateTime(String),
580    Delete,
581}
582
583impl SearchAttributeValue {
584    fn type_name(&self) -> Option<&'static str> {
585        match self {
586            Self::String(_) => Some("string"),
587            Self::Keyword(_) => Some("keyword"),
588            Self::KeywordList(_) => Some("keyword_list"),
589            Self::Int(_) => Some("int"),
590            Self::Float(_) => Some("float"),
591            Self::Bool(_) => Some("bool"),
592            Self::DateTime(_) => Some("datetime"),
593            Self::Delete => None,
594        }
595    }
596
597    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
598        let normalize_string = |value: String, kind: &'static str, limit: usize| {
599            let value = value.trim().to_string();
600            if value.is_empty() {
601                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
602            }
603            if value.len() > limit {
604                return Err(SearchAttributeUpdateError::ValueTooLong {
605                    key: key.to_string(),
606                    kind,
607                    limit,
608                });
609            }
610            Ok(value)
611        };
612
613        match self {
614            Self::String(value) => Ok(Self::String(normalize_string(
615                value,
616                "string",
617                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
618            )?)),
619            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
620                value,
621                "keyword",
622                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
623            )?)),
624            Self::KeywordList(values) => {
625                let values = values
626                    .into_iter()
627                    .map(|value| {
628                        let value = value.trim().to_string();
629                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
630                            return Err(SearchAttributeUpdateError::ValueTooLong {
631                                key: key.to_string(),
632                                kind: "keyword-list entry",
633                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
634                            });
635                        }
636                        Ok(value)
637                    })
638                    .collect::<std::result::Result<Vec<_>, _>>()?;
639                Ok(Self::KeywordList(values))
640            }
641            Self::Float(value) if !value.is_finite() => {
642                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
643            }
644            Self::DateTime(value) => {
645                let value =
646                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
647                if DateTime::parse_from_rfc3339(&value).is_err() {
648                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
649                }
650                Ok(Self::DateTime(value))
651            }
652            value => Ok(value),
653        }
654    }
655
656    fn into_json(self) -> Value {
657        match self {
658            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
659                Value::String(value)
660            }
661            Self::KeywordList(values) => {
662                Value::Array(values.into_iter().map(Value::String).collect())
663            }
664            Self::Int(value) => json!(value),
665            Self::Float(value) => json!(value),
666            Self::Bool(value) => json!(value),
667            Self::Delete => Value::Null,
668        }
669    }
670}
671
672/// Validated typed workflow-side search-attribute mutation.
673#[derive(Clone, Debug, Default, PartialEq)]
674pub struct SearchAttributeUpdate {
675    attributes: BTreeMap<String, SearchAttributeValue>,
676}
677
678impl SearchAttributeUpdate {
679    pub fn new() -> Self {
680        Self::default()
681    }
682
683    pub fn set(
684        mut self,
685        key: impl Into<String>,
686        value: SearchAttributeValue,
687    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
688        let key = key.into();
689        validate_search_attribute_key(&key)?;
690        if !self.attributes.contains_key(&key)
691            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
692        {
693            return Err(SearchAttributeUpdateError::TooManyAttributes);
694        }
695        self.attributes.insert(key.clone(), value.normalized(&key)?);
696        self.validate_size()?;
697        Ok(self)
698    }
699
700    pub fn string(
701        self,
702        key: impl Into<String>,
703        value: impl Into<String>,
704    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
705        self.set(key, SearchAttributeValue::String(value.into()))
706    }
707
708    pub fn keyword(
709        self,
710        key: impl Into<String>,
711        value: impl Into<String>,
712    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
713        self.set(key, SearchAttributeValue::Keyword(value.into()))
714    }
715
716    pub fn keyword_list<I, V>(
717        self,
718        key: impl Into<String>,
719        values: I,
720    ) -> std::result::Result<Self, SearchAttributeUpdateError>
721    where
722        I: IntoIterator<Item = V>,
723        V: Into<String>,
724    {
725        self.set(
726            key,
727            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
728        )
729    }
730
731    pub fn int(
732        self,
733        key: impl Into<String>,
734        value: i64,
735    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
736        self.set(key, SearchAttributeValue::Int(value))
737    }
738
739    pub fn float(
740        self,
741        key: impl Into<String>,
742        value: f64,
743    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
744        self.set(key, SearchAttributeValue::Float(value))
745    }
746
747    pub fn bool(
748        self,
749        key: impl Into<String>,
750        value: bool,
751    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
752        self.set(key, SearchAttributeValue::Bool(value))
753    }
754
755    pub fn datetime(
756        self,
757        key: impl Into<String>,
758        value: impl Into<String>,
759    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
760        self.set(key, SearchAttributeValue::DateTime(value.into()))
761    }
762
763    pub fn delete(
764        self,
765        key: impl Into<String>,
766    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
767        self.set(key, SearchAttributeValue::Delete)
768    }
769
770    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
771        let (attributes, _) = self.clone().into_wire_parts();
772        if serde_json::to_vec(&attributes)
773            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
774            .unwrap_or(true)
775        {
776            return Err(SearchAttributeUpdateError::PayloadTooLarge);
777        }
778        Ok(())
779    }
780
781    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
782        let mut attributes = serde_json::Map::new();
783        let mut attribute_types = BTreeMap::new();
784        for (key, value) in self.attributes {
785            if let Some(type_name) = value.type_name() {
786                attribute_types.insert(key.clone(), type_name.to_string());
787            }
788            attributes.insert(key, value.into_json());
789        }
790        (Value::Object(attributes), attribute_types)
791    }
792
793    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
794        if self.attributes.is_empty() {
795            return Err(SearchAttributeUpdateError::Empty);
796        }
797        self.validate_size()
798    }
799}
800
801fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
802    let valid = !key.is_empty()
803        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
804        && key
805            .bytes()
806            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
807    if valid {
808        Ok(())
809    } else {
810        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
811    }
812}
813
814/// The registered handler family reported by [`Error::HandlerType`].
815#[derive(Clone, Copy, Debug, PartialEq, Eq)]
816pub enum HandlerKind {
817    Workflow,
818    Activity,
819}
820
821impl std::fmt::Display for HandlerKind {
822    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
823        formatter.write_str(match self {
824            Self::Workflow => "workflow",
825            Self::Activity => "activity",
826        })
827    }
828}
829
830/// Whether a typed handler failed to adapt its input or result.
831#[derive(Clone, Copy, Debug, PartialEq, Eq)]
832pub enum HandlerValueKind {
833    Input,
834    Result,
835}
836
837impl std::fmt::Display for HandlerValueKind {
838    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
839        formatter.write_str(match self {
840            Self::Input => "input",
841            Self::Result => "result",
842        })
843    }
844}
845
846/// The lifecycle command sent to a workflow execution.
847#[derive(Clone, Copy, Debug, PartialEq, Eq)]
848pub enum WorkflowCommandKind {
849    Cancel,
850    Terminate,
851}
852
853impl WorkflowCommandKind {
854    fn as_str(self) -> &'static str {
855        match self {
856            Self::Cancel => "cancel",
857            Self::Terminate => "terminate",
858        }
859    }
860}
861
862/// Optional structured fields for a cancellation or termination request.
863#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
864pub struct WorkflowCommandOptions {
865    #[serde(skip_serializing_if = "Option::is_none")]
866    pub reason: Option<String>,
867    #[serde(skip_serializing_if = "Option::is_none")]
868    pub request_id: Option<String>,
869}
870
871/// Server-enforced timeout policy for a workflow start.
872///
873/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
874/// only bounds how long the caller waits. A server deadline produces a terminal
875/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
876/// `run_timeout`.
877#[derive(Clone, Debug, PartialEq, Eq)]
878pub struct WorkflowStartOptions {
879    pub execution_timeout_seconds: u64,
880    pub run_timeout_seconds: u64,
881}
882
883impl Default for WorkflowStartOptions {
884    fn default() -> Self {
885        Self {
886            execution_timeout_seconds: 3600,
887            run_timeout_seconds: 600,
888        }
889    }
890}
891
892impl WorkflowStartOptions {
893    pub fn new() -> Self {
894        Self::default()
895    }
896
897    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
898        self.execution_timeout_seconds = seconds;
899        self
900    }
901
902    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
903        self.run_timeout_seconds = seconds;
904        self
905    }
906
907    fn validate(&self) -> Result<()> {
908        if self.execution_timeout_seconds == 0 {
909            return Err(Error::Codec(
910                "execution_timeout_seconds must be at least 1".to_string(),
911            ));
912        }
913        if self.run_timeout_seconds == 0 {
914            return Err(Error::Codec(
915                "run_timeout_seconds must be at least 1".to_string(),
916            ));
917        }
918        if self.run_timeout_seconds > self.execution_timeout_seconds {
919            return Err(Error::Codec(
920                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
921            ));
922        }
923
924        Ok(())
925    }
926}
927
928/// Optional routing overrides for a continue-as-new transition.
929///
930/// Omitted values retain the current workflow type and task queue. Server-owned
931/// instance metadata is not accepted here and is carried by the server.
932#[derive(Clone, Debug, Default, PartialEq, Eq)]
933pub struct ContinueAsNewOptions {
934    pub workflow_type: Option<String>,
935    pub task_queue: Option<String>,
936}
937
938impl ContinueAsNewOptions {
939    pub fn new() -> Self {
940        Self::default()
941    }
942
943    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
944        self.workflow_type = Some(workflow_type.into());
945        self
946    }
947
948    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
949        self.task_queue = Some(task_queue.into());
950        self
951    }
952
953    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
954        for (field, value) in [
955            ("workflow_type", self.workflow_type.as_deref()),
956            ("task_queue", self.task_queue.as_deref()),
957        ] {
958            if value.is_some_and(|value| value.trim().is_empty()) {
959                return Err(ContinueAsNewOptionsError {
960                    field,
961                    message: format!("{field} must not be empty"),
962                });
963            }
964        }
965        Ok(())
966    }
967}
968
969/// A stable validation error raised before a continue-as-new command is emitted.
970#[derive(Clone, Debug, Error, PartialEq, Eq)]
971#[error("invalid continue-as-new option {field}: {message}")]
972pub struct ContinueAsNewOptionsError {
973    pub field: &'static str,
974    pub message: String,
975}
976
977/// Public history-budget information attached to the current workflow task.
978#[derive(Clone, Debug, Default, PartialEq, Eq)]
979pub struct WorkflowHistoryBudget {
980    pub event_count: u64,
981    pub size_bytes: Option<u64>,
982    pub continue_as_new_recommended: bool,
983    pub pressure: Option<String>,
984}
985
986#[doc(hidden)]
987#[derive(Clone, Debug)]
988pub struct ContinueAsNewRequest {
989    arguments: AvroValue,
990    options: ContinueAsNewOptions,
991}
992
993impl WorkflowCommandOptions {
994    pub fn new() -> Self {
995        Self::default()
996    }
997
998    pub fn reason(mut self, reason: impl Into<String>) -> Self {
999        self.reason = Some(reason.into());
1000        self
1001    }
1002
1003    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1004        self.request_id = Some(request_id.into());
1005        self
1006    }
1007}
1008
1009/// The accepted, machine-readable result of a lifecycle command.
1010#[derive(Clone, Debug, PartialEq)]
1011pub struct WorkflowCommandResult {
1012    pub command: WorkflowCommandKind,
1013    pub workflow_id: String,
1014    pub run_id: Option<String>,
1015    pub outcome: Option<String>,
1016    pub reason: Option<String>,
1017    pub command_status: Option<String>,
1018    pub raw: Value,
1019}
1020
1021/// A new run continuing a failed run from its recorded activity boundary.
1022#[derive(Clone, Debug, PartialEq)]
1023pub struct WorkflowRedriveResult {
1024    pub workflow_id: String,
1025    pub source_run_id: String,
1026    pub run_id: String,
1027    pub resume_step_sequence: u64,
1028    pub raw: Value,
1029}
1030
1031/// A stable rejection returned by instance- or selected-run lifecycle commands.
1032#[derive(Clone, Debug, Error)]
1033#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1034pub struct WorkflowCommandRejection {
1035    pub command: WorkflowCommandKind,
1036    pub status: u16,
1037    pub reason: String,
1038    pub message: String,
1039    pub workflow_id: String,
1040    pub run_id: Option<String>,
1041    pub target_scope: Option<String>,
1042    pub body: Value,
1043}
1044
1045/// Stable terminal categories returned by [`WorkflowHandle::result`].
1046#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1047pub enum WorkflowTerminalKind {
1048    Failed,
1049    Cancelled,
1050    Terminated,
1051    TimedOut,
1052}
1053
1054/// A typed terminal workflow outcome with durable identity and failure metadata.
1055///
1056/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1057/// of parsing its display representation. Fields remain `None` when an older
1058/// server did not publish that metadata.
1059#[derive(Clone, Debug, Error)]
1060#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1061pub struct WorkflowTerminalOutcome {
1062    pub kind: WorkflowTerminalKind,
1063    pub workflow_id: String,
1064    pub run_id: Option<String>,
1065    pub reason: String,
1066    pub failure_category: Option<String>,
1067    pub failure_id: Option<String>,
1068    pub exception_type: Option<String>,
1069    pub exception_class: Option<String>,
1070    pub non_retryable: Option<bool>,
1071    pub message: Option<String>,
1072    pub exception: Option<Value>,
1073    pub raw: Value,
1074}
1075
1076/// A worker-side activity settlement or heartbeat rejected by durable state.
1077#[derive(Clone, Debug, Error)]
1078#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1079pub struct ActivityTaskRejection {
1080    pub operation: String,
1081    pub status: u16,
1082    pub reason: String,
1083    pub task_id: String,
1084    pub activity_attempt_id: String,
1085    pub cancel_requested: bool,
1086    pub can_continue: Option<bool>,
1087    pub run_closed_reason: Option<String>,
1088    pub body: Value,
1089}
1090
1091/// Stable validation categories for [`ActivityOptions`].
1092#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1093pub enum ActivityOptionsErrorKind {
1094    EmptyTaskQueue,
1095    EmptyRetryPolicy,
1096    InvalidMaxAttempts,
1097    BackoffWithoutRetryBudget,
1098    TooManyBackoffIntervals,
1099    InvalidBackoffCoefficient,
1100    BackoffGenerationTooLarge,
1101    BackoffOverflow,
1102    EmptyNonRetryableErrorType,
1103    TimeoutNotPositive,
1104    MissingTotalTimeout,
1105    TimeoutOverflow,
1106    TimeoutOrder,
1107}
1108
1109/// A machine-readable activity-options validation failure.
1110#[derive(Clone, Debug, Error, PartialEq, Eq)]
1111#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1112pub struct ActivityOptionsError {
1113    pub kind: ActivityOptionsErrorKind,
1114    pub field: Option<&'static str>,
1115    pub message: String,
1116}
1117
1118impl ActivityOptionsError {
1119    fn new(
1120        kind: ActivityOptionsErrorKind,
1121        field: Option<&'static str>,
1122        message: impl Into<String>,
1123    ) -> Self {
1124        Self {
1125            kind,
1126            field,
1127            message: message.into(),
1128        }
1129    }
1130}
1131
1132/// Stable terminal categories returned when an awaited activity does not succeed.
1133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1134pub enum ActivityFailureKind {
1135    Failed,
1136    Cancelled,
1137    TimedOut,
1138}
1139
1140/// A stable, machine-readable terminal activity failure.
1141///
1142/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1143/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1144#[derive(Clone, Debug, Error, PartialEq)]
1145#[error("activity failed ({reason}): {message}")]
1146pub struct ActivityFailure {
1147    pub kind: ActivityFailureKind,
1148    pub reason: String,
1149    pub message: String,
1150    pub activity_execution_id: Option<String>,
1151    pub activity_attempt_id: Option<String>,
1152    pub activity_type: Option<String>,
1153    pub activity_class: Option<String>,
1154    pub attempt_number: Option<u64>,
1155    pub failure_id: Option<String>,
1156    pub failure_category: Option<String>,
1157    pub timeout_kind: Option<String>,
1158    pub non_retryable: bool,
1159    pub exception_type: Option<String>,
1160    pub exception_class: Option<String>,
1161    pub code: Option<Value>,
1162    pub exception: Option<Value>,
1163}
1164
1165/// Stable terminal categories returned when an awaited child does not succeed.
1166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1167pub enum ChildWorkflowFailureKind {
1168    Failed,
1169    Cancelled,
1170    Terminated,
1171}
1172
1173/// A stable, machine-readable child workflow failure delivered to its parent.
1174///
1175/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1176/// of parsing the display message. Child and parent identifiers retain the
1177/// relationship recorded in durable history across worker restarts.
1178#[derive(Clone, Debug, Error)]
1179#[error("child workflow failed ({reason}): {message}")]
1180pub struct ChildWorkflowFailure {
1181    pub kind: ChildWorkflowFailureKind,
1182    pub reason: String,
1183    pub message: String,
1184    pub parent_workflow_id: Option<String>,
1185    pub parent_workflow_run_id: Option<String>,
1186    pub child_workflow_id: Option<String>,
1187    pub child_workflow_run_id: Option<String>,
1188    pub child_workflow_type: Option<String>,
1189    pub failure_id: Option<String>,
1190    pub failure_category: Option<String>,
1191    pub exception_type: Option<String>,
1192    pub exception_class: Option<String>,
1193    pub non_retryable: bool,
1194    pub code: Option<Value>,
1195    pub exception: Option<Value>,
1196}
1197
1198/// The identity of one durable workflow execution.
1199#[derive(Clone, Debug, PartialEq, Eq)]
1200pub struct WorkflowIdentity {
1201    pub workflow_id: Option<String>,
1202    pub run_id: Option<String>,
1203}
1204
1205/// A successful child result together with its durable parent-child identity.
1206#[derive(Clone, Debug, PartialEq)]
1207pub struct ChildWorkflowResult {
1208    pub parent: WorkflowIdentity,
1209    pub child: WorkflowIdentity,
1210    pub child_workflow_type: Option<String>,
1211    pub result: Value,
1212}
1213
1214/// Lossless successful child result for fixed Avro Value workflows.
1215#[derive(Clone, Debug, PartialEq)]
1216pub struct ChildWorkflowAvroResult {
1217    pub parent: WorkflowIdentity,
1218    pub child: WorkflowIdentity,
1219    pub child_workflow_type: Option<String>,
1220    pub result: AvroValue,
1221}
1222
1223/// Stable user-facing identity for one member of a durable selection group.
1224#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1225#[serde(untagged)]
1226pub enum SelectionKey {
1227    Index(usize),
1228    Name(String),
1229}
1230
1231impl From<usize> for SelectionKey {
1232    fn from(value: usize) -> Self {
1233        Self::Index(value)
1234    }
1235}
1236
1237impl From<String> for SelectionKey {
1238    fn from(value: String) -> Self {
1239        Self::Name(value)
1240    }
1241}
1242
1243impl From<&str> for SelectionKey {
1244    fn from(value: &str) -> Self {
1245        Self::Name(value.to_string())
1246    }
1247}
1248
1249/// Typed result of explicitly awaiting a cancelled non-winning operation.
1250#[derive(Clone, Debug, Error, PartialEq, Eq)]
1251#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1252pub struct DurableOperationCancelled {
1253    pub selection_group_id: String,
1254    pub member_key: SelectionKey,
1255    pub member_index: usize,
1256    pub operation_kind: String,
1257    pub operation_identity: String,
1258}
1259
1260/// Stable identity for one enclosing deterministic parallel group.
1261///
1262/// The same fields are attached to every ordinary activity, timer, or child
1263/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1264/// no Rust-specific wire command is introduced.
1265#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1266pub struct ParallelGroupMetadata {
1267    pub parallel_group_id: String,
1268    pub parallel_group_kind: String,
1269    pub parallel_group_base_sequence: u64,
1270    pub parallel_group_size: usize,
1271    pub parallel_group_index: usize,
1272    #[serde(default, skip_serializing_if = "Option::is_none")]
1273    pub parallel_group_mode: Option<String>,
1274    #[serde(default, skip_serializing_if = "Option::is_none")]
1275    pub selection_member_key: Option<SelectionKey>,
1276    #[serde(default, skip_serializing_if = "Option::is_none")]
1277    pub selection_member_index: Option<usize>,
1278    #[serde(default, skip_serializing_if = "Option::is_none")]
1279    pub selection_member_base_sequence: Option<u64>,
1280    #[serde(default, skip_serializing_if = "Option::is_none")]
1281    pub selection_member_size: Option<usize>,
1282    #[serde(default, skip_serializing_if = "Option::is_none")]
1283    pub selection_member_kind: Option<String>,
1284}
1285
1286/// One input-ordered result returned by [`WorkflowContext::parallel`].
1287#[derive(Clone, Debug, PartialEq)]
1288pub enum ParallelResult {
1289    Activity(Value),
1290    ChildWorkflow(ChildWorkflowResult),
1291    Timer,
1292    Signal(Vec<Value>),
1293    Condition(ConditionWaitResult),
1294    Group(Vec<ParallelResult>),
1295}
1296
1297/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1298#[derive(Clone, Debug, PartialEq)]
1299pub enum ParallelAvroResult {
1300    Activity(AvroValue),
1301    ChildWorkflow(ChildWorkflowAvroResult),
1302    Timer,
1303    Signal(Vec<AvroValue>),
1304    Condition(ConditionWaitResult),
1305    Group(Vec<ParallelAvroResult>),
1306}
1307
1308impl ParallelAvroResult {
1309    fn into_json_result(self) -> Result<ParallelResult> {
1310        match self {
1311            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1312            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1313                parent: result.parent,
1314                child: result.child,
1315                child_workflow_type: result.child_workflow_type,
1316                result: result.result.into_json()?,
1317            })),
1318            Self::Timer => Ok(ParallelResult::Timer),
1319            Self::Signal(values) => Ok(ParallelResult::Signal(
1320                values
1321                    .into_iter()
1322                    .map(AvroValue::into_json)
1323                    .collect::<Result<Vec<_>>>()?,
1324            )),
1325            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1326            Self::Group(results) => Ok(ParallelResult::Group(
1327                results
1328                    .into_iter()
1329                    .map(Self::into_json_result)
1330                    .collect::<Result<Vec<_>>>()?,
1331            )),
1332        }
1333    }
1334}
1335
1336/// One successful leaf retained when another parallel member failed.
1337#[derive(Clone, Debug, PartialEq)]
1338pub struct ParallelCompletion {
1339    pub member_path: Vec<usize>,
1340    pub result: ParallelResult,
1341}
1342
1343/// A deterministic join failed after some siblings had already completed.
1344///
1345/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1346/// error. `completed` is declaration ordered and contains only durable
1347/// successes observed in the same replay. Late sibling completions can add
1348/// entries on a later replay without changing `member_path` or the selected
1349/// positional failure.
1350#[derive(Debug, Error)]
1351#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1352pub struct ParallelFailure {
1353    pub group_id: String,
1354    pub member_path: Vec<usize>,
1355    pub group_path: Vec<ParallelGroupMetadata>,
1356    pub completed: Vec<ParallelCompletion>,
1357    #[source]
1358    pub cause: Box<Error>,
1359}
1360
1361/// Stable validation error returned before an invalid group emits commands.
1362#[derive(Clone, Debug, Error, PartialEq, Eq)]
1363#[error("invalid deterministic parallel group ({reason}): {message}")]
1364pub struct ParallelGroupError {
1365    pub reason: &'static str,
1366    pub member_path: Vec<usize>,
1367    pub message: String,
1368}
1369
1370/// Cooperative workflow cancellation observed at an author-controlled point.
1371#[derive(Clone, Debug, Error, PartialEq, Eq)]
1372#[error("workflow cancellation was requested")]
1373pub struct WorkflowCancellationRequested;
1374
1375/// A forward saga failure followed by a terminal compensation failure.
1376#[derive(Debug, Error)]
1377#[error(
1378    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1379)]
1380pub struct SagaCompensationFailure {
1381    pub initiating_failure: Box<Error>,
1382    pub compensation_failure: Box<Error>,
1383    pub compensation_activity_type: String,
1384    pub compensation_registration_order: usize,
1385}
1386
1387/// Server behavior when a parent closes while its child is still open.
1388#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1389pub enum ParentClosePolicy {
1390    #[default]
1391    Abandon,
1392    /// Legacy terminal cancellation without cooperative cleanup.
1393    RequestCancel,
1394    /// Request cooperative cleanup with the original lineage and deadline.
1395    RequestCancellation,
1396    Terminate,
1397}
1398
1399impl ParentClosePolicy {
1400    fn as_str(self) -> &'static str {
1401        match self {
1402            Self::Abandon => "abandon",
1403            Self::RequestCancel => "request_cancel",
1404            Self::RequestCancellation => "request_cancellation",
1405            Self::Terminate => "terminate",
1406        }
1407    }
1408}
1409
1410/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1411#[non_exhaustive]
1412#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1413pub enum CancellationPolicy {
1414    /// Request cancellation and continue without waiting. Historical Activity default.
1415    TryCancel,
1416    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1417    WaitCancellationCompleted,
1418    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1419    #[default]
1420    Abandon,
1421}
1422
1423impl CancellationPolicy {
1424    fn as_str(self) -> &'static str {
1425        match self {
1426            Self::TryCancel => "try_cancel",
1427            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1428            Self::Abandon => "abandon",
1429        }
1430    }
1431}
1432
1433/// Durable retry policy for one child workflow invocation.
1434#[derive(Clone, Debug, Default, PartialEq, Eq)]
1435pub struct ChildWorkflowRetryPolicy {
1436    pub max_attempts: Option<u32>,
1437    pub backoff_seconds: Vec<u64>,
1438    pub non_retryable_error_types: Vec<String>,
1439}
1440
1441/// Options recorded with a child-workflow command.
1442///
1443/// The task queue is mandatory so routing is explicit and replay-stable.
1444#[derive(Clone, Debug, PartialEq, Eq)]
1445pub struct ChildWorkflowOptions {
1446    pub task_queue: String,
1447    pub parent_close_policy: ParentClosePolicy,
1448    pub cancellation_policy: CancellationPolicy,
1449    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1450    pub execution_timeout_seconds: Option<u64>,
1451    pub run_timeout_seconds: Option<u64>,
1452}
1453
1454impl ChildWorkflowOptions {
1455    pub fn new(task_queue: impl Into<String>) -> Self {
1456        Self {
1457            task_queue: task_queue.into(),
1458            parent_close_policy: ParentClosePolicy::Abandon,
1459            cancellation_policy: CancellationPolicy::Abandon,
1460            retry_policy: None,
1461            execution_timeout_seconds: None,
1462            run_timeout_seconds: None,
1463        }
1464    }
1465
1466    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1467        self.parent_close_policy = policy;
1468        self
1469    }
1470
1471    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1472        self.cancellation_policy = policy;
1473        self
1474    }
1475
1476    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1477        self.retry_policy = Some(policy);
1478        self
1479    }
1480
1481    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1482        self.execution_timeout_seconds = Some(seconds);
1483        self
1484    }
1485
1486    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1487        self.run_timeout_seconds = Some(seconds);
1488        self
1489    }
1490}
1491
1492/// Backoff intervals for one durable activity retry policy.
1493#[derive(Clone, Debug, PartialEq, Eq)]
1494pub enum ActivityBackoff {
1495    /// Use these intervals between attempts. The server repeats the final
1496    /// interval if the retry budget contains more attempts than entries.
1497    /// All entries are retained, including those beyond the retry budget.
1498    Explicit(Vec<Duration>),
1499    /// Generate one interval for every retry using integer exponential growth.
1500    Exponential {
1501        initial_interval: Duration,
1502        coefficient: u32,
1503        maximum_interval: Option<Duration>,
1504    },
1505}
1506
1507/// Durable server-side retry policy for one activity execution.
1508#[derive(Clone, Debug, Default, PartialEq, Eq)]
1509pub struct ActivityRetryPolicy {
1510    pub max_attempts: Option<u32>,
1511    pub backoff: Option<ActivityBackoff>,
1512    pub non_retryable_error_types: Vec<String>,
1513}
1514
1515impl ActivityRetryPolicy {
1516    /// Start a policy with a finite attempt budget, including the first attempt.
1517    pub fn new(max_attempts: u32) -> Self {
1518        Self {
1519            max_attempts: Some(max_attempts),
1520            ..Self::default()
1521        }
1522    }
1523
1524    /// Preserve the complete explicit list independently of the attempt budget.
1525    /// Unused entries remain part of the policy compared during replay.
1526    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1527        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1528        self
1529    }
1530
1531    pub fn exponential_backoff(
1532        mut self,
1533        initial_interval: Duration,
1534        coefficient: u32,
1535        maximum_interval: Option<Duration>,
1536    ) -> Self {
1537        self.backoff = Some(ActivityBackoff::Exponential {
1538            initial_interval,
1539            coefficient,
1540            maximum_interval,
1541        });
1542        self
1543    }
1544
1545    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1546        self.non_retryable_error_types.push(error_type.into());
1547        self
1548    }
1549
1550    pub fn non_retryable_error_types(
1551        mut self,
1552        error_types: impl IntoIterator<Item = impl Into<String>>,
1553    ) -> Self {
1554        self.non_retryable_error_types
1555            .extend(error_types.into_iter().map(Into::into));
1556        self
1557    }
1558}
1559
1560/// Options recorded atomically on one deterministic `schedule_activity` command.
1561///
1562/// Durations are rounded up to whole seconds when encoded, so the server never
1563/// receives a shorter timeout or backoff than the caller requested.
1564#[derive(Clone, Debug, Default, PartialEq, Eq)]
1565pub struct ActivityOptions {
1566    pub task_queue: Option<String>,
1567    pub retry_policy: Option<ActivityRetryPolicy>,
1568    pub start_to_close_timeout: Option<Duration>,
1569    pub schedule_to_start_timeout: Option<Duration>,
1570    pub schedule_to_close_timeout: Option<Duration>,
1571    pub heartbeat_timeout: Option<Duration>,
1572    pub cancellation_policy: Option<CancellationPolicy>,
1573}
1574
1575impl ActivityOptions {
1576    pub fn new() -> Self {
1577        Self::default()
1578    }
1579
1580    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1581        self.task_queue = Some(task_queue.into());
1582        self
1583    }
1584
1585    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1586        self.retry_policy = Some(policy);
1587        self
1588    }
1589
1590    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1591        self.start_to_close_timeout = Some(timeout);
1592        self
1593    }
1594
1595    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1596        self.schedule_to_start_timeout = Some(timeout);
1597        self
1598    }
1599
1600    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1601        self.schedule_to_close_timeout = Some(timeout);
1602        self
1603    }
1604
1605    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1606        self.heartbeat_timeout = Some(timeout);
1607        self
1608    }
1609
1610    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1611        self.cancellation_policy = Some(policy);
1612        self
1613    }
1614
1615    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1616        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1617            && self.schedule_to_close_timeout.is_none()
1618        {
1619            return Err(ActivityOptionsError::new(
1620                ActivityOptionsErrorKind::MissingTotalTimeout,
1621                Some("schedule_to_close_timeout"),
1622                "remote Activity Abandon requires a finite positive total timeout",
1623            ));
1624        }
1625        if self
1626            .task_queue
1627            .as_deref()
1628            .is_some_and(|queue| queue.trim().is_empty())
1629        {
1630            return Err(ActivityOptionsError::new(
1631                ActivityOptionsErrorKind::EmptyTaskQueue,
1632                Some("task_queue"),
1633                "task_queue must not be empty",
1634            ));
1635        }
1636
1637        for (field, value) in [
1638            ("start_to_close_timeout", self.start_to_close_timeout),
1639            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1640            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1641            ("heartbeat_timeout", self.heartbeat_timeout),
1642        ] {
1643            if value.is_some_and(|value| value.is_zero()) {
1644                return Err(ActivityOptionsError::new(
1645                    ActivityOptionsErrorKind::TimeoutNotPositive,
1646                    Some(field),
1647                    format!("{field} must be positive"),
1648                ));
1649            }
1650        }
1651
1652        validate_timeout_order(
1653            "heartbeat_timeout",
1654            self.heartbeat_timeout,
1655            "start_to_close_timeout",
1656            self.start_to_close_timeout,
1657        )?;
1658        validate_timeout_order(
1659            "start_to_close_timeout",
1660            self.start_to_close_timeout,
1661            "schedule_to_close_timeout",
1662            self.schedule_to_close_timeout,
1663        )?;
1664        validate_timeout_order(
1665            "schedule_to_start_timeout",
1666            self.schedule_to_start_timeout,
1667            "schedule_to_close_timeout",
1668            self.schedule_to_close_timeout,
1669        )?;
1670
1671        Ok(ValidatedActivityOptions {
1672            task_queue: self.task_queue.clone(),
1673            retry_policy: self
1674                .retry_policy
1675                .as_ref()
1676                .map(validate_activity_retry_policy)
1677                .transpose()?,
1678            start_to_close_timeout: timeout_seconds(
1679                "start_to_close_timeout",
1680                self.start_to_close_timeout,
1681            )?,
1682            schedule_to_start_timeout: timeout_seconds(
1683                "schedule_to_start_timeout",
1684                self.schedule_to_start_timeout,
1685            )?,
1686            schedule_to_close_timeout: timeout_seconds(
1687                "schedule_to_close_timeout",
1688                self.schedule_to_close_timeout,
1689            )?,
1690            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1691            cancellation_policy: self.cancellation_policy,
1692        })
1693    }
1694}
1695
1696/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1697///
1698/// Constructors capture arguments but perform no I/O. The join validates the
1699/// complete tree, attaches the existing parallel-group metadata to every
1700/// ordinary command, schedules all leaves, and then suspends.
1701pub enum ParallelOperation {
1702    Activity {
1703        activity_type: String,
1704        options: ActivityOptions,
1705        arguments: Result<AvroValue>,
1706    },
1707    ChildWorkflow {
1708        workflow_type: String,
1709        options: ChildWorkflowOptions,
1710        arguments: Result<AvroValue>,
1711    },
1712    Timer(Duration),
1713    Signal(String),
1714    Condition {
1715        options: ConditionWaitOptions,
1716        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1717    },
1718    Group(Vec<ParallelOperation>),
1719}
1720
1721impl ParallelOperation {
1722    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1723        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1724    }
1725
1726    pub fn activity_with_options<T: Serialize>(
1727        activity_type: impl Into<String>,
1728        options: ActivityOptions,
1729        args: T,
1730    ) -> Self {
1731        Self::Activity {
1732            activity_type: activity_type.into(),
1733            options,
1734            arguments: AvroValue::from_serialize(&args),
1735        }
1736    }
1737
1738    pub fn child_workflow<T: Serialize>(
1739        workflow_type: impl Into<String>,
1740        options: ChildWorkflowOptions,
1741        args: T,
1742    ) -> Self {
1743        Self::ChildWorkflow {
1744            workflow_type: workflow_type.into(),
1745            options,
1746            arguments: AvroValue::from_serialize(&args),
1747        }
1748    }
1749
1750    pub fn timer(duration: Duration) -> Self {
1751        Self::Timer(duration)
1752    }
1753
1754    pub fn signal(signal_name: impl Into<String>) -> Self {
1755        Self::Signal(signal_name.into())
1756    }
1757
1758    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1759    where
1760        F: Fn() -> Result<bool> + Send + 'static,
1761    {
1762        Self::Condition {
1763            options,
1764            predicate: Box::new(predicate),
1765        }
1766    }
1767
1768    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1769        Self::Group(operations)
1770    }
1771}
1772
1773#[derive(Clone, Debug)]
1774struct ValidatedActivityOptions {
1775    task_queue: Option<String>,
1776    retry_policy: Option<Value>,
1777    start_to_close_timeout: Option<u64>,
1778    schedule_to_start_timeout: Option<u64>,
1779    schedule_to_close_timeout: Option<u64>,
1780    heartbeat_timeout: Option<u64>,
1781    cancellation_policy: Option<CancellationPolicy>,
1782}
1783
1784fn validate_timeout_order(
1785    smaller_name: &'static str,
1786    smaller: Option<Duration>,
1787    larger_name: &'static str,
1788    larger: Option<Duration>,
1789) -> std::result::Result<(), ActivityOptionsError> {
1790    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1791        return Err(ActivityOptionsError::new(
1792            ActivityOptionsErrorKind::TimeoutOrder,
1793            Some(smaller_name),
1794            format!("{smaller_name} must be <= {larger_name}"),
1795        ));
1796    }
1797    Ok(())
1798}
1799
1800fn timeout_seconds(
1801    field: &'static str,
1802    value: Option<Duration>,
1803) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1804    value
1805        .map(|value| {
1806            activity_protocol_seconds(value).ok_or_else(|| {
1807                ActivityOptionsError::new(
1808                    ActivityOptionsErrorKind::TimeoutOverflow,
1809                    Some(field),
1810                    format!("{field} is too large for the worker protocol"),
1811                )
1812            })
1813        })
1814        .transpose()
1815}
1816
1817fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1818    value
1819        .as_secs()
1820        .checked_add(u64::from(value.subsec_nanos() > 0))
1821}
1822
1823fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1824    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1825}
1826
1827fn validate_activity_retry_policy(
1828    policy: &ActivityRetryPolicy,
1829) -> std::result::Result<Value, ActivityOptionsError> {
1830    if policy.max_attempts.is_none()
1831        && policy.backoff.is_none()
1832        && policy.non_retryable_error_types.is_empty()
1833    {
1834        return Err(ActivityOptionsError::new(
1835            ActivityOptionsErrorKind::EmptyRetryPolicy,
1836            Some("retry_policy"),
1837            "retry_policy must configure at least one field",
1838        ));
1839    }
1840    if policy.max_attempts == Some(0) {
1841        return Err(ActivityOptionsError::new(
1842            ActivityOptionsErrorKind::InvalidMaxAttempts,
1843            Some("retry_policy.max_attempts"),
1844            "max_attempts must be >= 1",
1845        ));
1846    }
1847    if policy
1848        .non_retryable_error_types
1849        .iter()
1850        .any(|error_type| error_type.trim().is_empty())
1851    {
1852        return Err(ActivityOptionsError::new(
1853            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1854            Some("retry_policy.non_retryable_error_types"),
1855            "non_retryable_error_types must not contain empty values",
1856        ));
1857    }
1858
1859    let backoff_seconds = match &policy.backoff {
1860        None => None,
1861        Some(backoff) => {
1862            let max_attempts = policy.max_attempts.ok_or_else(|| {
1863                ActivityOptionsError::new(
1864                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1865                    Some("retry_policy.backoff"),
1866                    "backoff requires max_attempts",
1867                )
1868            })?;
1869            let retry_count = max_attempts.saturating_sub(1) as usize;
1870            let intervals = match backoff {
1871                ActivityBackoff::Explicit(intervals) => intervals.clone(),
1872                ActivityBackoff::Exponential {
1873                    initial_interval,
1874                    coefficient,
1875                    maximum_interval,
1876                } => {
1877                    if *coefficient < 1 {
1878                        return Err(ActivityOptionsError::new(
1879                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1880                            Some("retry_policy.backoff.coefficient"),
1881                            "backoff coefficient must be >= 1",
1882                        ));
1883                    }
1884                    if retry_count > 10_000 {
1885                        return Err(ActivityOptionsError::new(
1886                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1887                            Some("retry_policy.max_attempts"),
1888                            "generated backoff supports at most 10000 retry intervals",
1889                        ));
1890                    }
1891                    let mut current = *initial_interval;
1892                    let mut intervals = Vec::with_capacity(retry_count);
1893                    for _ in 0..retry_count {
1894                        let interval = maximum_interval
1895                            .map(|maximum| current.min(maximum))
1896                            .unwrap_or(current);
1897                        intervals.push(interval);
1898                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1899                            break;
1900                        }
1901                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1902                            ActivityOptionsError::new(
1903                                ActivityOptionsErrorKind::BackoffOverflow,
1904                                Some("retry_policy.backoff"),
1905                                "generated backoff interval overflowed",
1906                            )
1907                        })?;
1908                    }
1909                    intervals
1910                }
1911            };
1912            Some(
1913                intervals
1914                    .into_iter()
1915                    .map(|interval| {
1916                        activity_protocol_seconds(interval).ok_or_else(|| {
1917                            ActivityOptionsError::new(
1918                                ActivityOptionsErrorKind::BackoffOverflow,
1919                                Some("retry_policy.backoff"),
1920                                "backoff interval is too large for the worker protocol",
1921                            )
1922                        })
1923                    })
1924                    .collect::<std::result::Result<Vec<_>, _>>()?,
1925            )
1926        }
1927    };
1928
1929    let mut encoded = serde_json::Map::new();
1930    if let Some(max_attempts) = policy.max_attempts {
1931        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1932    }
1933    if let Some(backoff_seconds) = backoff_seconds {
1934        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1935    }
1936    if !policy.non_retryable_error_types.is_empty() {
1937        let mut canonical_error_types = Vec::new();
1938        for error_type in policy
1939            .non_retryable_error_types
1940            .iter()
1941            .map(|error_type| error_type.trim())
1942        {
1943            if !canonical_error_types.contains(&error_type) {
1944                canonical_error_types.push(error_type);
1945            }
1946        }
1947        encoded.insert(
1948            "non_retryable_error_types".to_string(),
1949            json!(canonical_error_types),
1950        );
1951    }
1952    Ok(Value::Object(encoded))
1953}
1954
1955/// A stable, machine-readable failure raised when workflow code no longer
1956/// reconstructs the durable command stream recorded in history.
1957#[derive(Clone, Debug, Error)]
1958#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1959pub struct ReplayFailure {
1960    pub reason: String,
1961    pub sequence: Option<u64>,
1962    pub expected: Option<String>,
1963    pub actual: Option<String>,
1964    pub message: String,
1965}
1966
1967impl ReplayFailure {
1968    fn new(
1969        reason: impl Into<String>,
1970        sequence: Option<u64>,
1971        expected: Option<String>,
1972        actual: Option<String>,
1973        message: impl Into<String>,
1974    ) -> Self {
1975        Self {
1976            reason: reason.into(),
1977            sequence,
1978            expected,
1979            actual,
1980            message: message.into(),
1981        }
1982    }
1983}
1984
1985/// A stable, machine-readable workflow query or query-task settlement failure.
1986#[derive(Clone, Debug, Error)]
1987#[error("query failed ({reason}, HTTP {status}): {message}")]
1988pub struct QueryFailure {
1989    pub status: u16,
1990    pub reason: String,
1991    pub message: String,
1992    pub body: Value,
1993}
1994
1995/// A stable failure returned when a server rejects an SDK protocol version.
1996#[derive(Clone, Debug, Error)]
1997#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
1998pub struct ProtocolFailure {
1999    pub status: u16,
2000    pub reason: String,
2001    pub message: String,
2002    pub supported_version: Option<String>,
2003    pub requested_version: Option<String>,
2004    pub body: Value,
2005}
2006
2007#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2008pub struct PayloadEnvelope {
2009    pub codec: String,
2010    pub blob: String,
2011}
2012
2013impl PayloadEnvelope {
2014    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2015        encode_payload(value, DEFAULT_CODEC)
2016    }
2017
2018    /// Encode an explicit typed value, including the bytes branch that JSON
2019    /// serialization cannot represent.
2020    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2021        encode_avro_value(value)
2022    }
2023}
2024
2025/// Native adapter for the fixed language-neutral Avro Value schema.
2026#[derive(Clone, Debug)]
2027pub enum AvroValue {
2028    Null,
2029    Boolean(bool),
2030    Long(i64),
2031    Double(f64),
2032    Bytes(Vec<u8>),
2033    String(String),
2034    Array(Vec<AvroValue>),
2035    Map(BTreeMap<String, AvroValue>),
2036}
2037
2038impl PartialEq for AvroValue {
2039    fn eq(&self, other: &Self) -> bool {
2040        match (self, other) {
2041            (Self::Null, Self::Null) => true,
2042            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2043            (Self::Long(left), Self::Long(right)) => left == right,
2044            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2045            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2046            (Self::String(left), Self::String(right)) => left == right,
2047            (Self::Array(left), Self::Array(right)) => left == right,
2048            (Self::Map(left), Self::Map(right)) => left == right,
2049            _ => false,
2050        }
2051    }
2052}
2053
2054impl AvroValue {
2055    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2056        Self::from_serde_value(
2057            serde_value::to_value(value).map_err(|error| {
2058                Error::Codec(format!("could not adapt value for Avro: {error}"))
2059            })?,
2060        )
2061    }
2062
2063    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2064        use serde_value::Value as SerdeValue;
2065
2066        match value {
2067            SerdeValue::Unit => Ok(Self::Null),
2068            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2069            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2070            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2071            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2072            SerdeValue::I64(value) => Ok(Self::Long(value)),
2073            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2074            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2075            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2076            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2077                Error::Codec(
2078                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2079                        .to_string(),
2080                )
2081            }),
2082            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2083            SerdeValue::F64(value) => Self::finite_double(value),
2084            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2085            SerdeValue::String(value) => Ok(Self::String(value)),
2086            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2087            SerdeValue::Option(None) => Ok(Self::Null),
2088            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2089                Self::from_serde_value(*value)
2090            }
2091            SerdeValue::Seq(values) => values
2092                .into_iter()
2093                .map(Self::from_serde_value)
2094                .collect::<Result<Vec<_>>>()
2095                .map(Self::Array),
2096            SerdeValue::Map(values) => values
2097                .into_iter()
2098                .map(|(key, value)| {
2099                    let SerdeValue::String(key) = key else {
2100                        return Err(Error::Codec(
2101                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2102                        ));
2103                    };
2104
2105                    Ok((key, Self::from_serde_value(value)?))
2106                })
2107                .collect::<Result<BTreeMap<_, _>>>()
2108                .map(Self::Map),
2109        }
2110    }
2111
2112    fn finite_double(value: f64) -> Result<Self> {
2113        if !value.is_finite() {
2114            return Err(Error::Codec(
2115                "non_finite_float: Avro Value doubles must be finite".to_string(),
2116            ));
2117        }
2118
2119        Ok(Self::Double(value))
2120    }
2121
2122    fn into_json(self) -> Result<Value> {
2123        match self {
2124            Self::Null => Ok(Value::Null),
2125            Self::Boolean(value) => Ok(Value::Bool(value)),
2126            Self::Long(value) => Ok(Value::Number(value.into())),
2127            Self::Double(value) => serde_json::Number::from_f64(value)
2128                .map(Value::Number)
2129                .ok_or_else(|| {
2130                    Error::Codec(
2131                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2132                    )
2133                }),
2134            Self::Bytes(value) => Ok(json!({
2135                "$type": "bytes",
2136                "base64": BASE64.encode(value),
2137            })),
2138            Self::String(value) => Ok(Value::String(value)),
2139            Self::Array(values) => values
2140                .into_iter()
2141                .map(Self::into_json)
2142                .collect::<Result<Vec<_>>>()
2143                .map(Value::Array),
2144            Self::Map(values) => values
2145                .into_iter()
2146                .map(|(key, value)| Ok((key, value.into_json()?)))
2147                .collect::<Result<serde_json::Map<_, _>>>()
2148                .map(Value::Object),
2149        }
2150    }
2151
2152    fn into_serde_value(self) -> serde_value::Value {
2153        use serde_value::Value as SerdeValue;
2154
2155        match self {
2156            Self::Null => SerdeValue::Unit,
2157            Self::Boolean(value) => SerdeValue::Bool(value),
2158            Self::Long(value) => SerdeValue::I64(value),
2159            Self::Double(value) => SerdeValue::F64(value),
2160            Self::Bytes(value) => SerdeValue::Bytes(value),
2161            Self::String(value) => SerdeValue::String(value),
2162            Self::Array(values) => {
2163                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2164            }
2165            Self::Map(values) => SerdeValue::Map(
2166                values
2167                    .into_iter()
2168                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2169                    .collect(),
2170            ),
2171        }
2172    }
2173
2174    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2175        self.into_serde_value().deserialize_into().map_err(|error| {
2176            Error::Codec(format!(
2177                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2178            ))
2179        })
2180    }
2181}
2182
2183impl Serialize for AvroValue {
2184    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2185    where
2186        S: Serializer,
2187    {
2188        match self {
2189            Self::Null => serializer.serialize_unit(),
2190            Self::Boolean(value) => serializer.serialize_bool(*value),
2191            Self::Long(value) => serializer.serialize_i64(*value),
2192            Self::Double(value) => serializer.serialize_f64(*value),
2193            Self::Bytes(value) => serializer.serialize_bytes(value),
2194            Self::String(value) => serializer.serialize_str(value),
2195            Self::Array(values) => {
2196                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2197                for value in values {
2198                    sequence.serialize_element(value)?;
2199                }
2200                sequence.end()
2201            }
2202            Self::Map(values) => {
2203                let mut map = serializer.serialize_map(Some(values.len()))?;
2204                for (key, value) in values {
2205                    map.serialize_entry(key, value)?;
2206                }
2207                map.end()
2208            }
2209        }
2210    }
2211}
2212
2213pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2214    let datum = avro_value_to_datum(value)?;
2215    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2216        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2217    let mut bytes = Vec::with_capacity(datum.len() + 10);
2218    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2219    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2220    bytes.extend_from_slice(&datum);
2221    Ok(PayloadEnvelope {
2222        codec: DEFAULT_CODEC.to_string(),
2223        blob: BASE64.encode(bytes),
2224    })
2225}
2226
2227pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2228    if envelope.codec != DEFAULT_CODEC {
2229        return Err(unsupported_payload_codec(&envelope.codec));
2230    }
2231    decode_avro_value_blob(&envelope.blob)
2232}
2233
2234pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2235    let blob = match codec {
2236        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2237        other => return Err(unsupported_payload_codec(other)),
2238    };
2239
2240    Ok(PayloadEnvelope {
2241        codec: codec.to_string(),
2242        blob,
2243    })
2244}
2245
2246pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2247    match envelope.codec.as_str() {
2248        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2249        other => Err(unsupported_payload_codec(other)),
2250    }
2251}
2252
2253fn handler_type_error<T>(
2254    handler_kind: HandlerKind,
2255    handler_name: &str,
2256    value_kind: HandlerValueKind,
2257    message: impl Into<String>,
2258) -> Error {
2259    Error::HandlerType {
2260        handler_kind,
2261        handler_name: handler_name.to_string(),
2262        value_kind,
2263        rust_type: type_name::<T>(),
2264        message: message.into(),
2265    }
2266}
2267
2268fn decode_handler_input<T: DeserializeOwned>(
2269    arguments: AvroValue,
2270    handler_kind: HandlerKind,
2271    handler_name: &str,
2272) -> Result<T> {
2273    let argument = match arguments {
2274        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2275            arguments.pop().expect("one typed handler argument")
2276        }
2277        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2278        AvroValue::Array(arguments) => {
2279            return Err(handler_type_error::<T>(
2280                handler_kind,
2281                handler_name,
2282                HandlerValueKind::Input,
2283                format!(
2284                    "typed handlers accept one request value, but the task carried {} arguments",
2285                    arguments.len()
2286                ),
2287            ));
2288        }
2289        argument => argument,
2290    };
2291
2292    argument.deserialize().map_err(|error| {
2293        handler_type_error::<T>(
2294            handler_kind,
2295            handler_name,
2296            HandlerValueKind::Input,
2297            error.to_string(),
2298        )
2299    })
2300}
2301
2302fn encode_handler_result<T: Serialize>(
2303    result: &T,
2304    handler_kind: HandlerKind,
2305    handler_name: &str,
2306) -> Result<AvroValue> {
2307    AvroValue::from_serialize(result).map_err(|error| {
2308        handler_type_error::<T>(
2309            handler_kind,
2310            handler_name,
2311            HandlerValueKind::Result,
2312            error.to_string(),
2313        )
2314    })
2315}
2316
2317fn decode_handler_result<T: DeserializeOwned>(
2318    result: AvroValue,
2319    handler_kind: HandlerKind,
2320    handler_name: &str,
2321) -> Result<T> {
2322    result.deserialize().map_err(|error| {
2323        handler_type_error::<T>(
2324            handler_kind,
2325            handler_name,
2326            HandlerValueKind::Result,
2327            error.to_string(),
2328        )
2329    })
2330}
2331
2332#[cfg(test)]
2333fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2334    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2335}
2336
2337fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2338    validate_payload_codec(fallback_codec)?;
2339
2340    if value.is_null() {
2341        return Ok(Value::Null);
2342    }
2343
2344    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2345        return decode_blob(blob, codec);
2346    }
2347
2348    if let Some(blob) = value.as_str() {
2349        return decode_blob(blob, fallback_codec);
2350    }
2351
2352    Err(untagged_payload_value())
2353}
2354
2355fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2356    let envelope = match codec {
2357        DEFAULT_CODEC => encode_avro_value(value)?,
2358        other => return Err(unsupported_payload_codec(other)),
2359    };
2360    Ok(serde_json::to_value(envelope)?)
2361}
2362
2363fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2364    validate_payload_codec(fallback_codec)?;
2365
2366    if value.is_null() {
2367        return Ok(AvroValue::Null);
2368    }
2369
2370    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2371        validate_payload_codec(codec)?;
2372        return decode_avro_value_blob(blob);
2373    }
2374
2375    if let Some(blob) = value.as_str() {
2376        return match fallback_codec {
2377            DEFAULT_CODEC => decode_avro_value_blob(blob),
2378            other => Err(unsupported_payload_codec(other)),
2379        };
2380    }
2381
2382    Err(untagged_payload_value())
2383}
2384
2385fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2386    match value {
2387        AvroValue::Null => AvroValue::Array(Vec::new()),
2388        AvroValue::Array(_) => value,
2389        other => AvroValue::Array(vec![other]),
2390    }
2391}
2392
2393fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2394    match codec {
2395        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2396        other => Err(unsupported_payload_codec(other)),
2397    }
2398}
2399
2400fn validate_payload_codec(codec: &str) -> Result<()> {
2401    match codec {
2402        DEFAULT_CODEC => Ok(()),
2403        MISSING_TASK_PAYLOAD_CODEC => {
2404            Err(invalid_task_payload_codec("task payload_codec is missing"))
2405        }
2406        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2407        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2408            "task payload_codec must be a string",
2409        )),
2410        other => Err(unsupported_payload_codec(other)),
2411    }
2412}
2413
2414fn invalid_task_payload_codec(reason: &str) -> Error {
2415    Error::Codec(format!(
2416        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2417    ))
2418}
2419
2420fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2421    let Some(object) = value.as_object() else {
2422        return Ok(None);
2423    };
2424    if !object.contains_key("codec") && !object.contains_key("blob") {
2425        return Ok(None);
2426    }
2427
2428    let codec = object
2429        .get("codec")
2430        .and_then(Value::as_str)
2431        .ok_or_else(invalid_payload_envelope)?;
2432    validate_payload_codec(codec)?;
2433    let blob = object
2434        .get("blob")
2435        .and_then(Value::as_str)
2436        .ok_or_else(invalid_payload_envelope)?;
2437    Ok(Some((codec, blob)))
2438}
2439
2440fn invalid_payload_envelope() -> Error {
2441    Error::Codec(
2442        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2443            .to_string(),
2444    )
2445}
2446
2447fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2448    for command in commands {
2449        let Some(command) = command.as_object() else {
2450            continue;
2451        };
2452        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2453            continue;
2454        };
2455        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2456            continue;
2457        };
2458
2459        if let Some(codec) = command.get("payload_codec") {
2460            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2461            validate_payload_codec(codec)?;
2462        }
2463
2464        let payload = command
2465            .get(payload_field)
2466            .ok_or_else(invalid_payload_envelope)?;
2467        if runtime_payloads::Reference::parse(payload)?.is_none() {
2468            validate_outbound_payload_envelope(payload)?;
2469        }
2470    }
2471    Ok(())
2472}
2473
2474fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2475    if commands.iter().any(|command| {
2476        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2477            && command
2478                .get("condition_wait_occurrence_id")
2479                .and_then(Value::as_str)
2480                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2481    }) {
2482        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2483    } else if commands.iter().any(|command| {
2484        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2485            && command.get("attribute_types").is_some()
2486    }) {
2487        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2488    } else if commands
2489        .iter()
2490        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2491    {
2492        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2493    } else if commands
2494        .iter()
2495        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2496    {
2497        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2498    } else if commands.iter().any(|command| {
2499        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2500    }) {
2501        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2502    } else {
2503        MINIMUM_WORKER_PROTOCOL_VERSION
2504    }
2505}
2506
2507fn workflow_completion_protocol_version_with_message_streams(
2508    commands: &[Value],
2509    has_message_stream_metadata: bool,
2510) -> &'static str {
2511    let command_protocol = workflow_completion_protocol_version(commands);
2512    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2513        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2514    } else {
2515        command_protocol
2516    }
2517}
2518
2519fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2520    match command_type {
2521        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2522        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2523        "start_service_operation" => Some("request_payload"),
2524        "upsert_memo" => Some("entries"),
2525        _ => None,
2526    }
2527}
2528
2529fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2530    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2531        return Err(untagged_payload_value());
2532    };
2533    validate_payload_codec(codec)?;
2534    decode_avro_value_blob(blob)?;
2535    Ok(())
2536}
2537
2538fn unsupported_payload_codec(codec: &str) -> Error {
2539    Error::Codec(format!(
2540        "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"
2541    ))
2542}
2543
2544fn untagged_payload_value() -> Error {
2545    Error::Codec(
2546        "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"
2547            .to_string(),
2548    )
2549}
2550
2551fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2552    let bytes = BASE64.decode(blob).map_err(|err| {
2553        Error::Codec(format!(
2554            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2555        ))
2556    })?;
2557
2558    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2559        return Err(unsupported_payload_codec("json"));
2560    }
2561
2562    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2563        return Err(Error::Codec(
2564            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2565        ));
2566    }
2567
2568    let fingerprint: [u8; 8] = bytes[2..10]
2569        .try_into()
2570        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2571    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2572        return Err(Error::Codec(format!(
2573            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2574            fingerprint
2575                .iter()
2576                .map(|byte| format!("{byte:02x}"))
2577                .collect::<String>()
2578        )));
2579    }
2580
2581    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2582    // The current fingerprint selects the current immutable schema, so reader
2583    // resolution would only re-walk the same recursive union. Future retained
2584    // writer fingerprints supply a distinct reader schema in this branch.
2585    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2586    if datum_reader.truncated {
2587        return Err(Error::Codec(
2588            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2589        ));
2590    }
2591    let datum = datum.map_err(|err| {
2592        Error::Codec(format!(
2593            "invalid_payload_framing: malformed Avro Value datum: {err}"
2594        ))
2595    })?;
2596    if datum_reader.remaining() != 0 {
2597        return Err(Error::Codec(format!(
2598            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2599            datum_reader.remaining()
2600        )));
2601    }
2602    avro_value_from_datum(datum)
2603}
2604
2605struct StrictAvroDatumReader<'a> {
2606    bytes: &'a [u8],
2607    offset: usize,
2608    truncated: bool,
2609}
2610
2611impl<'a> StrictAvroDatumReader<'a> {
2612    fn new(bytes: &'a [u8]) -> Self {
2613        Self {
2614            bytes,
2615            offset: 0,
2616            truncated: false,
2617        }
2618    }
2619
2620    fn remaining(&self) -> usize {
2621        self.bytes.len() - self.offset
2622    }
2623}
2624
2625impl Read for StrictAvroDatumReader<'_> {
2626    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2627        let count = buffer.len().min(self.remaining());
2628        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2629        self.offset += count;
2630        if count < buffer.len() {
2631            self.truncated = true;
2632        }
2633
2634        Ok(count)
2635    }
2636}
2637
2638fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2639    let branch = match value {
2640        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2641        AvroValue::Boolean(value) => AvroDatum::Union(
2642            1,
2643            Box::new(AvroDatum::Record(vec![(
2644                "boolean".to_string(),
2645                AvroDatum::Boolean(*value),
2646            )])),
2647        ),
2648        AvroValue::Long(value) => AvroDatum::Union(
2649            2,
2650            Box::new(AvroDatum::Record(vec![(
2651                "long".to_string(),
2652                AvroDatum::Long(*value),
2653            )])),
2654        ),
2655        AvroValue::Double(value) => {
2656            if !value.is_finite() {
2657                return Err(Error::Codec(
2658                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2659                ));
2660            }
2661            AvroDatum::Union(
2662                3,
2663                Box::new(AvroDatum::Record(vec![(
2664                    "double".to_string(),
2665                    AvroDatum::Double(*value),
2666                )])),
2667            )
2668        }
2669        AvroValue::Bytes(value) => AvroDatum::Union(
2670            4,
2671            Box::new(AvroDatum::Record(vec![(
2672                "bytes".to_string(),
2673                AvroDatum::Bytes(value.clone()),
2674            )])),
2675        ),
2676        AvroValue::String(value) => AvroDatum::Union(
2677            5,
2678            Box::new(AvroDatum::Record(vec![(
2679                "string".to_string(),
2680                AvroDatum::String(value.clone()),
2681            )])),
2682        ),
2683        AvroValue::Array(values) => AvroDatum::Union(
2684            6,
2685            Box::new(AvroDatum::Record(vec![(
2686                "items".to_string(),
2687                AvroDatum::Array(
2688                    values
2689                        .iter()
2690                        .map(avro_value_to_datum)
2691                        .collect::<Result<Vec<_>>>()?,
2692                ),
2693            )])),
2694        ),
2695        AvroValue::Map(values) => AvroDatum::Union(
2696            7,
2697            Box::new(AvroDatum::Record(vec![(
2698                "entries".to_string(),
2699                AvroDatum::Array(
2700                    values
2701                        .iter()
2702                        .map(|(key, value)| {
2703                            Ok(AvroDatum::Record(vec![
2704                                ("key".to_string(), AvroDatum::String(key.clone())),
2705                                ("value".to_string(), avro_value_to_datum(value)?),
2706                            ]))
2707                        })
2708                        .collect::<Result<Vec<_>>>()?,
2709                ),
2710            )])),
2711        ),
2712    };
2713    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2714}
2715
2716fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2717    let AvroDatum::Record(mut outer) = datum else {
2718        return Err(Error::Codec(
2719            "invalid_payload_framing: datum is not a Value record".to_string(),
2720        ));
2721    };
2722    let (_, branch) = outer
2723        .pop()
2724        .filter(|(name, _)| name == "value")
2725        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2726    let AvroDatum::Union(_, branch) = branch else {
2727        return Err(Error::Codec(
2728            "invalid_payload_framing: invalid Value union".to_string(),
2729        ));
2730    };
2731    match *branch {
2732        AvroDatum::Null => Ok(AvroValue::Null),
2733        AvroDatum::Record(mut fields) => {
2734            let (name, value) = fields.pop().ok_or_else(|| {
2735                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2736            })?;
2737            match (name.as_str(), value) {
2738                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2739                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2740                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2741                    Ok(AvroValue::Double(value))
2742                }
2743                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2744                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2745                ("items", AvroDatum::Array(values)) => values
2746                    .into_iter()
2747                    .map(avro_value_from_datum)
2748                    .collect::<Result<Vec<_>>>()
2749                    .map(AvroValue::Array),
2750                ("entries", AvroDatum::Map(values)) => values
2751                    .into_iter()
2752                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2753                    .collect::<Result<BTreeMap<_, _>>>()
2754                    .map(AvroValue::Map),
2755                _ => Err(Error::Codec(
2756                    "invalid_payload_framing: unknown Value branch".to_string(),
2757                )),
2758            }
2759        }
2760        _ => Err(Error::Codec(
2761            "invalid_payload_framing: invalid Value branch".to_string(),
2762        )),
2763    }
2764}
2765
2766fn avro_value_schema() -> Result<&'static Schema> {
2767    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2768        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2769            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2770    }) {
2771        Ok(schema) => Ok(schema),
2772        Err(message) => Err(Error::Codec(message.clone())),
2773    }
2774}
2775
2776fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2777    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2778        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2779        // have the same block representation when each ordered array record
2780        // contains the map key followed by its value, so this encoding-only
2781        // adaptation lets the official encoder retain BTreeMap wire order.
2782        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2783            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2784        let entries_schema = schema
2785            .pointer_mut("/fields/0/type/7/fields/0/type")
2786            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2787        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2788            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2789        }
2790        *entries_schema = json!({
2791            "type": "array",
2792            "items": {
2793                "type": "record",
2794                "name": "MapEntry",
2795                "fields": [
2796                    {"name": "key", "type": "string"},
2797                    {"name": "value", "type": "Value"}
2798                ]
2799            }
2800        });
2801        Schema::parse_str(&schema.to_string())
2802            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2803    }) {
2804        Ok(schema) => Ok(schema),
2805        Err(message) => Err(Error::Codec(message.clone())),
2806    }
2807}
2808
2809#[derive(Clone, Debug)]
2810pub struct Client {
2811    http: reqwest::Client,
2812    hydration_timeout: Duration,
2813    base_url: String,
2814    token: Option<String>,
2815    control_token: Option<String>,
2816    worker_token: Option<String>,
2817    namespace: String,
2818    max_external_payload_bytes: usize,
2819    worker_storage_admission: Option<WorkerStorageAdmission>,
2820    cooperative_worker_protocol: bool,
2821    worker_protocol_version: WorkerProtocolVersion,
2822    local_activities_enabled: bool,
2823    worker_sessions_enabled: bool,
2824    max_concurrent_worker_sessions: usize,
2825    worker_build_id: Option<String>,
2826    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2827    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2828}
2829
2830impl Client {
2831    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2832        Self::builder(base_url).build()
2833    }
2834
2835    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2836        ClientBuilder {
2837            base_url: base_url.into(),
2838            token: None,
2839            control_token: None,
2840            worker_token: None,
2841            namespace: "default".to_string(),
2842            timeout: Duration::from_secs(60),
2843            max_external_payload_bytes: 64 * 1024 * 1024,
2844            worker_protocol_version: WorkerProtocolVersion::default(),
2845        }
2846    }
2847
2848    pub async fn health(&self) -> Result<Value> {
2849        self.request_json(
2850            reqwest::Method::GET,
2851            "/health",
2852            RequestProtocol::ControlPlane,
2853            Option::<&Value>::None,
2854        )
2855        .await
2856    }
2857
2858    pub async fn cluster_info(&self) -> Result<Value> {
2859        self.request_json(
2860            reqwest::Method::GET,
2861            "/cluster/info",
2862            RequestProtocol::ControlPlane,
2863            Option::<&Value>::None,
2864        )
2865        .await
2866    }
2867
2868    pub async fn start_workflow<T: Serialize>(
2869        &self,
2870        workflow_type: &str,
2871        task_queue: &str,
2872        workflow_id: &str,
2873        input: T,
2874    ) -> Result<WorkflowHandle> {
2875        self.start_workflow_with_options(
2876            workflow_type,
2877            task_queue,
2878            workflow_id,
2879            WorkflowStartOptions::default(),
2880            input,
2881        )
2882        .await
2883    }
2884
2885    /// Start a workflow with explicit server-enforced execution and run
2886    /// deadlines.
2887    pub async fn start_workflow_with_options<T: Serialize>(
2888        &self,
2889        workflow_type: &str,
2890        task_queue: &str,
2891        workflow_id: &str,
2892        options: WorkflowStartOptions,
2893        input: T,
2894    ) -> Result<WorkflowHandle> {
2895        options.validate()?;
2896        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2897        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2898        let body = json!({
2899            "workflow_id": workflow_id,
2900            "workflow_type": workflow_type,
2901            "task_queue": task_queue,
2902            "input": input_envelope,
2903            "execution_timeout_seconds": options.execution_timeout_seconds,
2904            "run_timeout_seconds": options.run_timeout_seconds
2905        });
2906
2907        let data: Value = self
2908            .request_json(
2909                reqwest::Method::POST,
2910                "/workflows",
2911                RequestProtocol::ControlPlane,
2912                Some(&body),
2913            )
2914            .await?;
2915
2916        Ok(WorkflowHandle {
2917            client: self.clone(),
2918            workflow_id: data
2919                .get("workflow_id")
2920                .and_then(Value::as_str)
2921                .unwrap_or(workflow_id)
2922                .to_string(),
2923            run_id: data
2924                .get("run_id")
2925                .and_then(Value::as_str)
2926                .map(str::to_string),
2927            workflow_type: data
2928                .get("workflow_type")
2929                .and_then(Value::as_str)
2930                .unwrap_or(workflow_type)
2931                .to_string(),
2932        })
2933    }
2934
2935    pub async fn signal_workflow<T: Serialize>(
2936        &self,
2937        workflow_id: &str,
2938        signal_name: &str,
2939        input: T,
2940    ) -> Result<Value> {
2941        self.signal_workflow_target(workflow_id, None, signal_name, input)
2942            .await
2943    }
2944
2945    /// Append one idempotently identified item to an instance-scoped input stream.
2946    pub async fn append_message_stream<T: Serialize>(
2947        &self,
2948        workflow_id: &str,
2949        stream_name: &str,
2950        message_id: &str,
2951        input: T,
2952    ) -> Result<Value> {
2953        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2954        let body = json!({
2955            "message_id": message_id,
2956            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2957        });
2958        self.request_json(
2959            reqwest::Method::POST,
2960            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2961            RequestProtocol::ControlPlane,
2962            Some(&body),
2963        )
2964        .await
2965    }
2966
2967    /// Signal only if `run_id` is still the current run for this instance.
2968    pub async fn signal_workflow_run<T: Serialize>(
2969        &self,
2970        workflow_id: &str,
2971        run_id: &str,
2972        signal_name: &str,
2973        input: T,
2974    ) -> Result<Value> {
2975        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2976            .await
2977    }
2978
2979    async fn signal_workflow_target<T: Serialize>(
2980        &self,
2981        workflow_id: &str,
2982        run_id: Option<&str>,
2983        signal_name: &str,
2984        input: T,
2985    ) -> Result<Value> {
2986        validate_user_signal_name(signal_name)?;
2987        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2988        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2989        let body = json!({
2990            "input": input_envelope
2991        });
2992        let path = match run_id {
2993            Some(run_id) => {
2994                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
2995            }
2996            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
2997        };
2998        self.request_json(
2999            reqwest::Method::POST,
3000            &path,
3001            RequestProtocol::ControlPlane,
3002            Some(&body),
3003        )
3004        .await
3005    }
3006
3007    /// Close the current run as cancelled immediately.
3008    ///
3009    /// Server revokes open tasks and timers without resuming workflow code for
3010    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3011    /// request on a supporting runtime and opted-in worker.
3012    pub async fn cancel_workflow(
3013        &self,
3014        workflow_id: &str,
3015        options: WorkflowCommandOptions,
3016    ) -> Result<WorkflowCommandResult> {
3017        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3018            .await
3019    }
3020
3021    /// Close the selected run as cancelled, only if `run_id` is still current.
3022    pub async fn cancel_workflow_run(
3023        &self,
3024        workflow_id: &str,
3025        run_id: &str,
3026        options: WorkflowCommandOptions,
3027    ) -> Result<WorkflowCommandResult> {
3028        self.workflow_command(
3029            workflow_id,
3030            Some(run_id),
3031            WorkflowCommandKind::Cancel,
3032            options,
3033        )
3034        .await
3035    }
3036
3037    /// Forcefully terminate the current run for an instance.
3038    pub async fn terminate_workflow(
3039        &self,
3040        workflow_id: &str,
3041        options: WorkflowCommandOptions,
3042    ) -> Result<WorkflowCommandResult> {
3043        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3044            .await
3045    }
3046
3047    /// Forcefully terminate only if `run_id` is still current.
3048    pub async fn terminate_workflow_run(
3049        &self,
3050        workflow_id: &str,
3051        run_id: &str,
3052        options: WorkflowCommandOptions,
3053    ) -> Result<WorkflowCommandResult> {
3054        self.workflow_command(
3055            workflow_id,
3056            Some(run_id),
3057            WorkflowCommandKind::Terminate,
3058            options,
3059        )
3060        .await
3061    }
3062
3063    /// Continue a failed run from its recorded activity failure boundary.
3064    pub async fn redrive_workflow_run(
3065        &self,
3066        workflow_id: &str,
3067        failed_run_id: &str,
3068        request_id: Option<&str>,
3069    ) -> Result<WorkflowRedriveResult> {
3070        let body = request_id
3071            .map(|id| json!({"request_id": id}))
3072            .unwrap_or_else(|| json!({}));
3073        let data: Value = self
3074            .request_json(
3075                reqwest::Method::POST,
3076                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3077                RequestProtocol::ControlPlane,
3078                Some(&body),
3079            )
3080            .await?;
3081        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3082            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3083        {
3084            return Err(Error::Codec(
3085                "redrive response was not accepted".to_string(),
3086            ));
3087        }
3088        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3089            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3090        {
3091            return Err(Error::Codec(
3092                "redrive response does not match the requested source run".to_string(),
3093            ));
3094        }
3095        let run_id = data
3096            .get("run_id")
3097            .and_then(Value::as_str)
3098            .filter(|id| !id.is_empty() && *id != failed_run_id)
3099            .ok_or_else(|| {
3100                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3101            })?;
3102        let resume_step_sequence = data
3103            .get("resume_step_sequence")
3104            .and_then(Value::as_u64)
3105            .filter(|sequence| *sequence > 0)
3106            .ok_or_else(|| {
3107                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3108            })?;
3109        Ok(WorkflowRedriveResult {
3110            workflow_id: workflow_id.to_string(),
3111            source_run_id: failed_run_id.to_string(),
3112            run_id: run_id.to_string(),
3113            resume_step_sequence,
3114            raw: data,
3115        })
3116    }
3117
3118    async fn workflow_command(
3119        &self,
3120        workflow_id: &str,
3121        run_id: Option<&str>,
3122        command: WorkflowCommandKind,
3123        options: WorkflowCommandOptions,
3124    ) -> Result<WorkflowCommandResult> {
3125        let path = match run_id {
3126            Some(run_id) => format!(
3127                "/workflows/{workflow_id}/runs/{run_id}/{}",
3128                command.as_str()
3129            ),
3130            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3131        };
3132        let data = match self
3133            .request_json(
3134                reqwest::Method::POST,
3135                &path,
3136                RequestProtocol::ControlPlane,
3137                Some(&options),
3138            )
3139            .await
3140        {
3141            Ok(data) => data,
3142            Err(Error::Http { status, body }) => {
3143                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3144                    command,
3145                    status,
3146                    body,
3147                    workflow_id,
3148                    run_id,
3149                )));
3150            }
3151            Err(error) => return Err(error),
3152        };
3153
3154        Ok(workflow_command_result(command, data, workflow_id, run_id))
3155    }
3156
3157    /// Execute a named, read-only query against a running or completed workflow.
3158    ///
3159    /// Arguments and results use the platform payload envelope. Server and
3160    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3161    /// reason, HTTP status, and original response body.
3162    pub async fn query_workflow<T: Serialize>(
3163        &self,
3164        workflow_id: &str,
3165        query_name: &str,
3166        input: T,
3167    ) -> Result<Value> {
3168        self.query_workflow_target(workflow_id, None, query_name, input)
3169            .await
3170    }
3171
3172    /// Query only if `run_id` is still current, preventing accidental retargeting.
3173    pub async fn query_workflow_run<T: Serialize>(
3174        &self,
3175        workflow_id: &str,
3176        run_id: &str,
3177        query_name: &str,
3178        input: T,
3179    ) -> Result<Value> {
3180        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3181            .await
3182    }
3183
3184    /// Query a workflow and return the lossless fixed Avro Value result.
3185    pub async fn query_workflow_avro_value<T: Serialize>(
3186        &self,
3187        workflow_id: &str,
3188        query_name: &str,
3189        input: T,
3190    ) -> Result<AvroValue> {
3191        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3192            .await
3193    }
3194
3195    /// Query a selected run and return the lossless fixed Avro Value result.
3196    pub async fn query_workflow_run_avro_value<T: Serialize>(
3197        &self,
3198        workflow_id: &str,
3199        run_id: &str,
3200        query_name: &str,
3201        input: T,
3202    ) -> Result<AvroValue> {
3203        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3204            .await
3205    }
3206
3207    async fn query_workflow_avro_value_target<T: Serialize>(
3208        &self,
3209        workflow_id: &str,
3210        run_id: Option<&str>,
3211        query_name: &str,
3212        input: T,
3213    ) -> Result<AvroValue> {
3214        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3215        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3216        let path = match run_id {
3217            Some(run_id) => {
3218                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3219            }
3220            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3221        };
3222        let response: Value = match self
3223            .request_json(
3224                reqwest::Method::POST,
3225                &path,
3226                RequestProtocol::ControlPlane,
3227                Some(&body),
3228            )
3229            .await
3230        {
3231            Ok(response) => response,
3232            Err(Error::Http { status, body }) => {
3233                return Err(Error::QueryFailed(query_failure(status, body)));
3234            }
3235            Err(error) => return Err(error),
3236        };
3237
3238        let envelope = response
3239            .get("result_envelope")
3240            .filter(|envelope| !envelope.is_null())
3241            .ok_or_else(|| {
3242                Error::Codec(
3243                    "missing_payload_envelope: typed query result requires result_envelope"
3244                        .to_string(),
3245                )
3246            })?;
3247        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3248    }
3249
3250    async fn query_workflow_target<T: Serialize>(
3251        &self,
3252        workflow_id: &str,
3253        run_id: Option<&str>,
3254        query_name: &str,
3255        input: T,
3256    ) -> Result<Value> {
3257        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3258        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3259        let body = json!({
3260            "input": input_envelope
3261        });
3262        let path = match run_id {
3263            Some(run_id) => {
3264                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3265            }
3266            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3267        };
3268        let response: Value = match self
3269            .request_json(
3270                reqwest::Method::POST,
3271                &path,
3272                RequestProtocol::ControlPlane,
3273                Some(&body),
3274            )
3275            .await
3276        {
3277            Ok(response) => response,
3278            Err(Error::Http { status, body }) => {
3279                return Err(Error::QueryFailed(query_failure(status, body)));
3280            }
3281            Err(error) => return Err(error),
3282        };
3283
3284        if let Some(envelope) = response
3285            .get("result_envelope")
3286            .filter(|envelope| !envelope.is_null())
3287        {
3288            return decode_wire_value(envelope, DEFAULT_CODEC);
3289        }
3290
3291        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3292    }
3293
3294    /// Send a synchronous update using fixed Avro Value arguments.
3295    pub async fn update_workflow<T: Serialize>(
3296        &self,
3297        workflow_id: &str,
3298        update_name: &str,
3299        input: T,
3300        request_id: Option<&str>,
3301    ) -> Result<Value> {
3302        let response = self
3303            .update_workflow_response(workflow_id, update_name, input, request_id)
3304            .await?;
3305        if let Some(envelope) = response
3306            .get("result_envelope")
3307            .filter(|envelope| !envelope.is_null())
3308        {
3309            return decode_wire_value(envelope, DEFAULT_CODEC);
3310        }
3311        Ok(response.get("result").cloned().unwrap_or(response))
3312    }
3313
3314    /// Send a synchronous update and retain a bytes-capable Avro result.
3315    pub async fn update_workflow_avro_value<T: Serialize>(
3316        &self,
3317        workflow_id: &str,
3318        update_name: &str,
3319        input: T,
3320        request_id: Option<&str>,
3321    ) -> Result<AvroValue> {
3322        let response = self
3323            .update_workflow_response(workflow_id, update_name, input, request_id)
3324            .await?;
3325        let envelope = response
3326            .get("result_envelope")
3327            .filter(|envelope| !envelope.is_null())
3328            .ok_or_else(|| {
3329                Error::Codec(
3330                    "missing_payload_envelope: typed update result requires result_envelope"
3331                        .to_string(),
3332                )
3333            })?;
3334        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3335    }
3336
3337    async fn update_workflow_response<T: Serialize>(
3338        &self,
3339        workflow_id: &str,
3340        update_name: &str,
3341        input: T,
3342        request_id: Option<&str>,
3343    ) -> Result<Value> {
3344        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3345        let mut body = json!({
3346            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3347            "wait_for": "completed",
3348        });
3349        if let Some(request_id) = request_id {
3350            body["request_id"] = json!(request_id);
3351        }
3352        self.request_json(
3353            reqwest::Method::POST,
3354            &format!("/workflows/{workflow_id}/update/{update_name}"),
3355            RequestProtocol::ControlPlane,
3356            Some(&body),
3357        )
3358        .await
3359    }
3360
3361    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3362        let path = format!("/workflows/{workflow_id}");
3363        let mut data: WorkflowDescription = self
3364            .request_json(
3365                reqwest::Method::GET,
3366                &path,
3367                RequestProtocol::ControlPlane,
3368                Option::<&Value>::None,
3369            )
3370            .await?;
3371        data.decode_payloads()?;
3372        Ok(data)
3373    }
3374
3375    /// Describe one selected run, including historical terminal runs.
3376    pub async fn describe_workflow_run(
3377        &self,
3378        workflow_id: &str,
3379        run_id: &str,
3380    ) -> Result<WorkflowDescription> {
3381        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3382        let mut data: WorkflowDescription = self
3383            .request_json(
3384                reqwest::Method::GET,
3385                &path,
3386                RequestProtocol::ControlPlane,
3387                Option::<&Value>::None,
3388            )
3389            .await?;
3390        data.decode_payloads()?;
3391        Ok(data)
3392    }
3393
3394    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3395        let mut path = format!(
3396            "/workflows/{}/runs/{}/streams",
3397            percent_encode_path_segment(workflow_id),
3398            percent_encode_path_segment(run_id),
3399        );
3400        if let Some(stream_name) = stream_name {
3401            path.push('/');
3402            path.push_str(&percent_encode_path_segment(stream_name));
3403        }
3404        path
3405    }
3406
3407    /// List the run-scoped output streams already opened by a workflow.
3408    pub async fn list_workflow_streams(
3409        &self,
3410        workflow_id: &str,
3411        run_id: &str,
3412    ) -> Result<Vec<WorkflowStreamDescription>> {
3413        let response: WorkflowStreamListResponse = self
3414            .request_json(
3415                reqwest::Method::GET,
3416                &Self::workflow_stream_path(workflow_id, run_id, None),
3417                RequestProtocol::ControlPlane,
3418                Option::<&Value>::None,
3419            )
3420            .await?;
3421        Ok(response.streams)
3422    }
3423
3424    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3425    pub async fn describe_workflow_stream(
3426        &self,
3427        workflow_id: &str,
3428        run_id: &str,
3429        stream_name: &str,
3430    ) -> Result<WorkflowStreamDescription> {
3431        let response: WorkflowStreamDescriptionResponse = self
3432            .request_json(
3433                reqwest::Method::GET,
3434                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3435                RequestProtocol::ControlPlane,
3436                Option::<&Value>::None,
3437            )
3438            .await?;
3439        Ok(response.stream)
3440    }
3441
3442    /// Read one bounded page beginning at a zero-based offset.
3443    ///
3444    /// Delivery is at least once: persist `next_offset` only after processing
3445    /// the page. The future is cancellation-safe; dropping it cancels the
3446    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3447    /// service contract.
3448    pub async fn subscribe_workflow_stream(
3449        &self,
3450        workflow_id: &str,
3451        run_id: &str,
3452        stream_name: &str,
3453        from_offset: u64,
3454        max_items: usize,
3455        wait: Duration,
3456    ) -> Result<WorkflowStreamPage> {
3457        let max_items = max_items.clamp(1, 500);
3458        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3459        let path = format!(
3460            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3461            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3462        );
3463        let response: WorkflowStreamPageResponse = self
3464            .request_json_with_timeout(
3465                reqwest::Method::GET,
3466                &path,
3467                RequestProtocol::ControlPlane,
3468                Option::<&Value>::None,
3469                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3470            )
3471            .await?;
3472
3473        let items = response
3474            .items
3475            .into_iter()
3476            .map(|raw| {
3477                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3478                let envelope = raw.get("payload").cloned();
3479                let payload = envelope
3480                    .as_ref()
3481                    .filter(|value| value.get("blob").is_some())
3482                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3483                    .transpose()?
3484                    .map(AvroValue::into_json)
3485                    .transpose()?;
3486                Ok(WorkflowStreamItem {
3487                    offset,
3488                    payload,
3489                    payload_envelope: envelope,
3490                    payload_reference: raw
3491                        .get("payload_reference")
3492                        .and_then(Value::as_str)
3493                        .map(str::to_string),
3494                    payload_codec: raw
3495                        .get("payload_codec")
3496                        .and_then(Value::as_str)
3497                        .map(str::to_string),
3498                    idempotency_key: raw
3499                        .get("idempotency_key")
3500                        .and_then(Value::as_str)
3501                        .map(str::to_string),
3502                    item_type: raw
3503                        .get("item_type")
3504                        .and_then(Value::as_str)
3505                        .map(str::to_string),
3506                    content_type: raw
3507                        .get("content_type")
3508                        .and_then(Value::as_str)
3509                        .map(str::to_string),
3510                    origin: raw
3511                        .get("origin")
3512                        .and_then(Value::as_str)
3513                        .map(str::to_string),
3514                    origin_reference: raw
3515                        .get("origin_reference")
3516                        .and_then(Value::as_str)
3517                        .map(str::to_string),
3518                    emitted_at: raw
3519                        .get("emitted_at")
3520                        .and_then(Value::as_str)
3521                        .map(str::to_string),
3522                    raw,
3523                })
3524            })
3525            .collect::<Result<Vec<_>>>()?;
3526        Ok(WorkflowStreamPage {
3527            stream: response.stream,
3528            items,
3529            next_offset: response.next_offset,
3530            terminal: response.terminal,
3531        })
3532    }
3533
3534    /// Append inline Avro envelopes or opaque external payload references.
3535    pub async fn append_workflow_stream(
3536        &self,
3537        workflow_id: &str,
3538        run_id: &str,
3539        stream_name: &str,
3540        items: &[WorkflowStreamAppendItem],
3541        max_pending_items: Option<u64>,
3542    ) -> Result<WorkflowStreamAppendResult> {
3543        if items.is_empty() {
3544            return Err(Error::Codec(
3545                "workflow_stream_items_empty: append requires at least one item".to_string(),
3546            ));
3547        }
3548        let mut body = json!({
3549            "items": items
3550                .iter()
3551                .map(|item| item.wire_value(None))
3552                .collect::<Vec<_>>(),
3553        });
3554        if let Some(max_pending_items) = max_pending_items {
3555            if max_pending_items == 0 {
3556                return Err(Error::Codec(
3557                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3558                        .to_string(),
3559                ));
3560            }
3561            body["max_pending_items"] = json!(max_pending_items);
3562        }
3563        let response: WorkflowStreamAppendResponse = self
3564            .request_json(
3565                reqwest::Method::POST,
3566                &format!(
3567                    "{}/items",
3568                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3569                ),
3570                RequestProtocol::ControlPlane,
3571                Some(&body),
3572            )
3573            .await?;
3574        Ok(WorkflowStreamAppendResult {
3575            stream: response.stream,
3576            accepted_offsets: response.accepted_offsets,
3577            accepted: response.accepted,
3578            deduped: response.deduped,
3579        })
3580    }
3581
3582    /// Close a stream, or mark it errored when `error_reason` is supplied.
3583    pub async fn close_workflow_stream(
3584        &self,
3585        workflow_id: &str,
3586        run_id: &str,
3587        stream_name: &str,
3588        error_reason: Option<&str>,
3589        retention_seconds: Option<u64>,
3590    ) -> Result<WorkflowStreamDescription> {
3591        let mut body = json!({});
3592        if let Some(error_reason) = error_reason {
3593            body["error_reason"] = json!(error_reason);
3594        }
3595        if let Some(retention_seconds) = retention_seconds {
3596            if retention_seconds == 0 {
3597                return Err(Error::Codec(
3598                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3599                        .to_string(),
3600                ));
3601            }
3602            body["retention_seconds"] = json!(retention_seconds);
3603        }
3604        let response: WorkflowStreamDescriptionResponse = self
3605            .request_json(
3606                reqwest::Method::POST,
3607                &format!(
3608                    "{}/close",
3609                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3610                ),
3611                RequestProtocol::ControlPlane,
3612                Some(&body),
3613            )
3614            .await?;
3615        Ok(response.stream)
3616    }
3617
3618    pub async fn register_worker(
3619        &self,
3620        worker_id: &str,
3621        task_queue: &str,
3622        supported_workflow_types: Vec<String>,
3623        supported_activity_types: Vec<String>,
3624        max_concurrent_workflow_tasks: usize,
3625        max_concurrent_activity_tasks: usize,
3626    ) -> Result<RegisterWorkerResponse> {
3627        self.register_worker_with_capabilities(
3628            worker_id,
3629            task_queue,
3630            supported_workflow_types,
3631            supported_activity_types,
3632            max_concurrent_workflow_tasks,
3633            max_concurrent_activity_tasks,
3634            Vec::new(),
3635        )
3636        .await
3637    }
3638
3639    /// Register a worker and explicitly advertise additive worker capabilities.
3640    pub async fn register_worker_with_capabilities(
3641        &self,
3642        worker_id: &str,
3643        task_queue: &str,
3644        supported_workflow_types: Vec<String>,
3645        supported_activity_types: Vec<String>,
3646        max_concurrent_workflow_tasks: usize,
3647        max_concurrent_activity_tasks: usize,
3648        capabilities: Vec<String>,
3649    ) -> Result<RegisterWorkerResponse> {
3650        self.register_worker_with_command_contracts(
3651            worker_id,
3652            task_queue,
3653            supported_workflow_types,
3654            supported_activity_types,
3655            max_concurrent_workflow_tasks,
3656            max_concurrent_activity_tasks,
3657            capabilities,
3658            Value::Object(serde_json::Map::new()),
3659        )
3660        .await
3661    }
3662
3663    /// Register a worker and advertise its named query and update handlers.
3664    ///
3665    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3666    /// so a workflow contract with a non-empty or malformed
3667    /// `update_validators` declaration returns
3668    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3669    #[allow(clippy::too_many_arguments)]
3670    pub async fn register_worker_with_command_contracts(
3671        &self,
3672        worker_id: &str,
3673        task_queue: &str,
3674        supported_workflow_types: Vec<String>,
3675        supported_activity_types: Vec<String>,
3676        max_concurrent_workflow_tasks: usize,
3677        max_concurrent_activity_tasks: usize,
3678        capabilities: Vec<String>,
3679        workflow_command_contracts: Value,
3680    ) -> Result<RegisterWorkerResponse> {
3681        self.register_worker_with_definition_fingerprints(
3682            worker_id,
3683            task_queue,
3684            supported_workflow_types,
3685            supported_activity_types,
3686            max_concurrent_workflow_tasks,
3687            max_concurrent_activity_tasks,
3688            capabilities,
3689            workflow_command_contracts,
3690            None,
3691        )
3692        .await
3693    }
3694
3695    #[allow(clippy::too_many_arguments)]
3696    async fn register_worker_with_definition_fingerprints(
3697        &self,
3698        worker_id: &str,
3699        task_queue: &str,
3700        supported_workflow_types: Vec<String>,
3701        supported_activity_types: Vec<String>,
3702        max_concurrent_workflow_tasks: usize,
3703        max_concurrent_activity_tasks: usize,
3704        capabilities: Vec<String>,
3705        workflow_command_contracts: Value,
3706        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3707    ) -> Result<RegisterWorkerResponse> {
3708        if let Some(contracts) = workflow_command_contracts.as_object() {
3709            for (workflow_type, contract) in contracts {
3710                let Some(update_validators) = contract.get("update_validators") else {
3711                    continue;
3712                };
3713                if !update_validators
3714                    .as_array()
3715                    .is_some_and(|validators| validators.is_empty())
3716                {
3717                    return Err(Error::UnsupportedUpdateValidators {
3718                        workflow_type: workflow_type.clone(),
3719                    });
3720                }
3721            }
3722        }
3723
3724        let mut body = json!({
3725            "worker_id": worker_id,
3726            "task_queue": task_queue,
3727            "runtime": "rust",
3728            "sdk_version": SDK_VERSION,
3729            "supported_workflow_types": supported_workflow_types,
3730            "supported_activity_types": supported_activity_types,
3731            "capabilities": capabilities,
3732            "capability_manifest": portable_worker_affinity_capability_manifest(),
3733            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3734            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3735        });
3736        if let Some(build_id) = &self.worker_build_id {
3737            if build_id.is_empty() || build_id.len() > 255 {
3738                return Err(Error::WorkerLoop(
3739                    "worker build ID must contain 1 to 255 bytes".into(),
3740                ));
3741            }
3742            body["build_id"] = json!(build_id);
3743        }
3744        if self.sticky_cache.is_some() {
3745            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
3746                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
3747                "implementation":"bounded_durable_history_cache"});
3748        }
3749        if self.local_activities_enabled {
3750            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3751                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3752        }
3753        if self.worker_sessions_enabled {
3754            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3755                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3756            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3757        }
3758        if workflow_command_contracts
3759            .as_object()
3760            .is_some_and(|contracts| !contracts.is_empty())
3761        {
3762            body["workflow_command_contracts"] = workflow_command_contracts;
3763        }
3764        if let Some(fingerprints) = workflow_definition_fingerprints {
3765            body["workflow_definition_fingerprints"] = json!(fingerprints);
3766        }
3767
3768        let response: Value = self
3769            .request_json(
3770                reqwest::Method::POST,
3771                "/worker/register",
3772                RequestProtocol::DefaultWorker,
3773                Some(&body),
3774            )
3775            .await?;
3776        if self.sticky_cache.is_some() {
3777            self.confirm_sticky_registration(&response, worker_id, task_queue)
3778                .await?;
3779        }
3780        if self.local_activities_enabled || self.worker_sessions_enabled {
3781            let compatible = response["registered"].as_bool() == Some(true)
3782                && response["worker_id"].as_str() == Some(worker_id)
3783                && response["namespace"].as_str() == Some(self.namespace.as_str())
3784                && response["task_queue"].as_str() == Some(task_queue)
3785                && response["protocol_version"]
3786                    .as_str()
3787                    .and_then(|version| version.strip_prefix("1."))
3788                    .and_then(|minor| minor.parse::<u64>().ok())
3789                    .is_some_and(|minor| minor >= 18)
3790                && (!self.local_activities_enabled
3791                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3792                        == Some(true))
3793                && (!self.worker_sessions_enabled
3794                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3795                        == Some(true)
3796                        && response["capabilities"].as_array().is_some_and(|accepted| {
3797                            capabilities.iter().all(|capability| {
3798                                accepted
3799                                    .iter()
3800                                    .any(|value| value.as_str() == Some(capability.as_str()))
3801                            })
3802                        })));
3803            if !compatible {
3804                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3805                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3806                } else {
3807                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3808                });
3809                if response["registered"] == true
3810                    && response["worker_id"].as_str() == Some(worker_id)
3811                {
3812                    if let Err(deregistration) =
3813                        self.deregister_worker_registration(worker_id).await
3814                    {
3815                        return Err(Error::WorkerShutdown {
3816                            primary: Box::new(error),
3817                            deregistration: Box::new(deregistration),
3818                        });
3819                    }
3820                }
3821                return Err(error);
3822            }
3823        }
3824        if self.cooperative_worker_protocol {
3825            let compatible = response["registered"].as_bool() == Some(true)
3826                && response["worker_id"].as_str() == Some(worker_id)
3827                && response["namespace"].as_str() == Some(self.namespace.as_str())
3828                && response["task_queue"].as_str() == Some(task_queue)
3829                && response["protocol_version"]
3830                    .as_str()
3831                    .is_some_and(cooperative_cancellation::supports_protocol)
3832                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3833                    == Some(true)
3834                && response["capabilities"].as_array().is_some_and(|accepted| {
3835                    capabilities.iter().all(|capability| {
3836                        accepted
3837                            .iter()
3838                            .any(|value| value.as_str() == Some(capability.as_str()))
3839                    })
3840                });
3841            if !compatible {
3842                let error = Error::CooperativeCancellationUnavailable(
3843                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3844                );
3845                if response["registered"].as_bool() == Some(true)
3846                    && response["worker_id"].as_str() == Some(worker_id)
3847                {
3848                    if let Err(deregistration) =
3849                        self.deregister_worker_registration(worker_id).await
3850                    {
3851                        return Err(Error::WorkerShutdown {
3852                            primary: Box::new(error),
3853                            deregistration: Box::new(deregistration),
3854                        });
3855                    }
3856                }
3857                return Err(error);
3858            }
3859        }
3860        Ok(serde_json::from_value(response)?)
3861    }
3862
3863    /// Gracefully remove one worker's registration through the worker plane.
3864    ///
3865    /// This operation is separate from operator-facing worker management. It
3866    /// uses worker-protocol authentication and returns the server's lease
3867    /// recovery result.
3868    pub async fn deregister_worker_registration(
3869        &self,
3870        worker_id: &str,
3871    ) -> Result<WorkerDeregistrationEnvelope> {
3872        let path = format!(
3873            "/worker/registrations/{}",
3874            percent_encode_path_segment(worker_id)
3875        );
3876        self.request_json(
3877            reqwest::Method::DELETE,
3878            &path,
3879            RequestProtocol::DefaultWorker,
3880            Option::<&Value>::None,
3881        )
3882        .await
3883    }
3884
3885    /// Long-poll for an ephemeral, read-only workflow query task.
3886    pub async fn poll_query_task(
3887        &self,
3888        worker_id: &str,
3889        task_queue: &str,
3890        timeout: Duration,
3891    ) -> Result<Option<QueryTask>> {
3892        Ok(self
3893            .poll_query_task_response(worker_id, task_queue, timeout)
3894            .await?
3895            .task)
3896    }
3897
3898    /// Poll a query task while preserving server stop and drain metadata.
3899    pub async fn poll_query_task_response(
3900        &self,
3901        worker_id: &str,
3902        task_queue: &str,
3903        timeout: Duration,
3904    ) -> Result<PollQueryTaskResponse> {
3905        let poll_request_id = unique_request_id("rust-query-poll");
3906        self.poll_query_task_response_with_request_id(
3907            worker_id,
3908            task_queue,
3909            timeout,
3910            &poll_request_id,
3911            1,
3912        )
3913        .await
3914    }
3915
3916    async fn poll_query_task_response_with_request_id(
3917        &self,
3918        worker_id: &str,
3919        task_queue: &str,
3920        timeout: Duration,
3921        poll_request_id: &str,
3922        transport_retries: usize,
3923    ) -> Result<PollQueryTaskResponse> {
3924        let timeout_seconds = long_poll_timeout_seconds(timeout);
3925        let body = json!({
3926            "worker_id": worker_id,
3927            "task_queue": task_queue,
3928            "poll_request_id": poll_request_id,
3929            "timeout_seconds": timeout_seconds,
3930        });
3931        self.poll_request_json(
3932            "/worker/query-tasks/poll",
3933            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3934            &body,
3935            timeout + Duration::from_secs(5),
3936            transport_retries,
3937        )
3938        .await
3939    }
3940
3941    /// Complete a query task without appending workflow history.
3942    pub async fn complete_query_task<T: Serialize>(
3943        &self,
3944        query_task_id: &str,
3945        lease_owner: &str,
3946        query_task_attempt: u64,
3947        result: T,
3948        codec: &str,
3949    ) -> Result<Value> {
3950        let typed_result = AvroValue::from_serialize(&result)?;
3951        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3952        self.complete_query_task_with_envelope(
3953            query_task_id,
3954            lease_owner,
3955            query_task_attempt,
3956            typed_result.into_json()?,
3957            result_envelope,
3958        )
3959        .await
3960    }
3961
3962    async fn complete_query_task_with_envelope(
3963        &self,
3964        query_task_id: &str,
3965        lease_owner: &str,
3966        query_task_attempt: u64,
3967        result: Value,
3968        result_envelope: Value,
3969    ) -> Result<Value> {
3970        let body = json!({
3971            "lease_owner": lease_owner,
3972            "query_task_attempt": query_task_attempt,
3973            "result": result,
3974            "result_envelope": result_envelope,
3975        });
3976        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3977        let response = self
3978            .request_json(
3979                reqwest::Method::POST,
3980                &path,
3981                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3982                Some(&body),
3983            )
3984            .await;
3985        query_task_response(response)
3986    }
3987
3988    /// Report a stable machine-readable query-task failure.
3989    pub async fn fail_query_task(
3990        &self,
3991        query_task_id: &str,
3992        lease_owner: &str,
3993        query_task_attempt: u64,
3994        message: impl Into<String>,
3995        reason: impl Into<String>,
3996        failure_type: impl Into<String>,
3997    ) -> Result<Value> {
3998        let body = json!({
3999            "lease_owner": lease_owner,
4000            "query_task_attempt": query_task_attempt,
4001            "failure": {
4002                "message": message.into(),
4003                "reason": reason.into(),
4004                "type": failure_type.into(),
4005            }
4006        });
4007        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4008        let response = self
4009            .request_json(
4010                reqwest::Method::POST,
4011                &path,
4012                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4013                Some(&body),
4014            )
4015            .await;
4016        query_task_response(response)
4017    }
4018
4019    pub async fn heartbeat_worker(
4020        &self,
4021        worker_id: &str,
4022        workflow_available: usize,
4023        activity_available: usize,
4024    ) -> Result<Value> {
4025        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4026            .await
4027    }
4028
4029    async fn heartbeat_worker_with_sessions(
4030        &self,
4031        worker_id: &str,
4032        workflow_available: usize,
4033        activity_available: usize,
4034        session_available: Option<usize>,
4035    ) -> Result<Value> {
4036        let mut body = json!({
4037            "worker_id": worker_id,
4038            "task_slots": {
4039                "workflow_available": workflow_available,
4040                "activity_available": activity_available
4041            },
4042            "process_metrics": {
4043                "process_id": std::process::id(),
4044                "process_uptime_seconds": 0
4045            }
4046        });
4047
4048        if let Some(available) = session_available {
4049            body["task_slots"]["session_available"] = json!(available);
4050        }
4051
4052        self.request_json(
4053            reqwest::Method::POST,
4054            "/worker/heartbeat",
4055            RequestProtocol::DefaultWorker,
4056            Some(&body),
4057        )
4058        .await
4059    }
4060
4061    pub async fn poll_workflow_task(
4062        &self,
4063        worker_id: &str,
4064        task_queue: &str,
4065        timeout: Duration,
4066    ) -> Result<Option<WorkflowTask>> {
4067        Ok(self
4068            .poll_workflow_task_response(worker_id, task_queue, timeout)
4069            .await?
4070            .task)
4071    }
4072
4073    pub async fn poll_workflow_task_response(
4074        &self,
4075        worker_id: &str,
4076        task_queue: &str,
4077        timeout: Duration,
4078    ) -> Result<PollWorkflowTaskResponse> {
4079        let poll_request_id = unique_request_id("rust-workflow-poll");
4080        self.poll_workflow_task_response_with_request_id(
4081            worker_id,
4082            task_queue,
4083            timeout,
4084            &poll_request_id,
4085            1,
4086        )
4087        .await
4088    }
4089
4090    async fn poll_workflow_task_response_with_request_id(
4091        &self,
4092        worker_id: &str,
4093        task_queue: &str,
4094        timeout: Duration,
4095        poll_request_id: &str,
4096        transport_retries: usize,
4097    ) -> Result<PollWorkflowTaskResponse> {
4098        let body = json!({
4099            "worker_id": worker_id,
4100            "task_queue": task_queue,
4101            "poll_request_id": poll_request_id,
4102            "timeout_seconds": long_poll_timeout_seconds(timeout),
4103            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4104        });
4105        let mut wire: Value = self
4106            .poll_request_json_unresolved(
4107                "/worker/workflow-tasks/poll",
4108                RequestProtocol::DefaultWorker,
4109                &body,
4110                timeout + Duration::from_secs(5),
4111                transport_retries,
4112            )
4113            .await?;
4114        let claim =
4115            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4116        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4117            self.resolve_runtime_payloads(
4118                &mut wire,
4119                "/worker/workflow-tasks/poll",
4120                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4121            )
4122            .await?;
4123            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4124            if let Some(task) = data.task.as_mut() {
4125                self.fetch_remaining_workflow_history(worker_id, task)
4126                    .await?;
4127            }
4128            Ok(data)
4129        })
4130        .await?;
4131        Ok(data)
4132    }
4133
4134    async fn fetch_remaining_workflow_history(
4135        &self,
4136        worker_id: &str,
4137        task: &mut WorkflowTask,
4138    ) -> Result<()> {
4139        let mut next_token = task.next_history_page_token.clone();
4140        let mut seen = BTreeSet::new();
4141
4142        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4143            if seen.len() >= 128 || !seen.insert(token.clone()) {
4144                return Err(Error::Codec(
4145                    "workflow history pagination exceeded its page bound or repeated a token"
4146                        .into(),
4147                ));
4148            }
4149            let lease_owner = task
4150                .lease_owner
4151                .clone()
4152                .unwrap_or_else(|| worker_id.to_string());
4153            let page = self
4154                .workflow_task_history_page(
4155                    &task.task_id,
4156                    &lease_owner,
4157                    task.workflow_task_attempt,
4158                    &token,
4159                )
4160                .await?;
4161
4162            task.append_history_page(page);
4163
4164            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4165                return Err(Error::Codec(
4166                    "workflow history pagination returned the same page token".to_string(),
4167                ));
4168            }
4169
4170            next_token = task.next_history_page_token.clone();
4171        }
4172
4173        Ok(())
4174    }
4175
4176    async fn workflow_task_history_page(
4177        &self,
4178        task_id: &str,
4179        lease_owner: &str,
4180        workflow_task_attempt: u64,
4181        next_history_page_token: &str,
4182    ) -> Result<WorkflowTaskHistoryPage> {
4183        let body = json!({
4184            "lease_owner": lease_owner,
4185            "workflow_task_attempt": workflow_task_attempt,
4186            "next_history_page_token": next_history_page_token
4187        });
4188        let path = format!("/worker/workflow-tasks/{task_id}/history");
4189
4190        self.request_json(
4191            reqwest::Method::POST,
4192            &path,
4193            RequestProtocol::DefaultWorker,
4194            Some(&body),
4195        )
4196        .await
4197    }
4198
4199    pub async fn complete_workflow_task(
4200        &self,
4201        task_id: &str,
4202        lease_owner: &str,
4203        workflow_task_attempt: u64,
4204        commands: Vec<Value>,
4205    ) -> Result<Value> {
4206        self.complete_workflow_task_with_message_streams(
4207            task_id,
4208            lease_owner,
4209            workflow_task_attempt,
4210            commands,
4211            Vec::new(),
4212            Vec::new(),
4213            None,
4214        )
4215        .await
4216    }
4217
4218    #[allow(clippy::too_many_arguments)]
4219    async fn complete_workflow_task_with_message_streams(
4220        &self,
4221        task_id: &str,
4222        lease_owner: &str,
4223        workflow_task_attempt: u64,
4224        commands: Vec<Value>,
4225        message_stream_cursors: Vec<Value>,
4226        message_stream_waits: Vec<Value>,
4227        sticky_cache: Option<Value>,
4228    ) -> Result<Value> {
4229        validate_workflow_task_commands(&commands)?;
4230        let has_message_stream_metadata =
4231            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4232        if has_message_stream_metadata
4233            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4234        {
4235            return Err(Error::Codec(
4236                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4237                    .to_string(),
4238            ));
4239        }
4240        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4241            &commands,
4242            has_message_stream_metadata,
4243        );
4244        let protocol_version = if sticky_cache.is_some()
4245            && protocol_version
4246                .strip_prefix("1.")
4247                .and_then(|minor| minor.parse::<u64>().ok())
4248                .is_some_and(|minor| minor < 18)
4249        {
4250            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4251        } else {
4252            protocol_version
4253        };
4254        let mut body = json!({
4255            "lease_owner": lease_owner,
4256            "workflow_task_attempt": workflow_task_attempt,
4257            "commands": commands
4258        });
4259        if !message_stream_cursors.is_empty() {
4260            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4261        }
4262        if !message_stream_waits.is_empty() {
4263            body["message_stream_waits"] = Value::Array(message_stream_waits);
4264        }
4265        if let Some(claim) = sticky_cache {
4266            body["sticky_cache"] = claim;
4267        }
4268        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4269        self.request_json(
4270            reqwest::Method::POST,
4271            &path,
4272            RequestProtocol::Worker(protocol_version),
4273            Some(&body),
4274        )
4275        .await
4276    }
4277
4278    pub async fn fail_workflow_task(
4279        &self,
4280        task_id: &str,
4281        lease_owner: &str,
4282        workflow_task_attempt: u64,
4283        message: impl Into<String>,
4284    ) -> Result<Value> {
4285        self.fail_workflow_task_with_type(
4286            task_id,
4287            lease_owner,
4288            workflow_task_attempt,
4289            message,
4290            "RustWorkflowTaskFailure",
4291        )
4292        .await
4293    }
4294
4295    async fn fail_workflow_task_with_type(
4296        &self,
4297        task_id: &str,
4298        lease_owner: &str,
4299        workflow_task_attempt: u64,
4300        message: impl Into<String>,
4301        failure_type: &str,
4302    ) -> Result<Value> {
4303        let body = json!({
4304            "lease_owner": lease_owner,
4305            "workflow_task_attempt": workflow_task_attempt,
4306            "failure": {
4307                "message": message.into(),
4308                "type": failure_type
4309            }
4310        });
4311        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4312        self.request_json(
4313            reqwest::Method::POST,
4314            &path,
4315            RequestProtocol::DefaultWorker,
4316            Some(&body),
4317        )
4318        .await
4319    }
4320
4321    pub async fn poll_activity_task(
4322        &self,
4323        worker_id: &str,
4324        task_queue: &str,
4325        timeout: Duration,
4326    ) -> Result<Option<ActivityTask>> {
4327        Ok(self
4328            .poll_activity_task_response(worker_id, task_queue, timeout)
4329            .await?
4330            .task)
4331    }
4332
4333    /// Poll an activity task while preserving server stop and drain metadata.
4334    pub async fn poll_activity_task_response(
4335        &self,
4336        worker_id: &str,
4337        task_queue: &str,
4338        timeout: Duration,
4339    ) -> Result<PollActivityTaskResponse> {
4340        let poll_request_id = unique_request_id("rust-activity-poll");
4341        self.poll_activity_task_response_with_request_id(
4342            worker_id,
4343            task_queue,
4344            timeout,
4345            &poll_request_id,
4346            1,
4347        )
4348        .await
4349        .map(worker_session::SessionPollResponse::ordinary)
4350    }
4351
4352    async fn poll_activity_task_response_with_request_id(
4353        &self,
4354        worker_id: &str,
4355        task_queue: &str,
4356        timeout: Duration,
4357        poll_request_id: &str,
4358        transport_retries: usize,
4359    ) -> Result<worker_session::SessionPollResponse> {
4360        let body = json!({
4361            "worker_id": worker_id,
4362            "task_queue": task_queue,
4363            "poll_request_id": poll_request_id,
4364            "timeout_seconds": long_poll_timeout_seconds(timeout),
4365        });
4366        let mut wire: Value = self
4367            .poll_request_json_unresolved(
4368                "/worker/activity-tasks/poll",
4369                RequestProtocol::DefaultWorker,
4370                &body,
4371                timeout + Duration::from_secs(5),
4372                transport_retries,
4373            )
4374            .await?;
4375        let claim = activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?;
4376        let mut data: worker_session::SessionPollResponse =
4377            activity_hydration::HydrationClaim::protect(claim.as_ref(), self, async {
4378                self.resolve_runtime_payloads(
4379                    &mut wire,
4380                    "/worker/activity-tasks/poll",
4381                    RequestProtocol::DefaultWorker,
4382                )
4383                .await?;
4384                Ok(serde_json::from_value(wire)?)
4385            })
4386            .await?;
4387        if let Some(task) = data.task.as_mut() {
4388            task.hydration_claim = claim;
4389        }
4390        Ok(data)
4391    }
4392
4393    pub async fn complete_activity_task<T: Serialize>(
4394        &self,
4395        task_id: &str,
4396        activity_attempt_id: &str,
4397        lease_owner: &str,
4398        result: T,
4399        codec: &str,
4400    ) -> Result<Value> {
4401        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4402        let body = json!({
4403            "activity_attempt_id": activity_attempt_id,
4404            "lease_owner": lease_owner,
4405            "result": result
4406        });
4407        let path = format!("/worker/activity-tasks/{task_id}/complete");
4408        activity_task_response(
4409            self.request_json(
4410                reqwest::Method::POST,
4411                &path,
4412                RequestProtocol::DefaultWorker,
4413                Some(&body),
4414            )
4415            .await,
4416            "complete",
4417            task_id,
4418            activity_attempt_id,
4419        )
4420    }
4421
4422    pub async fn fail_activity_task(
4423        &self,
4424        task_id: &str,
4425        activity_attempt_id: &str,
4426        lease_owner: &str,
4427        message: impl Into<String>,
4428        non_retryable: bool,
4429    ) -> Result<Value> {
4430        let body = json!({
4431            "activity_attempt_id": activity_attempt_id,
4432            "lease_owner": lease_owner,
4433            "failure": {
4434                "message": message.into(),
4435                "type": "RustActivityFailure",
4436                "non_retryable": non_retryable
4437            }
4438        });
4439        let path = format!("/worker/activity-tasks/{task_id}/fail");
4440        activity_task_response(
4441            self.request_json(
4442                reqwest::Method::POST,
4443                &path,
4444                RequestProtocol::DefaultWorker,
4445                Some(&body),
4446            )
4447            .await,
4448            "fail",
4449            task_id,
4450            activity_attempt_id,
4451        )
4452    }
4453
4454    /// Record a flat map of scalar/null activity progress metadata.
4455    ///
4456    /// Heartbeat details use the Server's bounded JSON progress contract.
4457    /// They are not workflow payload envelopes.
4458    pub async fn heartbeat_activity_task<T: Serialize>(
4459        &self,
4460        task_id: &str,
4461        activity_attempt_id: &str,
4462        lease_owner: &str,
4463        details: T,
4464    ) -> Result<ActivityHeartbeatResponse> {
4465        serde_json::from_value(
4466            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4467                .await?,
4468        )
4469        .map_err(Error::from)
4470    }
4471
4472    async fn heartbeat_activity_task_value<T: Serialize>(
4473        &self,
4474        task_id: &str,
4475        activity_attempt_id: &str,
4476        lease_owner: &str,
4477        details: T,
4478    ) -> Result<Value> {
4479        let details = AvroValue::from_serialize(&details)?.into_json()?;
4480        let body = json!({
4481            "activity_attempt_id": activity_attempt_id,
4482            "lease_owner": lease_owner,
4483            "details": details
4484        });
4485        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4486        activity_task_response(
4487            self.request_json(
4488                reqwest::Method::POST,
4489                &path,
4490                RequestProtocol::DefaultWorker,
4491                Some(&body),
4492            )
4493            .await,
4494            "heartbeat",
4495            task_id,
4496            activity_attempt_id,
4497        )
4498    }
4499
4500    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4501        &self,
4502        method: reqwest::Method,
4503        path: &str,
4504        protocol: RequestProtocol,
4505        body: Option<&B>,
4506    ) -> Result<T> {
4507        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4508            .await
4509    }
4510
4511    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4512        &self,
4513        method: reqwest::Method,
4514        path: &str,
4515        protocol: RequestProtocol,
4516        body: Option<&B>,
4517        timeout: Duration,
4518    ) -> Result<T> {
4519        let mut value: Value = self
4520            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4521            .await?;
4522        let protocol = match protocol {
4523            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4524                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4525            }
4526            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4527        };
4528        self.resolve_runtime_payloads(&mut value, path, protocol)
4529            .await?;
4530        Ok(serde_json::from_value(value)?)
4531    }
4532
4533    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4534        &self,
4535        method: reqwest::Method,
4536        path: &str,
4537        protocol: RequestProtocol,
4538        body: Option<&B>,
4539        timeout: Duration,
4540    ) -> Result<T> {
4541        let protocol = match protocol {
4542            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4543                let selected = self.worker_protocol_version.as_str();
4544                if self.cooperative_worker_protocol
4545                    && !cooperative_cancellation::supports_protocol(selected)
4546                {
4547                    return Err(Error::CooperativeCancellationUnavailable(
4548                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4549                    ));
4550                }
4551                if let RequestProtocol::Worker(minimum) = protocol {
4552                    let supported = minimum
4553                        .strip_prefix("1.")
4554                        .and_then(|minor| minor.parse::<u64>().ok())
4555                        .zip(
4556                            selected
4557                                .strip_prefix("1.")
4558                                .and_then(|minor| minor.parse::<u64>().ok()),
4559                        )
4560                        .is_some_and(|(minimum, selected)| selected >= minimum);
4561                    if !supported {
4562                        return Err(Error::WorkerLoop(format!(
4563                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4564                        )));
4565                    }
4566                }
4567                RequestProtocol::Worker(selected)
4568            }
4569            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4570        };
4571        let auth_token = self.auth_token(protocol)?;
4572        let mut request = self
4573            .http
4574            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4575            .timeout(timeout)
4576            .header(reqwest::header::ACCEPT, "application/json")
4577            .header(reqwest::header::CONTENT_TYPE, "application/json")
4578            .header("X-Namespace", &self.namespace);
4579
4580        match protocol {
4581            RequestProtocol::DefaultWorker => {
4582                request = request.header(
4583                    "X-Durable-Workflow-Protocol-Version",
4584                    self.worker_protocol_version.as_str(),
4585                );
4586            }
4587            RequestProtocol::Worker(version) => {
4588                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4589            }
4590            RequestProtocol::ControlPlane => {
4591                request = request.header(
4592                    "X-Durable-Workflow-Control-Plane-Version",
4593                    CONTROL_PLANE_VERSION,
4594                );
4595            }
4596        }
4597
4598        if let Some(token) = auth_token {
4599            request = request.bearer_auth(token);
4600        }
4601
4602        if let Some(body) = body {
4603            let mut body = serde_json::to_value(body)?;
4604            if matches!(
4605                method,
4606                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4607            ) {
4608                self.externalize_runtime_payloads(&mut body, path, protocol)
4609                    .await?;
4610            }
4611            request = request.json(&body);
4612        }
4613
4614        let request = request.build()?;
4615        let request_body = request
4616            .body()
4617            .and_then(reqwest::Body::as_bytes)
4618            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4619        let poll_request_id = path.ends_with("/poll").then(|| {
4620            request_body
4621                .as_ref()
4622                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4623                .unwrap_or_default()
4624        });
4625        let mut storage_retries = 0_usize;
4626        let mut deferred_workflow_completion = false;
4627
4628        loop {
4629            // Keep the serialized body and lease/poll identity across admission pauses.
4630            let receive = async {
4631                let response = self
4632                    .http
4633                    .execute(request.try_clone().ok_or_else(|| {
4634                        Error::WorkerLoop("worker request body cannot be retried".to_string())
4635                    })?)
4636                    .await?;
4637                let status = response.status();
4638                Ok::<_, Error>((status, response.bytes().await?))
4639            };
4640            let retry_deadline = self
4641                .worker_storage_admission
4642                .as_ref()
4643                .and_then(|admission| admission.workflow_completion_retry_deadline);
4644            if deferred_workflow_completion
4645                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
4646            {
4647                return Err(Error::Timeout);
4648            }
4649            let (status, bytes) = match retry_deadline.filter(|_| deferred_workflow_completion) {
4650                Some(deadline) => tokio::time::timeout_at(deadline, receive)
4651                    .await
4652                    .map_err(|_| Error::Timeout)??,
4653                None => receive.await?,
4654            };
4655
4656            if !status.is_success() {
4657                let body = String::from_utf8_lossy(&bytes).to_string();
4658                if let Some(protocol) = protocol_failure(status, &body) {
4659                    return Err(Error::Protocol(protocol));
4660                }
4661                let error = Error::Http { status, body };
4662                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
4663                    &error,
4664                    path,
4665                    request_body.as_ref(),
4666                )
4667                .is_some();
4668                if self
4669                    .wait_for_storage_admission(
4670                        &error,
4671                        protocol,
4672                        Some(path),
4673                        poll_request_id.as_deref(),
4674                        request_body.as_ref(),
4675                        &mut storage_retries,
4676                    )
4677                    .await
4678                {
4679                    continue;
4680                }
4681                return Err(error);
4682            }
4683
4684            if bytes.is_empty() {
4685                return Ok(serde_json::from_value(Value::Null)?);
4686            }
4687
4688            return Ok(serde_json::from_slice(&bytes)?);
4689        }
4690    }
4691
4692    async fn wait_for_storage_admission(
4693        &self,
4694        error: &Error,
4695        protocol: RequestProtocol,
4696        path: Option<&str>,
4697        poll_request_id: Option<&str>,
4698        request_body: Option<&Value>,
4699        retries: &mut usize,
4700    ) -> bool {
4701        let Some(admission) = self
4702            .worker_storage_admission
4703            .as_ref()
4704            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4705        else {
4706            return false;
4707        };
4708        let completion_deferred = path.and_then(|path| {
4709            worker_deferred_workflow_completion_retry_after(error, path, request_body)
4710        });
4711        let Some(advertised_delay) = completion_deferred
4712            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
4713            .or_else(|| {
4714                path.and_then(|path| {
4715                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4716                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4717                })
4718            })
4719        else {
4720            return false;
4721        };
4722        *retries = retries.saturating_add(1);
4723        let delay = worker_retry_delay(admission.policy, *retries)
4724            .max(advertised_delay)
4725            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4726        let delay = if completion_deferred.is_some() {
4727            delay.max(advertised_delay)
4728        } else {
4729            delay
4730        };
4731        let wait_deadline = tokio::time::Instant::now() + delay;
4732        loop {
4733            if admission.stop.load(Ordering::SeqCst) {
4734                return false;
4735            }
4736            let now = tokio::time::Instant::now();
4737            if admission
4738                .workflow_completion_retry_deadline
4739                .is_some_and(|deadline| now >= deadline)
4740            {
4741                return false;
4742            }
4743            let remaining = wait_deadline.saturating_duration_since(now);
4744            if remaining.is_zero() {
4745                return true;
4746            }
4747            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4748        }
4749    }
4750
4751    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4752        &self,
4753        path: &str,
4754        protocol: RequestProtocol,
4755        body: &B,
4756        timeout: Duration,
4757        max_retries: usize,
4758    ) -> Result<T> {
4759        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
4760            .await
4761    }
4762
4763    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
4764        &self,
4765        path: &str,
4766        protocol: RequestProtocol,
4767        body: &B,
4768        timeout: Duration,
4769        max_retries: usize,
4770    ) -> Result<T> {
4771        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
4772            .await
4773    }
4774
4775    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
4776        &self,
4777        path: &str,
4778        protocol: RequestProtocol,
4779        body: &B,
4780        timeout: Duration,
4781        max_retries: usize,
4782        resolve: bool,
4783    ) -> Result<T> {
4784        let mut retries = 0;
4785
4786        loop {
4787            let response = if resolve {
4788                self.request_json_with_timeout(
4789                    reqwest::Method::POST,
4790                    path,
4791                    protocol,
4792                    Some(body),
4793                    timeout,
4794                )
4795                .await
4796            } else {
4797                self.request_json_unresolved_with_timeout(
4798                    reqwest::Method::POST,
4799                    path,
4800                    protocol,
4801                    Some(body),
4802                    timeout,
4803                )
4804                .await
4805            };
4806
4807            match response {
4808                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4809                response => return worker_poll_response(response),
4810            }
4811        }
4812    }
4813
4814    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4815        match protocol {
4816            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4817                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4818                    return Ok(Some(token));
4819                }
4820                if self.control_token.is_some() {
4821                    return Err(Error::MissingRoleCredentials {
4822                        role: "worker",
4823                        opposite_role: "control",
4824                    });
4825                }
4826                Ok(None)
4827            }
4828            RequestProtocol::ControlPlane => {
4829                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4830                    return Ok(Some(token));
4831                }
4832                if self.worker_token.is_some() {
4833                    return Err(Error::MissingRoleCredentials {
4834                        role: "control",
4835                        opposite_role: "worker",
4836                    });
4837                }
4838                Ok(None)
4839            }
4840        }
4841    }
4842}
4843
4844fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4845    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4846    let reason = body
4847        .get("reason")
4848        .and_then(Value::as_str)
4849        .unwrap_or("query_rejected")
4850        .to_string();
4851    let message = body
4852        .get("message")
4853        .or_else(|| body.get("error"))
4854        .and_then(Value::as_str)
4855        .unwrap_or("workflow query was rejected")
4856        .to_string();
4857
4858    QueryFailure {
4859        status: status.as_u16(),
4860        reason,
4861        message,
4862        body,
4863    }
4864}
4865
4866fn workflow_command_result(
4867    command: WorkflowCommandKind,
4868    data: Value,
4869    workflow_id: &str,
4870    run_id: Option<&str>,
4871) -> WorkflowCommandResult {
4872    WorkflowCommandResult {
4873        command,
4874        workflow_id: data
4875            .get("workflow_id")
4876            .and_then(Value::as_str)
4877            .unwrap_or(workflow_id)
4878            .to_string(),
4879        run_id: data
4880            .get("run_id")
4881            .and_then(Value::as_str)
4882            .or(run_id)
4883            .map(str::to_string),
4884        outcome: data
4885            .get("outcome")
4886            .and_then(Value::as_str)
4887            .map(str::to_string),
4888        reason: data
4889            .get("reason")
4890            .and_then(Value::as_str)
4891            .map(str::to_string),
4892        command_status: data
4893            .get("command_status")
4894            .and_then(Value::as_str)
4895            .map(str::to_string),
4896        raw: data,
4897    }
4898}
4899
4900fn workflow_command_rejection(
4901    command: WorkflowCommandKind,
4902    status: reqwest::StatusCode,
4903    raw_body: String,
4904    workflow_id: &str,
4905    run_id: Option<&str>,
4906) -> WorkflowCommandRejection {
4907    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4908    WorkflowCommandRejection {
4909        command,
4910        status: status.as_u16(),
4911        reason: body
4912            .get("reason")
4913            .and_then(Value::as_str)
4914            .unwrap_or("workflow_command_rejected")
4915            .to_string(),
4916        message: body
4917            .get("message")
4918            .or_else(|| body.get("error"))
4919            .and_then(Value::as_str)
4920            .unwrap_or("workflow lifecycle command was rejected")
4921            .to_string(),
4922        workflow_id: body
4923            .get("workflow_id")
4924            .and_then(Value::as_str)
4925            .unwrap_or(workflow_id)
4926            .to_string(),
4927        run_id: body
4928            .get("run_id")
4929            .and_then(Value::as_str)
4930            .or(run_id)
4931            .map(str::to_string),
4932        target_scope: body
4933            .get("target_scope")
4934            .and_then(Value::as_str)
4935            .map(str::to_string),
4936        body,
4937    }
4938}
4939
4940fn query_task_response(response: Result<Value>) -> Result<Value> {
4941    match response {
4942        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4943        response => response,
4944    }
4945}
4946
4947fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4948    match response {
4949        Err(Error::Http { status, body })
4950            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4951        {
4952            Ok(serde_json::from_str(&body)?)
4953        }
4954        response => response,
4955    }
4956}
4957
4958fn worker_poll_body_is_stop(body: &str) -> bool {
4959    serde_json::from_str::<Value>(body)
4960        .ok()
4961        .is_some_and(|body| {
4962            worker_poll_is_stop(
4963                body.get("poll_status").and_then(Value::as_str),
4964                body.get("reason").and_then(Value::as_str),
4965            )
4966        })
4967}
4968
4969fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4970    matches!(poll_status, Some("draining" | "stopped"))
4971        || matches!(reason, Some("worker_draining" | "worker_stopped"))
4972}
4973
4974fn query_task_rejection_is_final(error: &Error) -> bool {
4975    matches!(
4976        error,
4977        Error::QueryFailed(failure)
4978            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
4979    )
4980}
4981
4982fn activity_task_response<T>(
4983    response: Result<T>,
4984    operation: &str,
4985    task_id: &str,
4986    activity_attempt_id: &str,
4987) -> Result<T> {
4988    match response {
4989        Err(Error::Http { status, body }) => {
4990            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
4991            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
4992                operation: operation.to_string(),
4993                status: status.as_u16(),
4994                reason: body
4995                    .get("reason")
4996                    .and_then(Value::as_str)
4997                    .unwrap_or("activity_task_rejected")
4998                    .to_string(),
4999                task_id: body
5000                    .get("task_id")
5001                    .and_then(Value::as_str)
5002                    .unwrap_or(task_id)
5003                    .to_string(),
5004                activity_attempt_id: body
5005                    .get("activity_attempt_id")
5006                    .and_then(Value::as_str)
5007                    .unwrap_or(activity_attempt_id)
5008                    .to_string(),
5009                cancel_requested: body
5010                    .get("cancel_requested")
5011                    .and_then(Value::as_bool)
5012                    .unwrap_or(false),
5013                can_continue: body.get("can_continue").and_then(Value::as_bool),
5014                run_closed_reason: body
5015                    .get("run_closed_reason")
5016                    .and_then(Value::as_str)
5017                    .map(str::to_string),
5018                body,
5019            }))
5020        }
5021        response => response,
5022    }
5023}
5024
5025fn activity_task_rejection_is_final(error: &Error) -> bool {
5026    matches!(
5027        error,
5028        Error::ActivityTaskRejected(rejection)
5029            if matches!(
5030                rejection.reason.as_str(),
5031                "run_cancelled"
5032                    | "run_terminated"
5033                    | "attempt_closed"
5034                    | "stale_attempt"
5035                    | "activity_cancelled"
5036                    | "task_cancelled"
5037                    | "run_closed"
5038                    | "activity_not_running"
5039                    | "attempt_not_found"
5040            )
5041    )
5042}
5043
5044fn workflow_task_completion_is_terminal_timeout(
5045    error: &Error,
5046    task_id: &str,
5047    workflow_task_attempt: u64,
5048    run_id: Option<&str>,
5049) -> bool {
5050    let Error::Http { status, body } = error else {
5051        return false;
5052    };
5053    if *status != reqwest::StatusCode::CONFLICT {
5054        return false;
5055    }
5056
5057    let Some(run_id) = run_id else {
5058        return false;
5059    };
5060    let Ok(body) = serde_json::from_str::<Value>(body) else {
5061        return false;
5062    };
5063
5064    body.get("recorded").and_then(Value::as_bool) == Some(false)
5065        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5066        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5067        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5068        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5069        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5070}
5071
5072fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5073    let body: Value = serde_json::from_str(raw_body).ok()?;
5074    let reason = body.get("reason")?.as_str()?;
5075    if !matches!(
5076        reason,
5077        "missing_protocol_version"
5078            | "unsupported_protocol_version"
5079            | "missing_control_plane_version"
5080            | "unsupported_control_plane_version"
5081    ) {
5082        return None;
5083    }
5084
5085    Some(ProtocolFailure {
5086        status: status.as_u16(),
5087        reason: reason.to_string(),
5088        message: body
5089            .get("message")
5090            .or_else(|| body.get("error"))
5091            .and_then(Value::as_str)
5092            .unwrap_or("protocol version rejected")
5093            .to_string(),
5094        supported_version: body
5095            .get("supported_version")
5096            .and_then(Value::as_str)
5097            .map(str::to_string),
5098        requested_version: body
5099            .get("requested_version")
5100            .and_then(Value::as_str)
5101            .map(str::to_string),
5102        body,
5103    })
5104}
5105
5106fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5107    timeout
5108        .as_secs()
5109        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5110        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5111}
5112
5113fn worker_operation_is_retryable(error: &Error) -> bool {
5114    if worker_poll_capacity_retry_after(error).is_some()
5115        || worker_storage_admission_body(error).is_some()
5116        || worker_backend_unavailable_body(error).is_some()
5117        || worker_operation_is_explicitly_non_retryable(error)
5118    {
5119        return false;
5120    }
5121
5122    match error {
5123        Error::Transport(error) => {
5124            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5125        }
5126        Error::Http { status, .. } => {
5127            matches!(
5128                *status,
5129                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5130            ) || status.is_server_error()
5131        }
5132        _ => false,
5133    }
5134}
5135
5136fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5137    let body: Value = match error {
5138        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5139        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5140        _ => return None,
5141    };
5142    matches!(
5143        body.get("reason").and_then(Value::as_str),
5144        Some("storage_pressure" | "storage_admission_unavailable")
5145    )
5146    .then_some(body)
5147}
5148
5149fn worker_storage_admission_retry_after(
5150    error: &Error,
5151    poll_request_id: Option<&str>,
5152) -> Option<Duration> {
5153    let Error::Http { status, .. } = error else {
5154        return None;
5155    };
5156    let body = worker_storage_admission_body(error)?;
5157    let delay = body.get("retry_after_seconds")?.as_u64()?;
5158    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5159        || delay == 0
5160        || body.get("retryable") != Some(&Value::Bool(true))
5161        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5162        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5163        || body
5164            .get("request_admitted")
5165            .is_some_and(|admitted| admitted != &Value::Bool(false))
5166    {
5167        return None;
5168    }
5169    match poll_request_id {
5170        Some(id) => {
5171            if id.is_empty()
5172                || body.get("task") != Some(&Value::Null)
5173                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5174                || body.get("poll_status") != body.get("reason")
5175                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5176                || body.get("claim_admitted") != Some(&Value::Bool(false))
5177            {
5178                return None;
5179            }
5180        }
5181        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5182        None => {}
5183    }
5184    Some(Duration::from_secs(delay))
5185}
5186
5187fn worker_backend_unavailable_retry_after(
5188    error: &Error,
5189    path: &str,
5190    poll_request_id: Option<&str>,
5191) -> Option<Duration> {
5192    let operation = match path {
5193        "/worker/register" => "register_worker",
5194        "/worker/heartbeat" => "heartbeat_worker",
5195        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5196        "/worker/activity-tasks/poll" => "poll_activity_task",
5197        "/worker/query-tasks/poll" => "poll_query_task",
5198        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5199        _ => return None,
5200    };
5201    let body = worker_backend_unavailable_body(error)?;
5202    let delay = body.get("retry_after_seconds")?.as_u64()?;
5203    if delay == 0
5204        || body.get("operation")?.as_str()? != operation
5205        || body.get("outcome")?.as_str()? != "unknown"
5206        || body.get("retryable") != Some(&Value::Bool(true))
5207        || body.get("worker_id")?.as_str()?.is_empty()
5208    {
5209        return None;
5210    }
5211    if let Some(id) = poll_request_id {
5212        if id.is_empty()
5213            || body.get("task") != Some(&Value::Null)
5214            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5215            || body.get("poll_request_id")?.as_str()? != id
5216            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5217        {
5218            return None;
5219        }
5220    } else if path.ends_with("/poll") {
5221        return None;
5222    }
5223    Some(Duration::from_secs(delay))
5224}
5225
5226fn worker_fenced_completion_retry_after(
5227    error: &Error,
5228    path: &str,
5229    request_body: Option<&Value>,
5230) -> Option<Duration> {
5231    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5232        .strip_prefix("/worker/workflow-tasks/")
5233        .and_then(|tail| tail.strip_suffix("/complete"))
5234    {
5235        ("complete_workflow_task", task_id, "workflow_task_attempt")
5236    } else if let Some(task_id) = path
5237        .strip_prefix("/worker/activity-tasks/")
5238        .and_then(|tail| tail.strip_suffix("/complete"))
5239    {
5240        ("complete_activity_task", task_id, "activity_attempt_id")
5241    } else {
5242        return None;
5243    };
5244    if task_id.is_empty() || task_id.contains('/') {
5245        return None;
5246    }
5247
5248    let request = request_body?.as_object()?;
5249    let lease_owner = request.get("lease_owner")?.as_str()?;
5250    if lease_owner.is_empty() {
5251        return None;
5252    }
5253    let attempt = request.get(attempt_field)?;
5254    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5255        || (attempt_field == "activity_attempt_id"
5256            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5257    {
5258        return None;
5259    }
5260
5261    let body = worker_backend_unavailable_body(error)?;
5262    let delay = body.get("retry_after_seconds")?.as_u64()?;
5263    if delay == 0
5264        || body.get("operation")?.as_str()? != operation
5265        || body.get("outcome")?.as_str()? != "unknown"
5266        || body.get("retryable") != Some(&Value::Bool(true))
5267        || body.get("worker_id")?.as_str()? != lease_owner
5268        || body.get("task_queue") != Some(&Value::Null)
5269        || body.get("task_id")?.as_str()? != task_id
5270        || body.get("lease_owner")?.as_str()? != lease_owner
5271        || body.get(attempt_field) != Some(attempt)
5272    {
5273        return None;
5274    }
5275
5276    Some(Duration::from_secs(delay))
5277}
5278
5279fn worker_deferred_workflow_completion_retry_after(
5280    error: &Error,
5281    path: &str,
5282    request_body: Option<&Value>,
5283) -> Option<Duration> {
5284    let task_id = path
5285        .strip_prefix("/worker/workflow-tasks/")?
5286        .strip_suffix("/complete")?;
5287    if task_id.is_empty() || task_id.contains('/') {
5288        return None;
5289    }
5290    let request = request_body?.as_object()?;
5291    let owner = request.get("lease_owner")?.as_str()?;
5292    let attempt = request.get("workflow_task_attempt")?;
5293    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5294        return None;
5295    }
5296    let Error::Http { status, body } = error else {
5297        return None;
5298    };
5299    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5300        return None;
5301    }
5302    let body: Value = serde_json::from_str(body).ok()?;
5303    let delay = body.get("retry_after_seconds")?.as_u64()?;
5304    if !(1..=5).contains(&delay)
5305        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5306        || body.get("operation")?.as_str()? != "complete_workflow_task"
5307        || body.get("outcome")?.as_str()? != "deferred"
5308        || body.get("recorded") != Some(&Value::Bool(false))
5309        || body.get("retryable") != Some(&Value::Bool(true))
5310        || body.get("task_id")?.as_str()? != task_id
5311        || body.get("lease_owner")?.as_str()? != owner
5312        || body.get("workflow_task_attempt") != Some(attempt)
5313        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5314    {
5315        return None;
5316    }
5317    Some(Duration::from_secs(delay))
5318}
5319
5320fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5321    let Error::Http { status, body } = error else {
5322        return None;
5323    };
5324    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5325        return None;
5326    }
5327    let body: Value = serde_json::from_str(body).ok()?;
5328    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5329}
5330
5331fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5332    let Error::Http { body, .. } = error else {
5333        return false;
5334    };
5335
5336    serde_json::from_str::<Value>(body)
5337        .ok()
5338        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5339        == Some(false)
5340}
5341
5342fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5343    let Error::Http { status, body } = error else {
5344        return None;
5345    };
5346    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5347        return None;
5348    }
5349
5350    let body = serde_json::from_str::<Value>(body).ok()?;
5351    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5352        == Some("long_poll_capacity_exhausted")
5353        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5354    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5355        return None;
5356    }
5357
5358    Some(Duration::from_secs(
5359        body.get("retry_after_seconds")
5360            .and_then(Value::as_u64)
5361            .unwrap_or_default(),
5362    ))
5363}
5364
5365fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5366    let exponent = retry.saturating_sub(1).min(31) as u32;
5367    policy
5368        .initial_backoff
5369        .saturating_mul(1_u32 << exponent)
5370        .min(policy.max_backoff)
5371}
5372
5373#[derive(Debug)]
5374pub struct ClientBuilder {
5375    base_url: String,
5376    token: Option<String>,
5377    control_token: Option<String>,
5378    worker_token: Option<String>,
5379    namespace: String,
5380    timeout: Duration,
5381    max_external_payload_bytes: usize,
5382    worker_protocol_version: WorkerProtocolVersion,
5383}
5384
5385impl ClientBuilder {
5386    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5387    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5388        self.worker_protocol_version = version;
5389        self
5390    }
5391
5392    pub fn token(mut self, token: Option<String>) -> Self {
5393        self.token = token;
5394        self
5395    }
5396
5397    pub fn control_token(mut self, token: Option<String>) -> Self {
5398        self.control_token = token;
5399        self
5400    }
5401
5402    pub fn worker_token(mut self, token: Option<String>) -> Self {
5403        self.worker_token = token;
5404        self
5405    }
5406
5407    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5408        self.namespace = namespace.into();
5409        self
5410    }
5411
5412    pub fn timeout(mut self, timeout: Duration) -> Self {
5413        self.timeout = timeout;
5414        self
5415    }
5416
5417    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5418    /// References are fetched only from this client's authenticated runtime.
5419    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5420        self.max_external_payload_bytes = bytes;
5421        self
5422    }
5423
5424    pub fn build(self) -> Result<Client> {
5425        let base_url = self.base_url.trim_end_matches('/').to_string();
5426        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5427            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5428            .unwrap_or_else(|_| base_url.ends_with("/api"));
5429
5430        if has_sdk_api_suffix {
5431            return Err(Error::InvalidBaseUrl);
5432        }
5433
5434        Ok(Client {
5435            http: reqwest::Client::builder()
5436                .timeout(self.timeout)
5437                .redirect(reqwest::redirect::Policy::none())
5438                .build()?,
5439            hydration_timeout: self.timeout,
5440            base_url,
5441            token: self.token,
5442            control_token: self.control_token,
5443            worker_token: self.worker_token,
5444            namespace: self.namespace,
5445            max_external_payload_bytes: self.max_external_payload_bytes,
5446            worker_storage_admission: None,
5447            cooperative_worker_protocol: false,
5448            worker_protocol_version: self.worker_protocol_version,
5449            local_activities_enabled: false,
5450            worker_sessions_enabled: false,
5451            max_concurrent_worker_sessions: 10,
5452            worker_build_id: None,
5453            sticky_cache: None,
5454            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5455        })
5456    }
5457}
5458
5459#[derive(Clone, Debug)]
5460pub struct WorkflowHandle {
5461    client: Client,
5462    pub workflow_id: String,
5463    pub run_id: Option<String>,
5464    pub workflow_type: String,
5465}
5466
5467impl WorkflowHandle {
5468    /// Describe whichever run is current for this stable workflow instance.
5469    pub async fn describe(&self) -> Result<WorkflowDescription> {
5470        self.client.describe_workflow(&self.workflow_id).await
5471    }
5472
5473    /// Describe the run identity originally selected by this handle.
5474    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5475        let run_id = self.run_id.as_deref().ok_or_else(|| {
5476            Error::Codec("run_id is required for selected-run description".to_string())
5477        })?;
5478        self.client
5479            .describe_workflow_run(&self.workflow_id, run_id)
5480            .await
5481    }
5482
5483    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5484        self.client
5485            .signal_workflow(&self.workflow_id, signal_name, input)
5486            .await
5487    }
5488
5489    pub async fn append_message<T: Serialize>(
5490        &self,
5491        stream_name: &str,
5492        message_id: &str,
5493        input: T,
5494    ) -> Result<Value> {
5495        self.client
5496            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5497            .await
5498    }
5499
5500    /// Signal only if this handle's selected run is still current.
5501    pub async fn signal_selected_run<T: Serialize>(
5502        &self,
5503        signal_name: &str,
5504        input: T,
5505    ) -> Result<Value> {
5506        let run_id = self.run_id.as_deref().ok_or_else(|| {
5507            Error::Codec("run_id is required for selected-run signaling".to_string())
5508        })?;
5509        self.client
5510            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5511            .await
5512    }
5513
5514    /// Close whichever run is current as cancelled, without workflow cleanup.
5515    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5516        self.client
5517            .cancel_workflow(&self.workflow_id, options)
5518            .await
5519    }
5520
5521    /// Request cancellation only if this handle's selected run is still current.
5522    pub async fn cancel_selected_run(
5523        &self,
5524        options: WorkflowCommandOptions,
5525    ) -> Result<WorkflowCommandResult> {
5526        let run_id = self.run_id.as_deref().ok_or_else(|| {
5527            Error::Codec("run_id is required for selected-run cancellation".to_string())
5528        })?;
5529        self.client
5530            .cancel_workflow_run(&self.workflow_id, run_id, options)
5531            .await
5532    }
5533
5534    /// Forcefully terminate whichever run is current.
5535    pub async fn terminate(
5536        &self,
5537        options: WorkflowCommandOptions,
5538    ) -> Result<WorkflowCommandResult> {
5539        self.client
5540            .terminate_workflow(&self.workflow_id, options)
5541            .await
5542    }
5543
5544    /// Terminate only if this handle's selected run is still current.
5545    pub async fn terminate_selected_run(
5546        &self,
5547        options: WorkflowCommandOptions,
5548    ) -> Result<WorkflowCommandResult> {
5549        let run_id = self.run_id.as_deref().ok_or_else(|| {
5550            Error::Codec("run_id is required for selected-run termination".to_string())
5551        })?;
5552        self.client
5553            .terminate_workflow_run(&self.workflow_id, run_id, options)
5554            .await
5555    }
5556
5557    /// Continue this handle's failed run without repeating completed activities.
5558    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5559        let run_id = self
5560            .run_id
5561            .as_deref()
5562            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5563        self.client
5564            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5565            .await
5566    }
5567
5568    /// Execute a named, read-only query against this workflow.
5569    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5570        self.client
5571            .query_workflow(&self.workflow_id, query_name, input)
5572            .await
5573    }
5574
5575    pub async fn query_avro_value<T: Serialize>(
5576        &self,
5577        query_name: &str,
5578        input: T,
5579    ) -> Result<AvroValue> {
5580        self.client
5581            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5582            .await
5583    }
5584
5585    pub async fn update<T: Serialize>(
5586        &self,
5587        update_name: &str,
5588        input: T,
5589        request_id: Option<&str>,
5590    ) -> Result<Value> {
5591        self.client
5592            .update_workflow(&self.workflow_id, update_name, input, request_id)
5593            .await
5594    }
5595
5596    pub async fn update_avro_value<T: Serialize>(
5597        &self,
5598        update_name: &str,
5599        input: T,
5600        request_id: Option<&str>,
5601    ) -> Result<AvroValue> {
5602        self.client
5603            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5604            .await
5605    }
5606
5607    /// Query only if this handle's selected run is still current.
5608    pub async fn query_selected_run<T: Serialize>(
5609        &self,
5610        query_name: &str,
5611        input: T,
5612    ) -> Result<Value> {
5613        let run_id = self
5614            .run_id
5615            .as_deref()
5616            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5617        self.client
5618            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5619            .await
5620    }
5621
5622    /// Await the final terminal outcome of the current continue-as-new chain.
5623    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5624        self.result_target(options, None).await
5625    }
5626
5627    /// Await the final result without projecting Avro bytes through JSON.
5628    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5629        self.result_avro_value_target(options, None).await
5630    }
5631
5632    /// Await the final result and decode it into a Serde application type.
5633    pub async fn result_typed<T: DeserializeOwned>(
5634        &self,
5635        options: WorkflowResultOptions,
5636    ) -> Result<T> {
5637        let result = self.result_avro_value(options).await?;
5638        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5639    }
5640
5641    /// Await only the run identity originally selected by this handle.
5642    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5643        let run_id = self.run_id.as_deref().ok_or_else(|| {
5644            Error::Codec("run_id is required for selected-run result".to_string())
5645        })?;
5646        self.result_target(options, Some(run_id)).await
5647    }
5648
5649    /// Await the selected run's result on the lossless Avro Value surface.
5650    pub async fn result_selected_run_avro_value(
5651        &self,
5652        options: WorkflowResultOptions,
5653    ) -> Result<AvroValue> {
5654        let run_id = self.run_id.as_deref().ok_or_else(|| {
5655            Error::Codec("run_id is required for selected-run result".to_string())
5656        })?;
5657        self.result_avro_value_target(options, Some(run_id)).await
5658    }
5659
5660    /// Await the selected run and decode its result into a Serde type.
5661    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5662        &self,
5663        options: WorkflowResultOptions,
5664    ) -> Result<T> {
5665        let result = self.result_selected_run_avro_value(options).await?;
5666        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5667    }
5668
5669    async fn result_avro_value_target(
5670        &self,
5671        options: WorkflowResultOptions,
5672        selected_run_id: Option<&str>,
5673    ) -> Result<AvroValue> {
5674        let started = Instant::now();
5675
5676        loop {
5677            let description = match selected_run_id {
5678                Some(run_id) => {
5679                    self.client
5680                        .describe_workflow_run(&self.workflow_id, run_id)
5681                        .await?
5682                }
5683                None => self.describe().await?,
5684            };
5685            if description.is_completed() {
5686                return description.output_avro_value.ok_or_else(|| {
5687                    Error::Codec(
5688                        "missing_payload_envelope: typed workflow result requires output_envelope"
5689                            .to_string(),
5690                    )
5691                });
5692            }
5693            if description.is_terminal() {
5694                let outcome =
5695                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5696                return Err(match outcome.kind {
5697                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5698                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5699                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5700                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5701                });
5702            }
5703            if started.elapsed() >= options.timeout {
5704                return Err(Error::Timeout);
5705            }
5706            tokio::time::sleep(options.poll_interval).await;
5707        }
5708    }
5709
5710    async fn result_target(
5711        &self,
5712        options: WorkflowResultOptions,
5713        selected_run_id: Option<&str>,
5714    ) -> Result<Value> {
5715        let started = Instant::now();
5716
5717        loop {
5718            let description = match selected_run_id {
5719                Some(run_id) => {
5720                    self.client
5721                        .describe_workflow_run(&self.workflow_id, run_id)
5722                        .await?
5723                }
5724                None => self.describe().await?,
5725            };
5726            if description.is_completed() {
5727                return Ok(description.output.unwrap_or(Value::Null));
5728            }
5729
5730            if description.is_terminal() {
5731                let outcome =
5732                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5733                return Err(match outcome.kind {
5734                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5735                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5736                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5737                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5738                });
5739            }
5740
5741            if started.elapsed() >= options.timeout {
5742                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5743                    kind: WorkflowTerminalKind::TimedOut,
5744                    workflow_id: description
5745                        .workflow_id
5746                        .clone()
5747                        .unwrap_or_else(|| self.workflow_id.clone()),
5748                    run_id: description
5749                        .run_id
5750                        .clone()
5751                        .or_else(|| selected_run_id.map(str::to_string)),
5752                    reason: "result_wait_timeout".to_string(),
5753                    failure_category: Some("client_timeout".to_string()),
5754                    failure_id: None,
5755                    exception_type: None,
5756                    exception_class: None,
5757                    non_retryable: None,
5758                    message: Some(format!(
5759                        "workflow result was not terminal within {:?}",
5760                        options.timeout
5761                    )),
5762                    exception: None,
5763                    raw: description.raw_value(),
5764                }));
5765            }
5766
5767            tokio::time::sleep(options.poll_interval).await;
5768        }
5769    }
5770}
5771
5772#[derive(Clone, Copy, Debug)]
5773pub struct WorkflowResultOptions {
5774    pub poll_interval: Duration,
5775    pub timeout: Duration,
5776}
5777
5778impl Default for WorkflowResultOptions {
5779    fn default() -> Self {
5780        Self {
5781            poll_interval: Duration::from_millis(500),
5782            timeout: Duration::from_secs(30),
5783        }
5784    }
5785}
5786
5787#[derive(Clone, Debug, Deserialize)]
5788pub struct WorkflowDescription {
5789    pub workflow_id: Option<String>,
5790    pub run_id: Option<String>,
5791    pub workflow_type: Option<String>,
5792    pub status: Option<String>,
5793    #[serde(default)]
5794    pub closed_reason: Option<String>,
5795    #[serde(default)]
5796    pub error: Option<String>,
5797    #[serde(default)]
5798    pub failure: Option<Value>,
5799    #[serde(default)]
5800    pub exception: Option<Value>,
5801    #[serde(default)]
5802    pub failures: Vec<Value>,
5803    #[serde(default)]
5804    pub output: Option<Value>,
5805    #[serde(default)]
5806    pub output_envelope: Option<Value>,
5807    #[serde(skip)]
5808    pub output_avro_value: Option<AvroValue>,
5809    #[serde(flatten)]
5810    pub raw: HashMap<String, Value>,
5811}
5812
5813/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5814#[derive(Clone, Debug, Deserialize)]
5815pub struct WorkflowStreamDescription {
5816    pub stream_name: String,
5817    pub status: String,
5818    pub last_offset: i64,
5819    pub total_items: u64,
5820    pub pending_items: u64,
5821    #[serde(default)]
5822    pub opened_at: Option<String>,
5823    #[serde(default)]
5824    pub last_appended_at: Option<String>,
5825    #[serde(default)]
5826    pub closed_at: Option<String>,
5827    #[serde(default)]
5828    pub error_reason: Option<String>,
5829    #[serde(default)]
5830    pub retention_seconds: Option<u64>,
5831    #[serde(flatten)]
5832    pub raw: HashMap<String, Value>,
5833}
5834
5835impl WorkflowStreamDescription {
5836    pub fn is_terminal(&self) -> bool {
5837        matches!(self.status.as_str(), "closed" | "errored")
5838    }
5839}
5840
5841/// One item for direct or replay-safe append.
5842#[derive(Clone, Debug, Default)]
5843pub struct WorkflowStreamAppendItem {
5844    pub payload_envelope: Option<Value>,
5845    pub payload_reference: Option<String>,
5846    pub item_type: Option<String>,
5847    pub content_type: Option<String>,
5848    pub idempotency_key: Option<String>,
5849}
5850
5851impl WorkflowStreamAppendItem {
5852    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5853    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5854        let value = AvroValue::from_serialize(&payload)?;
5855        Ok(Self {
5856            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5857            ..Self::default()
5858        })
5859    }
5860
5861    /// Preserve an external payload URI as an opaque service-contract reference.
5862    pub fn from_reference(reference: impl Into<String>) -> Self {
5863        Self {
5864            payload_reference: Some(reference.into()),
5865            ..Self::default()
5866        }
5867    }
5868
5869    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5870        self.item_type = Some(item_type.into());
5871        self
5872    }
5873
5874    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5875        self.content_type = Some(content_type.into());
5876        self
5877    }
5878
5879    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5880        self.idempotency_key = Some(idempotency_key.into());
5881        self
5882    }
5883
5884    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5885        let mut item = serde_json::Map::new();
5886        if let Some(payload) = &self.payload_envelope {
5887            item.insert("payload".to_string(), payload.clone());
5888            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5889        }
5890        if let Some(reference) = &self.payload_reference {
5891            item.insert("payload_reference".to_string(), json!(reference));
5892        }
5893        if let Some(item_type) = &self.item_type {
5894            item.insert("item_type".to_string(), json!(item_type));
5895        }
5896        if let Some(content_type) = &self.content_type {
5897            item.insert("content_type".to_string(), json!(content_type));
5898        }
5899        if let Some(key) = derived_idempotency_key
5900            .as_ref()
5901            .or(self.idempotency_key.as_ref())
5902        {
5903            item.insert("idempotency_key".to_string(), json!(key));
5904        }
5905        Value::Object(item)
5906    }
5907}
5908
5909/// One durable item at its stable zero-based offset.
5910#[derive(Clone, Debug)]
5911pub struct WorkflowStreamItem {
5912    pub offset: u64,
5913    pub payload: Option<Value>,
5914    pub payload_envelope: Option<Value>,
5915    pub payload_reference: Option<String>,
5916    pub payload_codec: Option<String>,
5917    pub idempotency_key: Option<String>,
5918    pub item_type: Option<String>,
5919    pub content_type: Option<String>,
5920    pub origin: Option<String>,
5921    pub origin_reference: Option<String>,
5922    pub emitted_at: Option<String>,
5923    pub raw: Value,
5924}
5925
5926/// One bounded at-least-once subscription page.
5927#[derive(Clone, Debug)]
5928pub struct WorkflowStreamPage {
5929    pub stream: WorkflowStreamDescription,
5930    pub items: Vec<WorkflowStreamItem>,
5931    pub next_offset: u64,
5932    pub terminal: bool,
5933}
5934
5935/// Durable acceptance and deduplication outcome for an append request.
5936#[derive(Clone, Debug)]
5937pub struct WorkflowStreamAppendResult {
5938    pub stream: WorkflowStreamDescription,
5939    pub accepted_offsets: Vec<u64>,
5940    pub accepted: u64,
5941    pub deduped: u64,
5942}
5943
5944#[derive(Deserialize)]
5945struct WorkflowStreamListResponse {
5946    #[serde(default)]
5947    streams: Vec<WorkflowStreamDescription>,
5948}
5949
5950#[derive(Deserialize)]
5951struct WorkflowStreamDescriptionResponse {
5952    stream: WorkflowStreamDescription,
5953}
5954
5955#[derive(Deserialize)]
5956struct WorkflowStreamPageResponse {
5957    stream: WorkflowStreamDescription,
5958    #[serde(default)]
5959    items: Vec<Value>,
5960    next_offset: u64,
5961    terminal: bool,
5962}
5963
5964#[derive(Deserialize)]
5965struct WorkflowStreamAppendResponse {
5966    stream: WorkflowStreamDescription,
5967    #[serde(default)]
5968    accepted_offsets: Vec<u64>,
5969    accepted: u64,
5970    deduped: u64,
5971}
5972
5973impl WorkflowDescription {
5974    pub fn is_completed(&self) -> bool {
5975        matches!(self.status.as_deref(), Some("completed" | "Completed"))
5976    }
5977
5978    pub fn is_terminal(&self) -> bool {
5979        matches!(
5980            self.status.as_deref(),
5981            Some(
5982                "completed"
5983                    | "Completed"
5984                    | "failed"
5985                    | "Failed"
5986                    | "cancelled"
5987                    | "Cancelled"
5988                    | "terminated"
5989                    | "Terminated"
5990                    | "timed_out"
5991                    | "TimedOut",
5992            )
5993        )
5994    }
5995
5996    fn decode_payloads(&mut self) -> Result<()> {
5997        if let Some(envelope) = &self.output_envelope {
5998            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
5999            self.output = Some(value.clone().into_json()?);
6000            self.output_avro_value = Some(value);
6001        }
6002
6003        Ok(())
6004    }
6005
6006    fn raw_value(&self) -> Value {
6007        let mut data = self.raw.clone();
6008        data.insert(
6009            "workflow_id".to_string(),
6010            self.workflow_id
6011                .clone()
6012                .map(Value::String)
6013                .unwrap_or(Value::Null),
6014        );
6015        data.insert(
6016            "run_id".to_string(),
6017            self.run_id
6018                .clone()
6019                .map(Value::String)
6020                .unwrap_or(Value::Null),
6021        );
6022        data.insert(
6023            "workflow_type".to_string(),
6024            self.workflow_type
6025                .clone()
6026                .map(Value::String)
6027                .unwrap_or(Value::Null),
6028        );
6029        data.insert(
6030            "status".to_string(),
6031            self.status
6032                .clone()
6033                .map(Value::String)
6034                .unwrap_or(Value::Null),
6035        );
6036        data.insert(
6037            "closed_reason".to_string(),
6038            self.closed_reason
6039                .clone()
6040                .map(Value::String)
6041                .unwrap_or(Value::Null),
6042        );
6043        if let Some(failure) = &self.failure {
6044            data.insert("failure".to_string(), failure.clone());
6045        }
6046        if let Some(exception) = &self.exception {
6047            data.insert("exception".to_string(), exception.clone());
6048        }
6049        Value::Object(data.into_iter().collect())
6050    }
6051}
6052
6053fn workflow_terminal_outcome(
6054    description: &WorkflowDescription,
6055    workflow_id: &str,
6056    run_id: Option<&str>,
6057) -> WorkflowTerminalOutcome {
6058    let terminal_kind = description
6059        .closed_reason
6060        .as_deref()
6061        .or(description.status.as_deref())
6062        .unwrap_or("failed")
6063        .to_ascii_lowercase();
6064    let kind = match terminal_kind.as_str() {
6065        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6066        "terminated" => WorkflowTerminalKind::Terminated,
6067        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6068        _ => WorkflowTerminalKind::Failed,
6069    };
6070    let default_reason = match kind {
6071        WorkflowTerminalKind::Failed => "workflow_failed",
6072        WorkflowTerminalKind::Cancelled => "cancelled",
6073        WorkflowTerminalKind::Terminated => "terminated",
6074        WorkflowTerminalKind::TimedOut => "timed_out",
6075    };
6076    let failure = description
6077        .failure
6078        .as_ref()
6079        .filter(|value| value.is_object());
6080    let nested_failure = failure
6081        .and_then(|value| value.get("failures"))
6082        .and_then(Value::as_array)
6083        .and_then(|failures| failures.last())
6084        .or_else(|| description.failures.last());
6085    let exception = description
6086        .exception
6087        .clone()
6088        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6089        .or_else(|| {
6090            nested_failure
6091                .and_then(|value| value.get("exception_payload"))
6092                .cloned()
6093        });
6094    let string_field = |name: &str| {
6095        failure
6096            .and_then(|value| value.get(name))
6097            .and_then(Value::as_str)
6098            .or_else(|| {
6099                nested_failure
6100                    .and_then(|value| value.get(name))
6101                    .and_then(Value::as_str)
6102            })
6103            .map(str::to_string)
6104    };
6105    let exception_field = |name: &str| {
6106        exception
6107            .as_ref()
6108            .and_then(|value| value.get(name))
6109            .and_then(Value::as_str)
6110            .map(str::to_string)
6111    };
6112    let message = description
6113        .error
6114        .clone()
6115        .or_else(|| string_field("message"))
6116        .or_else(|| exception_field("message"));
6117    let reason = description
6118        .raw
6119        .get("reason")
6120        .and_then(Value::as_str)
6121        .map(str::to_string)
6122        .or_else(|| {
6123            failure
6124                .and_then(|value| value.get("reason"))
6125                .and_then(Value::as_str)
6126                .map(str::to_string)
6127        })
6128        .or_else(|| description.closed_reason.clone())
6129        .unwrap_or_else(|| default_reason.to_string());
6130    let failure_id = string_field("failure_id").or_else(|| {
6131        nested_failure
6132            .and_then(|value| value.get("id"))
6133            .and_then(Value::as_str)
6134            .map(str::to_string)
6135    });
6136
6137    WorkflowTerminalOutcome {
6138        kind,
6139        workflow_id: description
6140            .workflow_id
6141            .clone()
6142            .unwrap_or_else(|| workflow_id.to_string()),
6143        run_id: description
6144            .run_id
6145            .clone()
6146            .or_else(|| run_id.map(str::to_string)),
6147        reason,
6148        failure_category: string_field("failure_category")
6149            .or_else(|| Some(default_reason.to_string())),
6150        failure_id,
6151        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6152        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6153        non_retryable: failure
6154            .and_then(|value| value.get("non_retryable"))
6155            .and_then(Value::as_bool)
6156            .or_else(|| {
6157                nested_failure
6158                    .and_then(|value| value.get("non_retryable"))
6159                    .and_then(Value::as_bool)
6160            }),
6161        message,
6162        exception,
6163        raw: description.raw_value(),
6164    }
6165}
6166
6167#[derive(Clone, Debug, Deserialize)]
6168pub struct RegisterWorkerResponse {
6169    pub worker_id: String,
6170    pub registered: bool,
6171    #[serde(default)]
6172    pub heartbeat_interval_seconds: Option<u64>,
6173    #[serde(default)]
6174    pub protocol_version: Option<String>,
6175    #[serde(default)]
6176    pub server_capabilities: Option<Value>,
6177}
6178
6179/// Result of gracefully removing a worker-plane registration.
6180#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6181pub struct WorkerDeregistrationEnvelope {
6182    pub worker_id: String,
6183    pub outcome: String,
6184    pub recovered_workflow_task_count: u64,
6185}
6186
6187#[derive(Clone, Debug, Deserialize)]
6188pub struct PollWorkflowTaskResponse {
6189    #[serde(default)]
6190    pub task: Option<WorkflowTask>,
6191    #[serde(default)]
6192    pub poll_status: Option<String>,
6193    #[serde(default)]
6194    pub reason: Option<String>,
6195    #[serde(default)]
6196    pub protocol_version: Option<String>,
6197    #[serde(default)]
6198    pub server_capabilities: Option<Value>,
6199}
6200
6201impl PollWorkflowTaskResponse {
6202    /// Classify this response without parsing server display text.
6203    pub fn outcome(&self) -> WorkerPollOutcome {
6204        worker_poll_outcome(
6205            self.task.is_some(),
6206            self.poll_status.as_deref(),
6207            self.reason.as_deref(),
6208        )
6209    }
6210}
6211
6212fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6213    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6214        return false;
6215    };
6216    let supported = capabilities
6217        .get("workflow_memo_updates")
6218        .and_then(Value::as_object)
6219        .and_then(|memo| memo.get("supported"))
6220        .and_then(Value::as_bool)
6221        == Some(true);
6222    let command_advertised = capabilities
6223        .get("supported_workflow_task_commands")
6224        .and_then(Value::as_array)
6225        .is_some_and(|commands| {
6226            commands
6227                .iter()
6228                .any(|command| command.as_str() == Some("upsert_memo"))
6229        });
6230    supported && command_advertised
6231}
6232
6233fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6234    commands
6235        .iter()
6236        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6237}
6238
6239#[derive(Clone, Debug, Deserialize)]
6240pub struct PollActivityTaskResponse {
6241    #[serde(default)]
6242    pub task: Option<ActivityTask>,
6243    #[serde(default)]
6244    pub poll_status: Option<String>,
6245    #[serde(default)]
6246    pub reason: Option<String>,
6247}
6248
6249impl PollActivityTaskResponse {
6250    /// Classify this response without parsing server display text.
6251    pub fn outcome(&self) -> WorkerPollOutcome {
6252        worker_poll_outcome(
6253            self.task.is_some(),
6254            self.poll_status.as_deref(),
6255            self.reason.as_deref(),
6256        )
6257    }
6258}
6259
6260#[derive(Clone, Debug, Deserialize)]
6261pub struct PollQueryTaskResponse {
6262    #[serde(default)]
6263    pub task: Option<QueryTask>,
6264    #[serde(default)]
6265    pub poll_status: Option<String>,
6266    #[serde(default)]
6267    pub reason: Option<String>,
6268}
6269
6270impl PollQueryTaskResponse {
6271    /// Classify this response without parsing server display text.
6272    pub fn outcome(&self) -> WorkerPollOutcome {
6273        worker_poll_outcome(
6274            self.task.is_some(),
6275            self.poll_status.as_deref(),
6276            self.reason.as_deref(),
6277        )
6278    }
6279}
6280
6281/// Stable classification for worker poll responses.
6282#[derive(Clone, Debug, PartialEq, Eq)]
6283pub enum WorkerPollOutcome {
6284    /// A task was leased and is available on the response.
6285    Task,
6286    /// No task was leased, but the worker should continue polling.
6287    Idle {
6288        poll_status: Option<String>,
6289        reason: Option<String>,
6290    },
6291    /// The server asked this worker to stop claiming new work.
6292    Stop {
6293        poll_status: Option<String>,
6294        reason: Option<String>,
6295    },
6296}
6297
6298impl WorkerPollOutcome {
6299    pub fn should_stop(&self) -> bool {
6300        matches!(self, Self::Stop { .. })
6301    }
6302}
6303
6304fn worker_poll_outcome(
6305    has_task: bool,
6306    poll_status: Option<&str>,
6307    reason: Option<&str>,
6308) -> WorkerPollOutcome {
6309    if worker_poll_is_stop(poll_status, reason) {
6310        return WorkerPollOutcome::Stop {
6311            poll_status: poll_status.map(str::to_string),
6312            reason: reason.map(str::to_string),
6313        };
6314    }
6315
6316    if has_task {
6317        WorkerPollOutcome::Task
6318    } else {
6319        WorkerPollOutcome::Idle {
6320            poll_status: poll_status.map(str::to_string),
6321            reason: reason.map(str::to_string),
6322        }
6323    }
6324}
6325
6326/// An ephemeral server-routed query task.
6327#[derive(Clone, Debug, Deserialize)]
6328pub struct QueryTask {
6329    pub query_task_id: String,
6330    #[serde(default = "default_workflow_task_attempt")]
6331    pub query_task_attempt: u64,
6332    #[serde(default)]
6333    pub lease_owner: Option<String>,
6334    #[serde(default)]
6335    pub workflow_id: Option<String>,
6336    #[serde(default)]
6337    pub run_id: Option<String>,
6338    pub workflow_type: String,
6339    pub query_name: String,
6340    #[serde(
6341        default = "missing_task_payload_codec",
6342        deserialize_with = "deserialize_task_payload_codec"
6343    )]
6344    pub payload_codec: String,
6345    #[serde(default)]
6346    pub workflow_arguments: Option<Value>,
6347    #[serde(default)]
6348    pub query_arguments: Option<Value>,
6349    #[serde(default)]
6350    pub history_events: Vec<HistoryEvent>,
6351    #[serde(default)]
6352    pub history_export: Option<Value>,
6353    #[serde(default)]
6354    pub run_status: Option<String>,
6355}
6356
6357#[derive(Clone, Debug, Deserialize)]
6358pub struct WorkflowTask {
6359    pub task_id: String,
6360    #[serde(default)]
6361    pub workflow_command_id: Option<String>,
6362    #[serde(default)]
6363    pub workflow_id: Option<String>,
6364    #[serde(default)]
6365    pub run_id: Option<String>,
6366    pub workflow_type: String,
6367    #[serde(default)]
6368    pub cancel_requested: bool,
6369    #[serde(
6370        default = "missing_task_payload_codec",
6371        deserialize_with = "deserialize_task_payload_codec"
6372    )]
6373    pub payload_codec: String,
6374    #[serde(default)]
6375    pub arguments: Option<Value>,
6376    #[serde(default)]
6377    pub history_events: Vec<HistoryEvent>,
6378    #[serde(default)]
6379    pub total_history_events: Option<u64>,
6380    #[serde(default)]
6381    pub history_size_bytes: Option<u64>,
6382    #[serde(default)]
6383    pub continue_as_new_recommended: Option<bool>,
6384    #[serde(default)]
6385    pub history_budget_pressure: Option<String>,
6386    #[serde(default)]
6387    pub next_history_page_token: Option<String>,
6388    #[serde(default = "default_workflow_task_attempt")]
6389    pub workflow_task_attempt: u64,
6390    #[serde(default)]
6391    pub workflow_signal_id: Option<String>,
6392    #[serde(default)]
6393    pub signal_name: Option<String>,
6394    #[serde(default)]
6395    pub signal_arguments: Option<Value>,
6396    #[serde(default)]
6397    pub workflow_update_id: Option<String>,
6398    #[serde(default)]
6399    pub update_name: Option<String>,
6400    #[serde(default)]
6401    pub lease_owner: Option<String>,
6402}
6403
6404impl WorkflowTask {
6405    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6406        self.history_events.extend(page.history_events);
6407
6408        if page.total_history_events.is_some() {
6409            self.total_history_events = page.total_history_events;
6410        }
6411
6412        self.next_history_page_token = page
6413            .next_history_page_token
6414            .filter(|token| !token.is_empty());
6415    }
6416}
6417
6418#[derive(Clone, Debug, Deserialize)]
6419struct WorkflowTaskHistoryPage {
6420    #[serde(default)]
6421    history_events: Vec<HistoryEvent>,
6422    #[serde(default)]
6423    total_history_events: Option<u64>,
6424    #[serde(default)]
6425    next_history_page_token: Option<String>,
6426}
6427
6428#[derive(Clone, Debug, Deserialize)]
6429pub struct ActivityTask {
6430    pub task_id: String,
6431    #[serde(default)]
6432    pub activity_attempt_id: Option<String>,
6433    #[serde(default)]
6434    pub attempt_id: Option<String>,
6435    pub activity_type: String,
6436    #[serde(
6437        default = "missing_task_payload_codec",
6438        deserialize_with = "deserialize_task_payload_codec"
6439    )]
6440    pub payload_codec: String,
6441    #[serde(default)]
6442    pub arguments: Option<Value>,
6443    #[serde(default = "default_attempt_number")]
6444    pub attempt_number: u64,
6445    #[serde(default)]
6446    pub lease_owner: Option<String>,
6447}
6448
6449#[derive(Clone, Debug, Serialize, Deserialize)]
6450pub struct HistoryEvent {
6451    #[serde(alias = "type")]
6452    pub event_type: String,
6453    #[serde(default)]
6454    pub payload: Value,
6455    #[serde(flatten)]
6456    pub raw: HashMap<String, Value>,
6457}
6458
6459/// One decoded signal in the committed workflow-history snapshot.
6460#[derive(Clone, Debug, PartialEq)]
6461pub struct QuerySignal {
6462    pub id: Option<String>,
6463    pub name: String,
6464    pub arguments: Vec<Value>,
6465    avro_arguments: Vec<AvroValue>,
6466    pub workflow_sequence: Option<u64>,
6467}
6468
6469impl QuerySignal {
6470    /// Lossless fixed Avro Value arguments for this committed signal.
6471    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6472        &self.avro_arguments
6473    }
6474}
6475
6476/// Immutable state supplied to a registered query handler.
6477///
6478/// This context intentionally exposes no activity, signal-wait, or command
6479/// APIs. Query handlers inspect committed history and return a value; query
6480/// completion does not append an event or advance deterministic execution.
6481#[derive(Clone, Debug)]
6482pub struct QueryContext {
6483    pub workflow_id: Option<String>,
6484    pub run_id: Option<String>,
6485    pub workflow_type: String,
6486    pub run_status: Option<String>,
6487    workflow_input: Value,
6488    workflow_input_avro_value: AvroValue,
6489    history_events: Arc<Vec<HistoryEvent>>,
6490    signal_events: Arc<Vec<QuerySignal>>,
6491}
6492
6493impl QueryContext {
6494    /// The normalized argument list used to start the workflow.
6495    pub fn workflow_input(&self) -> &Value {
6496        &self.workflow_input
6497    }
6498
6499    /// The lossless fixed Avro Value argument list used to start the workflow.
6500    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6501        &self.workflow_input_avro_value
6502    }
6503
6504    /// The immutable committed history used for this query snapshot.
6505    pub fn history_events(&self) -> &[HistoryEvent] {
6506        self.history_events.as_slice()
6507    }
6508
6509    /// All decoded signals in committed workflow order.
6510    pub fn signal_events(&self) -> &[QuerySignal] {
6511        self.signal_events.as_slice()
6512    }
6513
6514    /// Decoded argument lists for each committed signal with `signal_name`.
6515    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6516        self.signal_events
6517            .iter()
6518            .filter(|signal| signal.name == signal_name)
6519            .map(|signal| signal.arguments.clone())
6520            .collect()
6521    }
6522
6523    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6524    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6525        self.signal_events
6526            .iter()
6527            .filter(|signal| signal.name == signal_name)
6528            .map(|signal| signal.avro_arguments.clone())
6529            .collect()
6530    }
6531}
6532
6533#[derive(Clone, Debug, Deserialize)]
6534pub struct ActivityHeartbeatResponse {
6535    #[serde(default)]
6536    pub cancel_requested: bool,
6537    #[serde(default)]
6538    pub heartbeat_recorded: bool,
6539    #[serde(default)]
6540    pub can_continue: Option<bool>,
6541    #[serde(default)]
6542    pub reason: Option<String>,
6543    #[serde(default)]
6544    pub run_closed_reason: Option<String>,
6545    #[serde(default)]
6546    pub run_closed_at: Option<String>,
6547    #[serde(default)]
6548    pub lease_expires_at: Option<String>,
6549    #[serde(default)]
6550    pub last_heartbeat_at: Option<String>,
6551}
6552
6553impl ActivityHeartbeatResponse {
6554    /// Whether the activity should stop instead of attempting completion.
6555    pub fn should_stop(&self) -> bool {
6556        self.cancel_requested || self.can_continue == Some(false)
6557    }
6558}
6559
6560fn missing_task_payload_codec() -> String {
6561    MISSING_TASK_PAYLOAD_CODEC.to_string()
6562}
6563
6564fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6565where
6566    D: Deserializer<'de>,
6567{
6568    Ok(match Value::deserialize(deserializer)? {
6569        Value::String(codec) => codec,
6570        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6571        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6572    })
6573}
6574
6575fn default_workflow_task_attempt() -> u64 {
6576    1
6577}
6578
6579fn default_attempt_number() -> u64 {
6580    1
6581}
6582
6583type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6584type WorkflowHandler = Arc<dyn Fn(WorkflowContext, AvroValue) -> WorkflowFuture + Send + Sync>;
6585type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6586type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6587type ReplayedWorkflowHandler =
6588    Arc<dyn Fn(WorkflowContext, AvroValue) -> ReplayedWorkflowInvocation + Send + Sync>;
6589type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6590type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6591type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6592type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6593type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6594type ReplayedQueryHandler = Arc<
6595    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6596        + Send
6597        + Sync,
6598>;
6599type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6600
6601struct ReplayedWorkflowInvocation {
6602    future: WorkflowFuture,
6603    snapshot: WorkflowStateSnapshot,
6604}
6605
6606#[derive(Clone)]
6607struct RegisteredWorkflow {
6608    execute: WorkflowHandler,
6609    replay: Option<ReplayedWorkflowHandler>,
6610    state_type: Option<TypeId>,
6611    definition_fingerprint: Option<String>,
6612}
6613
6614fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6615    names
6616        .iter()
6617        .map(|name| {
6618            json!({
6619                "name": name,
6620                "parameters": [{
6621                    "name": "args",
6622                    "position": 0,
6623                    "required": false,
6624                    "variadic": true,
6625                    "type": null,
6626                    "allows_null": true,
6627                    "default_available": false,
6628                    "default": null,
6629                }],
6630            })
6631        })
6632        .collect()
6633}
6634
6635#[derive(Debug)]
6636struct WorkflowTaskDecision {
6637    commands: Vec<Value>,
6638    message_stream_cursors: Vec<Value>,
6639    message_stream_waits: Vec<Value>,
6640    cancellation_delivery: Option<CancellationDelivery>,
6641    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6642    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6643}
6644
6645enum PreparedWorkflowTask {
6646    Decision(WorkflowTaskDecision),
6647    Execution {
6648        task: WorkflowTask,
6649        context: WorkflowContext,
6650        future: WorkflowFuture,
6651    },
6652}
6653
6654impl WorkflowTaskDecision {
6655    fn without_message_streams(commands: Vec<Value>) -> Self {
6656        Self {
6657            commands,
6658            message_stream_cursors: Vec::new(),
6659            message_stream_waits: Vec::new(),
6660            cancellation_delivery: None,
6661            cancellation_scope_opening: None,
6662            cancellation_scope_delivery: None,
6663        }
6664    }
6665}
6666
6667#[derive(Clone)]
6668enum RegisteredQuery {
6669    Snapshot(QueryHandler),
6670    Replayed {
6671        state_type: TypeId,
6672        handler: ReplayedQueryHandler,
6673    },
6674}
6675
6676#[derive(Clone, Debug)]
6677pub struct WorkerHeartbeatObservation {
6678    pub worker_id: String,
6679    pub task_queue: String,
6680    pub acknowledged_at_unix_millis: u64,
6681    pub acknowledgement: Value,
6682}
6683
6684/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6685///
6686/// Expected empty long polls and explicit Server capacity backpressure are
6687/// normal worker states. Capacity backpressure honors the advertised retry
6688/// delay without consuming this retry budget. Other transport failures,
6689/// retryable HTTP 408/429 responses, and server errors are retried with capped
6690/// exponential backoff. Authentication, protocol, codec, and handler failures
6691/// are never retried by the worker.
6692/// Explicit storage admission pauses also preserve the already-serialized worker
6693/// request without consuming this budget or rerunning its handler. The delay is
6694/// capped by `max_backoff`, except an explicit completion deferral must honor
6695/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
6696/// completion retries remain bounded by the original cleanup deadline.
6697/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6698/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6699/// and `max_retries = 0` disables ordinary retries in either mode.
6700#[derive(Clone, Copy, Debug)]
6701pub struct WorkerRetryPolicy {
6702    /// Number of retries after the initial request fails.
6703    pub max_retries: usize,
6704    /// Delay before the first retry.
6705    pub initial_backoff: Duration,
6706    /// Maximum delay between retries.
6707    pub max_backoff: Duration,
6708}
6709
6710impl Default for WorkerRetryPolicy {
6711    fn default() -> Self {
6712        Self {
6713            max_retries: 5,
6714            initial_backoff: Duration::from_millis(100),
6715            max_backoff: Duration::from_secs(5),
6716        }
6717    }
6718}
6719
6720#[derive(Clone, Debug)]
6721struct WorkerStorageAdmission {
6722    policy: WorkerRetryPolicy,
6723    stop: Arc<AtomicBool>,
6724    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
6725}
6726
6727struct StopWorkerOnDrop(Arc<AtomicBool>);
6728
6729impl Drop for StopWorkerOnDrop {
6730    fn drop(&mut self) {
6731        self.0.store(true, Ordering::SeqCst);
6732    }
6733}
6734
6735async fn wait_for_worker_stop(stop: &AtomicBool) {
6736    while !stop.load(Ordering::SeqCst) {
6737        tokio::time::sleep(Duration::from_millis(100)).await;
6738    }
6739}
6740
6741#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6742enum ManagedPollOutcome {
6743    Idle,
6744    Handled,
6745    Stop,
6746}
6747
6748#[derive(Clone)]
6749pub struct Worker {
6750    client: Client,
6751    worker_id: String,
6752    task_queue: String,
6753    workflows: HashMap<String, RegisteredWorkflow>,
6754    activities: HashMap<String, ActivityHandler>,
6755    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6756    signals: HashMap<String, Vec<String>>,
6757    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6758    registration_definitions:
6759        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
6760    registration_error: Option<DuplicateRegistrationError>,
6761    max_concurrent_workflow_tasks: usize,
6762    max_concurrent_activity_tasks: usize,
6763    poll_timeout: Duration,
6764    heartbeat_interval: Duration,
6765    retry_policy: WorkerRetryPolicy,
6766    recover_transient_outages: bool,
6767    run_stop: Option<Arc<AtomicBool>>,
6768    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6769    cooperative_cancellation_enabled: bool,
6770    allow_cancellation_scope_authoring: bool,
6771    allow_cancellation_scope_delivery: bool,
6772    cooperative_registration_confirmed: Arc<AtomicBool>,
6773    local_registration_confirmed: Arc<AtomicBool>,
6774    session_registration_confirmed: Arc<AtomicBool>,
6775    sticky_registration_confirmed: Arc<AtomicBool>,
6776    require_query_task_authority: bool,
6777    query_authority_confirmed: Arc<AtomicBool>,
6778    resource_capabilities: Vec<String>,
6779    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6780}
6781
6782impl Worker {
6783    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6784        Self {
6785            client,
6786            worker_id: default_worker_id(),
6787            task_queue: task_queue.into(),
6788            workflows: HashMap::new(),
6789            activities: HashMap::new(),
6790            queries: HashMap::new(),
6791            signals: HashMap::new(),
6792            updates: HashMap::new(),
6793            registration_definitions: HashMap::new(),
6794            registration_error: None,
6795            max_concurrent_workflow_tasks: 10,
6796            max_concurrent_activity_tasks: 10,
6797            poll_timeout: Duration::from_secs(30),
6798            heartbeat_interval: Duration::from_secs(60),
6799            retry_policy: WorkerRetryPolicy::default(),
6800            recover_transient_outages: false,
6801            run_stop: None,
6802            heartbeat_observer: None,
6803            cooperative_cancellation_enabled: false,
6804            allow_cancellation_scope_authoring: false,
6805            allow_cancellation_scope_delivery: false,
6806            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6807            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6808            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6809            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
6810            require_query_task_authority: false,
6811            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
6812            resource_capabilities: Vec::new(),
6813            sessions: Arc::new(Mutex::new(HashMap::new())),
6814        }
6815    }
6816
6817    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6818        self.worker_id = worker_id.into();
6819        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6820        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6821        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6822        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
6823        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
6824        self.client.reset_sticky_cache();
6825        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6826        self
6827    }
6828
6829    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6830        self.poll_timeout = timeout;
6831        self
6832    }
6833
6834    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6835        self.heartbeat_interval = interval;
6836        self
6837    }
6838
6839    /// Require original query timing and non-renewing runtime observation.
6840    ///
6841    /// Registration refuses before creating a Worker unless protocol 1.20 and
6842    /// the runtime's `query_task_authority` capability are available. By default,
6843    /// older Servers retain their weaker, disclosed local-timing behavior.
6844    pub fn require_query_task_authority(mut self, required: bool) -> Self {
6845        self.require_query_task_authority = required;
6846        self
6847    }
6848
6849    /// Explicitly enable inline local activities in this workflow worker.
6850    ///
6851    /// The worker advertises the capability to Server only when enabled.
6852    /// These callbacks must yield to Tokio and have idempotent side effects.
6853    /// Cooperative prepared local supervision is a separate capability.
6854    pub fn local_activities(mut self, enabled: bool) -> Self {
6855        self.client.local_activities_enabled = enabled;
6856        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6857        self
6858    }
6859
6860    /// Opt in to separate cooperative workflow cancellation requests.
6861    ///
6862    /// Registration requires the Server to acknowledge this exact worker,
6863    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6864    /// processing uses canonical delivery and activity ownership fences.
6865    /// Existing terminal cancel and terminate operations remain terminal.
6866    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
6867    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6868    /// and [`Worker::run_until`] register automatically.
6869    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6870        self.cooperative_cancellation_enabled = enabled;
6871        self.client.cooperative_worker_protocol = enabled;
6872        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6873        self
6874    }
6875
6876    /// Enable candidate scope authoring without advertising scoped execution.
6877    #[doc(hidden)]
6878    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6879        self.allow_cancellation_scope_authoring = enabled;
6880        self
6881    }
6882
6883    /// Enable the candidate scoped call consumer with canonical authoring.
6884    #[doc(hidden)]
6885    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6886        self.allow_cancellation_scope_delivery = enabled;
6887        self
6888    }
6889
6890    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6891    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6892        self.retry_policy = policy;
6893        self
6894    }
6895
6896    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6897    ///
6898    /// Retries preserve the poll request identity and use capped exponential
6899    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6900    /// An in-flight poll is allowed to finish so leased work is not discarded.
6901    /// Authentication, protocol, codec, handler and task settlement failures
6902    /// remain errors. Registration and deregistration are not retried here.
6903    ///
6904    /// The default is disabled, preserving the bounded retry contract.
6905    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6906    /// even when this option is enabled.
6907    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6908        self.recover_transient_outages = enabled;
6909        self
6910    }
6911
6912    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6913    where
6914        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6915    {
6916        self.heartbeat_observer = Some(Arc::new(observer));
6917        self
6918    }
6919
6920    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6921        self.max_concurrent_workflow_tasks = count.max(1);
6922        self
6923    }
6924
6925    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6926        self.max_concurrent_activity_tasks = count.max(1);
6927        self
6928    }
6929
6930    /// Validate local handler admission without making a Server request.
6931    ///
6932    /// Registration methods retain their existing signatures. A duplicate keeps
6933    /// the original handler and makes this Worker invalid, including its clones.
6934    /// `register`, `run`, `run_until` and `run_once` enforce this check before
6935    /// any network request. Build a new Worker to correct an invalid configuration.
6936    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
6937        match &self.registration_error {
6938            Some(error) => Err(error.clone()),
6939            None => Ok(()),
6940        }
6941    }
6942
6943    #[track_caller]
6944    fn admit_registration<F>(
6945        &mut self,
6946        handler_kind: RegistrationKind,
6947        workflow_type: Option<&str>,
6948        handler_name: &str,
6949        method: &'static str,
6950    ) -> bool {
6951        let location = std::panic::Location::caller();
6952        let definition = HandlerRegistration {
6953            method,
6954            handler_type: type_name::<F>(),
6955            file: location.file(),
6956            line: location.line(),
6957            column: location.column(),
6958        };
6959        let key = (
6960            handler_kind,
6961            workflow_type.map(str::to_owned),
6962            handler_name.to_owned(),
6963        );
6964        if let Some(first_definition) = self.registration_definitions.get(&key) {
6965            if self.registration_error.is_none() {
6966                self.registration_error = Some(DuplicateRegistrationError {
6967                    handler_kind,
6968                    workflow_type: key.1.clone(),
6969                    handler_name: key.2.clone(),
6970                    first_definition: first_definition.clone(),
6971                    second_definition: definition,
6972                });
6973            }
6974            return false;
6975        }
6976        self.registration_definitions.insert(key, definition);
6977        true
6978    }
6979
6980    /// Register a workflow handler.
6981    ///
6982    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6983    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6984    /// while acquiring or decoding a worker task remain worker-operation
6985    /// failures and do not get converted into workflow outcomes.
6986    #[track_caller]
6987    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6988    where
6989        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6990        Fut: Future<Output = Result<Value>> + Send + 'static,
6991    {
6992        let workflow_type = workflow_type.into();
6993        if !self.admit_registration::<F>(
6994            RegistrationKind::Workflow,
6995            None,
6996            &workflow_type,
6997            "register_workflow",
6998        ) {
6999            return;
7000        }
7001        let handler = Arc::new(handler);
7002        self.workflows.insert(
7003            workflow_type,
7004            RegisteredWorkflow {
7005                execute: Arc::new(move |ctx, input| {
7006                    let handler = Arc::clone(&handler);
7007                    Box::pin(async move {
7008                        let result = handler(ctx, input.into_json()?).await?;
7009                        AvroValue::from_serialize(&result)
7010                    })
7011                }),
7012                replay: None,
7013                state_type: None,
7014                definition_fingerprint: None,
7015            },
7016        );
7017    }
7018
7019    /// Register a workflow with one Serde request value and a Serde result.
7020    ///
7021    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7022    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7023    /// workflow-specific schema. A task must contain zero arguments for a unit
7024    /// request or exactly one argument for every other request type.
7025    ///
7026    /// See the runnable
7027    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7028    /// for typed workflow and activity contracts with retry and timeout policy.
7029    #[track_caller]
7030    pub fn register_typed_workflow<I, O, F, Fut>(
7031        &mut self,
7032        workflow_type: impl Into<String>,
7033        handler: F,
7034    ) where
7035        I: DeserializeOwned + Send + 'static,
7036        O: Serialize + Send + 'static,
7037        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7038        Fut: Future<Output = Result<O>> + Send + 'static,
7039    {
7040        let workflow_type = workflow_type.into();
7041        if !self.admit_registration::<F>(
7042            RegistrationKind::Workflow,
7043            None,
7044            &workflow_type,
7045            "register_typed_workflow",
7046        ) {
7047            return;
7048        }
7049        let handler_name = workflow_type.clone();
7050        let handler = Arc::new(handler);
7051        self.workflows.insert(
7052            workflow_type,
7053            RegisteredWorkflow {
7054                execute: Arc::new(move |ctx, input| {
7055                    let handler = Arc::clone(&handler);
7056                    let handler_name = handler_name.clone();
7057                    Box::pin(async move {
7058                        let input =
7059                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7060                        let result = handler(ctx, input).await?;
7061                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7062                    })
7063                }),
7064                replay: None,
7065                state_type: None,
7066                definition_fingerprint: None,
7067            },
7068        );
7069    }
7070
7071    /// Register a workflow on the lossless fixed Avro Value surface.
7072    #[track_caller]
7073    pub fn register_workflow_avro_value<F, Fut>(
7074        &mut self,
7075        workflow_type: impl Into<String>,
7076        handler: F,
7077    ) where
7078        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7079        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7080    {
7081        let workflow_type = workflow_type.into();
7082        if !self.admit_registration::<F>(
7083            RegistrationKind::Workflow,
7084            None,
7085            &workflow_type,
7086            "register_workflow_avro_value",
7087        ) {
7088            return;
7089        }
7090        self.workflows.insert(
7091            workflow_type,
7092            RegisteredWorkflow {
7093                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
7094                replay: None,
7095                state_type: None,
7096                definition_fingerprint: None,
7097            },
7098        );
7099    }
7100
7101    /// Register a workflow whose typed instance state can be reconstructed for queries.
7102    ///
7103    /// `state_factory` creates a fresh instance for every normal workflow task and
7104    /// query replay. The workflow handler is the single source of truth for state
7105    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7106    /// resolve. Query replay runs this same handler over committed history and
7107    /// discards any commands it would emit.
7108    #[track_caller]
7109    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7110        &mut self,
7111        workflow_type: impl Into<String>,
7112        state_factory: Factory,
7113        handler: F,
7114    ) where
7115        S: Clone + Send + Sync + 'static,
7116        Factory: Fn() -> S + Send + Sync + 'static,
7117        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7118        Fut: Future<Output = Result<Value>> + Send + 'static,
7119    {
7120        let workflow_type = workflow_type.into();
7121        if !self.admit_registration::<F>(
7122            RegistrationKind::Workflow,
7123            None,
7124            &workflow_type,
7125            "register_replayed_workflow",
7126        ) {
7127            return;
7128        }
7129        let state_factory = Arc::new(state_factory);
7130        let handler = Arc::new(handler);
7131
7132        let execute_factory = Arc::clone(&state_factory);
7133        let execute_handler = Arc::clone(&handler);
7134        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7135            let state = WorkflowInstance::new(execute_factory());
7136            let handler = Arc::clone(&execute_handler);
7137            Box::pin(async move {
7138                let result = handler(ctx, input.into_json()?, state).await?;
7139                AvroValue::from_serialize(&result)
7140            }) as WorkflowFuture
7141        });
7142
7143        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7144            let state = WorkflowInstance::new(state_factory());
7145            let snapshot_state = state.clone();
7146            let snapshot: WorkflowStateSnapshot =
7147                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7148            let replay_handler = Arc::clone(&handler);
7149            let future = async move {
7150                let result = replay_handler(ctx, input.into_json()?, state).await?;
7151                AvroValue::from_serialize(&result)
7152            };
7153            ReplayedWorkflowInvocation {
7154                future: Box::pin(future),
7155                snapshot,
7156            }
7157        });
7158
7159        self.workflows.insert(
7160            workflow_type,
7161            RegisteredWorkflow {
7162                execute,
7163                replay: Some(replay),
7164                state_type: Some(TypeId::of::<S>()),
7165                definition_fingerprint: None,
7166            },
7167        );
7168    }
7169
7170    /// Register a replayable workflow with one Serde request value and result.
7171    ///
7172    /// Normal task execution and instance-state query replay both decode and
7173    /// encode through the fixed Avro Value codec. The state factory and handler
7174    /// otherwise follow [`Worker::register_replayed_workflow`].
7175    #[track_caller]
7176    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7177        &mut self,
7178        workflow_type: impl Into<String>,
7179        state_factory: Factory,
7180        handler: F,
7181    ) where
7182        I: DeserializeOwned + Send + 'static,
7183        O: Serialize + Send + 'static,
7184        S: Clone + Send + Sync + 'static,
7185        Factory: Fn() -> S + Send + Sync + 'static,
7186        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7187        Fut: Future<Output = Result<O>> + Send + 'static,
7188    {
7189        let workflow_type = workflow_type.into();
7190        if !self.admit_registration::<F>(
7191            RegistrationKind::Workflow,
7192            None,
7193            &workflow_type,
7194            "register_typed_replayed_workflow",
7195        ) {
7196            return;
7197        }
7198        let state_factory = Arc::new(state_factory);
7199        let handler = Arc::new(handler);
7200
7201        let execute_name = workflow_type.clone();
7202        let execute_factory = Arc::clone(&state_factory);
7203        let execute_handler = Arc::clone(&handler);
7204        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7205            let state = WorkflowInstance::new(execute_factory());
7206            let handler = Arc::clone(&execute_handler);
7207            let handler_name = execute_name.clone();
7208            Box::pin(async move {
7209                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7210                let result = handler(ctx, input, state).await?;
7211                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7212            }) as WorkflowFuture
7213        });
7214
7215        let replay_name = workflow_type.clone();
7216        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7217            let state = WorkflowInstance::new(state_factory());
7218            let snapshot_state = state.clone();
7219            let snapshot: WorkflowStateSnapshot =
7220                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7221            let handler = Arc::clone(&handler);
7222            let handler_name = replay_name.clone();
7223            let future = async move {
7224                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7225                let result = handler(ctx, input, state).await?;
7226                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7227            };
7228            ReplayedWorkflowInvocation {
7229                future: Box::pin(future),
7230                snapshot,
7231            }
7232        });
7233
7234        self.workflows.insert(
7235            workflow_type,
7236            RegisteredWorkflow {
7237                execute,
7238                replay: Some(replay),
7239                state_type: Some(TypeId::of::<S>()),
7240                definition_fingerprint: None,
7241            },
7242        );
7243    }
7244
7245    /// Declare the signal names consumed by a registered workflow.
7246    ///
7247    /// Call this after registering the workflow and before starting the worker.
7248    /// Names read through `wait_signal` or `signals` need a declaration for
7249    /// Server command admission. Arguments remain arbitrary positional values,
7250    /// including lossless Avro values. This replaces the previous declaration;
7251    /// an empty slice declares no signals. Names are sorted and deduplicated.
7252    /// Existing runs retain the declarations captured when they started.
7253    pub fn declare_workflow_signals(
7254        &mut self,
7255        workflow_type: &str,
7256        signal_names: &[&str],
7257    ) -> Result<()> {
7258        if !self.workflows.contains_key(workflow_type) {
7259            return Err(Error::Codec(format!(
7260                "workflow type {workflow_type:?} is not registered"
7261            )));
7262        }
7263        if signal_names
7264            .iter()
7265            .any(|name| name.is_empty() || *name != name.trim())
7266        {
7267            return Err(Error::Codec(
7268                "signal names must be non-empty and have no surrounding whitespace".into(),
7269            ));
7270        }
7271        let mut names = signal_names
7272            .iter()
7273            .map(|name| (*name).to_string())
7274            .collect::<Vec<_>>();
7275        names.sort();
7276        names.dedup();
7277        self.signals.insert(workflow_type.to_string(), names);
7278        Ok(())
7279    }
7280
7281    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7282    ///
7283    /// Supply `include_str!` values for the workflow body and every helper whose
7284    /// behavior can affect replay. Register the workflow once, then set its
7285    /// identity before starting the worker. Duplicate registrations are invalid. The server
7286    /// rejects reusing a worker ID when its prior fingerprint disappears.
7287    /// Workflows without source identity remain runnable but cannot be safely redriven.
7288    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7289    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7290    pub fn set_workflow_definition_sources(
7291        &mut self,
7292        workflow_type: &str,
7293        sources: &[&str],
7294    ) -> Result<()> {
7295        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7296            return Err(Error::Codec(
7297                "workflow definition sources must be non-empty".to_string(),
7298            ));
7299        }
7300        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7301            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7302        })?;
7303        let mut hasher = Sha256::new();
7304        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7305        hasher.update((workflow_type.len() as u64).to_be_bytes());
7306        hasher.update(workflow_type.as_bytes());
7307        for source in sources {
7308            hasher.update((source.len() as u64).to_be_bytes());
7309            hasher.update(source.as_bytes());
7310        }
7311        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7312        Ok(())
7313    }
7314
7315    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7316    #[track_caller]
7317    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7318        &mut self,
7319        workflow_type: impl Into<String>,
7320        state_factory: Factory,
7321        handler: F,
7322    ) where
7323        S: Clone + Send + Sync + 'static,
7324        Factory: Fn() -> S + Send + Sync + 'static,
7325        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7326        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7327    {
7328        let workflow_type = workflow_type.into();
7329        if !self.admit_registration::<F>(
7330            RegistrationKind::Workflow,
7331            None,
7332            &workflow_type,
7333            "register_replayed_workflow_avro_value",
7334        ) {
7335            return;
7336        }
7337        let state_factory = Arc::new(state_factory);
7338        let handler = Arc::new(handler);
7339
7340        let execute_factory = Arc::clone(&state_factory);
7341        let execute_handler = Arc::clone(&handler);
7342        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7343            let state = WorkflowInstance::new(execute_factory());
7344            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
7345        });
7346
7347        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7348            let state = WorkflowInstance::new(state_factory());
7349            let snapshot_state = state.clone();
7350            let snapshot: WorkflowStateSnapshot =
7351                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7352            ReplayedWorkflowInvocation {
7353                future: Box::pin(handler(ctx, input, state)),
7354                snapshot,
7355            }
7356        });
7357
7358        self.workflows.insert(
7359            workflow_type,
7360            RegisteredWorkflow {
7361                execute,
7362                replay: Some(replay),
7363                state_type: Some(TypeId::of::<S>()),
7364                definition_fingerprint: None,
7365            },
7366        );
7367    }
7368
7369    #[track_caller]
7370    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7371    where
7372        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7373        Fut: Future<Output = Result<Value>> + Send + 'static,
7374    {
7375        let activity_type = activity_type.into();
7376        if !self.admit_registration::<F>(
7377            RegistrationKind::Activity,
7378            None,
7379            &activity_type,
7380            "register_activity",
7381        ) {
7382            return;
7383        }
7384        let handler = Arc::new(handler);
7385        self.activities.insert(
7386            activity_type,
7387            Arc::new(move |ctx, args| {
7388                let handler = Arc::clone(&handler);
7389                Box::pin(async move {
7390                    let result = handler(ctx, args.into_json()?).await?;
7391                    AvroValue::from_serialize(&result)
7392                })
7393            }),
7394        );
7395    }
7396
7397    /// Register an activity with one Serde request value and a Serde result.
7398    ///
7399    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7400    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7401    /// with the activity name and Rust type.
7402    #[track_caller]
7403    pub fn register_typed_activity<I, O, F, Fut>(
7404        &mut self,
7405        activity_type: impl Into<String>,
7406        handler: F,
7407    ) where
7408        I: DeserializeOwned + Send + 'static,
7409        O: Serialize + Send + 'static,
7410        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
7411        Fut: Future<Output = Result<O>> + Send + 'static,
7412    {
7413        let activity_type = activity_type.into();
7414        if !self.admit_registration::<F>(
7415            RegistrationKind::Activity,
7416            None,
7417            &activity_type,
7418            "register_typed_activity",
7419        ) {
7420            return;
7421        }
7422        let handler_name = activity_type.clone();
7423        let handler = Arc::new(handler);
7424        self.activities.insert(
7425            activity_type,
7426            Arc::new(move |ctx, input| {
7427                let handler = Arc::clone(&handler);
7428                let handler_name = handler_name.clone();
7429                Box::pin(async move {
7430                    let input =
7431                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
7432                    let result = handler(ctx, input).await?;
7433                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
7434                })
7435            }),
7436        );
7437    }
7438
7439    /// Register an activity on the lossless fixed Avro Value surface.
7440    #[track_caller]
7441    pub fn register_activity_avro_value<F, Fut>(
7442        &mut self,
7443        activity_type: impl Into<String>,
7444        handler: F,
7445    ) where
7446        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
7447        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7448    {
7449        let activity_type = activity_type.into();
7450        if !self.admit_registration::<F>(
7451            RegistrationKind::Activity,
7452            None,
7453            &activity_type,
7454            "register_activity_avro_value",
7455        ) {
7456            return;
7457        }
7458        self.activities.insert(
7459            activity_type,
7460            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7461        );
7462    }
7463
7464    /// Register a named, read-only query handler for a workflow type.
7465    ///
7466    /// The workflow type must also be registered with [`Worker::register_workflow`]
7467    /// before the worker runs. The handler receives only an immutable committed
7468    /// state snapshot and normalized query arguments.
7469    #[track_caller]
7470    pub fn register_query<F, Fut>(
7471        &mut self,
7472        workflow_type: impl Into<String>,
7473        query_name: impl Into<String>,
7474        handler: F,
7475    ) where
7476        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7477        Fut: Future<Output = Result<Value>> + Send + 'static,
7478    {
7479        let workflow_type = workflow_type.into();
7480        let query_name = query_name.into();
7481        if !self.admit_registration::<F>(
7482            RegistrationKind::Query,
7483            Some(&workflow_type),
7484            &query_name,
7485            "register_query",
7486        ) {
7487            return;
7488        }
7489        let handler = Arc::new(handler);
7490        self.queries.entry(workflow_type).or_default().insert(
7491            query_name,
7492            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
7493                let handler = Arc::clone(&handler);
7494                Box::pin(async move {
7495                    let result = handler(ctx, args.into_json()?).await?;
7496                    AvroValue::from_serialize(&result)
7497                })
7498            })),
7499        );
7500    }
7501
7502    /// Register a query handler on the lossless fixed Avro Value surface.
7503    #[track_caller]
7504    pub fn register_query_avro_value<F, Fut>(
7505        &mut self,
7506        workflow_type: impl Into<String>,
7507        query_name: impl Into<String>,
7508        handler: F,
7509    ) where
7510        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7511        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7512    {
7513        let workflow_type = workflow_type.into();
7514        let query_name = query_name.into();
7515        if !self.admit_registration::<F>(
7516            RegistrationKind::Query,
7517            Some(&workflow_type),
7518            &query_name,
7519            "register_query_avro_value",
7520        ) {
7521            return;
7522        }
7523        self.queries.entry(workflow_type).or_default().insert(
7524            query_name,
7525            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7526        );
7527    }
7528
7529    /// Register a named query against deterministically replayed instance state.
7530    ///
7531    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7532    /// same state type `S`. The handler receives an immutable, detached state
7533    /// clone, so successful and failed queries cannot affect workflow execution
7534    /// or the state reconstructed by a later query.
7535    #[track_caller]
7536    pub fn register_replayed_query<S, F, Fut>(
7537        &mut self,
7538        workflow_type: impl Into<String>,
7539        query_name: impl Into<String>,
7540        handler: F,
7541    ) where
7542        S: Clone + Send + Sync + 'static,
7543        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7544        Fut: Future<Output = Result<Value>> + Send + 'static,
7545    {
7546        let workflow_type = workflow_type.into();
7547        let query_name = query_name.into();
7548        if !self.admit_registration::<F>(
7549            RegistrationKind::Query,
7550            Some(&workflow_type),
7551            &query_name,
7552            "register_replayed_query",
7553        ) {
7554            return;
7555        }
7556        let handler = Arc::new(handler);
7557        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7558            let state = state.downcast::<S>().map_err(|_| {
7559                "registered query state type does not match the replayed workflow state".to_string()
7560            })?;
7561            let handler = Arc::clone(&handler);
7562            Ok(Box::pin(async move {
7563                let result = handler(ctx, state, args.into_json()?).await?;
7564                AvroValue::from_serialize(&result)
7565            }))
7566        });
7567
7568        self.queries.entry(workflow_type).or_default().insert(
7569            query_name,
7570            RegisteredQuery::Replayed {
7571                state_type: TypeId::of::<S>(),
7572                handler: erased_handler,
7573            },
7574        );
7575    }
7576
7577    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7578    #[track_caller]
7579    pub fn register_replayed_query_avro_value<S, F, Fut>(
7580        &mut self,
7581        workflow_type: impl Into<String>,
7582        query_name: impl Into<String>,
7583        handler: F,
7584    ) where
7585        S: Clone + Send + Sync + 'static,
7586        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7587        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7588    {
7589        let workflow_type = workflow_type.into();
7590        let query_name = query_name.into();
7591        if !self.admit_registration::<F>(
7592            RegistrationKind::Query,
7593            Some(&workflow_type),
7594            &query_name,
7595            "register_replayed_query_avro_value",
7596        ) {
7597            return;
7598        }
7599        let handler = Arc::new(handler);
7600        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7601            let state = state.downcast::<S>().map_err(|_| {
7602                "registered query state type does not match the replayed workflow state".to_string()
7603            })?;
7604            Ok(Box::pin(handler(ctx, state, args)))
7605        });
7606
7607        self.queries.entry(workflow_type).or_default().insert(
7608            query_name,
7609            RegisteredQuery::Replayed {
7610                state_type: TypeId::of::<S>(),
7611                handler: erased_handler,
7612            },
7613        );
7614    }
7615
7616    /// Register a synchronous workflow update handler.
7617    #[track_caller]
7618    pub fn register_update<F, Fut>(
7619        &mut self,
7620        workflow_type: impl Into<String>,
7621        update_name: impl Into<String>,
7622        handler: F,
7623    ) where
7624        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7625        Fut: Future<Output = Result<Value>> + Send + 'static,
7626    {
7627        let workflow_type = workflow_type.into();
7628        let update_name = update_name.into();
7629        if !self.admit_registration::<F>(
7630            RegistrationKind::Update,
7631            Some(&workflow_type),
7632            &update_name,
7633            "register_update",
7634        ) {
7635            return;
7636        }
7637        let handler = Arc::new(handler);
7638        self.updates.entry(workflow_type).or_default().insert(
7639            update_name,
7640            Arc::new(move |ctx, args| {
7641                let handler = Arc::clone(&handler);
7642                Box::pin(async move {
7643                    let result = handler(ctx, args.into_json()?).await?;
7644                    AvroValue::from_serialize(&result)
7645                })
7646            }),
7647        );
7648    }
7649
7650    /// Register an update handler on the lossless fixed Avro Value surface.
7651    #[track_caller]
7652    pub fn register_update_avro_value<F, Fut>(
7653        &mut self,
7654        workflow_type: impl Into<String>,
7655        update_name: impl Into<String>,
7656        handler: F,
7657    ) where
7658        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7659        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7660    {
7661        let workflow_type = workflow_type.into();
7662        let update_name = update_name.into();
7663        if !self.admit_registration::<F>(
7664            RegistrationKind::Update,
7665            Some(&workflow_type),
7666            &update_name,
7667            "register_update_avro_value",
7668        ) {
7669            return;
7670        }
7671        self.updates.entry(workflow_type).or_default().insert(
7672            update_name,
7673            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7674        );
7675    }
7676
7677    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7678        self.validate_registration()?;
7679        self.query_authority_confirmed
7680            .store(false, Ordering::SeqCst);
7681        if self.require_query_task_authority {
7682            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
7683                return Err(Error::WorkerLoop(
7684                    "query authority requires worker protocol 1.20".into(),
7685                ));
7686            }
7687            // Discovery uses the Worker credential, including worker-only Clients.
7688            let discovery: Value = self
7689                .client
7690                .request_json_unresolved_with_timeout::<Value, Value>(
7691                    reqwest::Method::GET,
7692                    "/cluster/info",
7693                    RequestProtocol::Worker("1.20"),
7694                    None,
7695                    Duration::from_secs(5),
7696                )
7697                .await?;
7698            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
7699                return Err(Error::WorkerLoop(
7700                    "runtime does not advertise query_task_authority".into(),
7701                ));
7702            }
7703        }
7704        self.sticky_registration_confirmed
7705            .store(false, Ordering::SeqCst);
7706        self.session_registration_confirmed
7707            .store(false, Ordering::SeqCst);
7708        for capability in &self.resource_capabilities {
7709            worker_session::validate_resource_capability(capability)?;
7710        }
7711        self.local_registration_confirmed
7712            .store(false, Ordering::SeqCst);
7713        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7714            return Err(Error::CooperativeCancellationUnavailable(
7715                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7716            ));
7717        }
7718        let mut command_contracts = serde_json::Map::new();
7719        for workflow_type in self.workflows.keys() {
7720            let mut queries = self
7721                .queries
7722                .get(workflow_type)
7723                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7724                .unwrap_or_default();
7725            queries.sort();
7726            let mut updates = self
7727                .updates
7728                .get(workflow_type)
7729                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7730                .unwrap_or_default();
7731            updates.sort();
7732            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7733            command_contracts.insert(
7734                workflow_type.clone(),
7735                json!({
7736                    "queries": queries,
7737                    "query_contracts": argument_vector_contracts(&queries),
7738                    "signals": signals,
7739                    "signal_contracts": argument_vector_contracts(&signals),
7740                    "updates": updates,
7741                    "update_contracts": argument_vector_contracts(&updates),
7742                    "update_validators": [],
7743                }),
7744            );
7745        }
7746
7747        self.cooperative_registration_confirmed
7748            .store(false, Ordering::SeqCst);
7749        let response = self
7750            .client
7751            .register_worker_with_definition_fingerprints(
7752                &self.worker_id,
7753                &self.task_queue,
7754                self.workflows.keys().cloned().collect(),
7755                self.activities.keys().cloned().collect(),
7756                self.max_concurrent_workflow_tasks,
7757                self.max_concurrent_activity_tasks,
7758                [
7759                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7760                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7761                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7762                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7763                    self.client
7764                        .local_activities_enabled
7765                        .then(|| "local_activities".to_string()),
7766                    self.client
7767                        .worker_sessions_enabled
7768                        .then(|| "worker_sessions".to_string()),
7769                    self.client
7770                        .sticky_cache
7771                        .is_some()
7772                        .then(|| "sticky_execution".to_string()),
7773                    self.cooperative_cancellation_enabled
7774                        .then(|| "cooperative_cancellation".to_string()),
7775                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7776                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7777                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7778                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7779                ]
7780                .into_iter()
7781                .flatten()
7782                .chain(self.resource_capabilities.iter().cloned())
7783                .collect(),
7784                Value::Object(command_contracts),
7785                Some(
7786                    self.workflows
7787                        .iter()
7788                        .filter_map(|(workflow_type, workflow)| {
7789                            workflow
7790                                .definition_fingerprint
7791                                .as_ref()
7792                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7793                        })
7794                        .collect(),
7795                ),
7796            )
7797            .await?;
7798        if self.cooperative_cancellation_enabled && response.registered {
7799            self.cooperative_registration_confirmed
7800                .store(true, Ordering::SeqCst);
7801        }
7802        if self.client.local_activities_enabled && response.registered {
7803            self.local_registration_confirmed
7804                .store(true, Ordering::SeqCst);
7805        }
7806        if self.client.worker_sessions_enabled && response.registered {
7807            self.session_registration_confirmed
7808                .store(true, Ordering::SeqCst);
7809        }
7810        if self.client.sticky_cache.is_some() && response.registered {
7811            self.sticky_registration_confirmed
7812                .store(true, Ordering::SeqCst);
7813        }
7814        self.query_authority_confirmed.store(
7815            response.registered
7816                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
7817                && response
7818                    .server_capabilities
7819                    .as_ref()
7820                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
7821            Ordering::SeqCst,
7822        );
7823        Ok(response)
7824    }
7825
7826    /// Run until shutdown or a terminal worker error occurs.
7827    ///
7828    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7829    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7830    /// authentication, protocol, and other non-retryable failures are returned.
7831    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7832    /// poll and heartbeat outages beyond the ordinary retry budget.
7833    pub async fn run(&self) -> Result<()> {
7834        self.run_until(std::future::pending::<()>()).await
7835    }
7836
7837    /// Run until `shutdown` resolves or a terminal worker error occurs.
7838    ///
7839    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7840    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7841    where
7842        F: Future<Output = ()>,
7843    {
7844        let _clear_cache_on_drop =
7845            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
7846        let stop = Arc::new(AtomicBool::new(false));
7847        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7848        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7849        worker.run_stop = Some(Arc::clone(&stop));
7850        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7851        tokio::pin!(run);
7852        tokio::pin!(shutdown);
7853        tokio::select! {
7854            result = &mut run => result,
7855            _ = &mut shutdown => {
7856                stop.store(true, Ordering::SeqCst);
7857                run.await
7858            }
7859        }
7860    }
7861
7862    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7863        let mut worker = self.clone();
7864        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7865            policy: self.retry_policy,
7866            stop,
7867            workflow_completion_retry_deadline: None,
7868        });
7869        worker
7870    }
7871
7872    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7873        let registration = self.register().await?;
7874        if !registration.registered {
7875            return Err(Error::WorkerLoop(format!(
7876                "worker registration for {:?} was not accepted",
7877                self.worker_id
7878            )));
7879        }
7880        let registered_worker_id = registration.worker_id.clone();
7881        let primary = self.run_registered_until(stop, registration).await;
7882        let primary = match (primary, self.close_worker_sessions().await) {
7883            (Ok(()), result) => result,
7884            (Err(error), Ok(())) => Err(error),
7885            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7886                primary: Box::new(primary),
7887                deregistration: Box::new(close),
7888            }),
7889        };
7890        self.session_registration_confirmed
7891            .store(false, Ordering::SeqCst);
7892        self.cooperative_registration_confirmed
7893            .store(false, Ordering::SeqCst);
7894        self.local_registration_confirmed
7895            .store(false, Ordering::SeqCst);
7896        let deregistration = self
7897            .client
7898            .deregister_worker_registration(&registered_worker_id)
7899            .await;
7900        self.sticky_registration_confirmed
7901            .store(false, Ordering::SeqCst);
7902        self.client.clear_sticky_cache()?;
7903
7904        match (primary, deregistration) {
7905            (Ok(()), Ok(_)) => Ok(()),
7906            (Ok(()), Err(deregistration)) => Err(deregistration),
7907            (Err(primary), Ok(_)) => Err(primary),
7908            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7909                primary: Box::new(primary),
7910                deregistration: Box::new(deregistration),
7911            }),
7912        }
7913    }
7914
7915    async fn run_registered_until(
7916        &self,
7917        stop: Arc<AtomicBool>,
7918        registration: RegisterWorkerResponse,
7919    ) -> Result<()> {
7920        if self.require_query_task_authority
7921            && !self.query_authority_confirmed.load(Ordering::SeqCst)
7922        {
7923            return Err(Error::WorkerLoop(
7924                "registration did not confirm query_task_authority".into(),
7925            ));
7926        }
7927        let heartbeat_interval = Duration::from_secs(
7928            registration
7929                .heartbeat_interval_seconds
7930                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7931        );
7932        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7933        // from the completion of the preceding attempt, including its bounded
7934        // retries. A fixed-epoch interval can leave an already-due tick queued
7935        // while an acknowledgement is slow, producing a catch-up heartbeat as
7936        // soon as that request completes.
7937        let heartbeat = tokio::time::sleep(Duration::ZERO);
7938        tokio::pin!(heartbeat);
7939        // Poll responses may already have leased server-side work by the time
7940        // they become ready, so each poller owns its responses through
7941        // completion or failure instead of racing raw polls in this select.
7942        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7943            let worker = self.clone();
7944            let stop = Arc::clone(&stop);
7945            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7946        });
7947        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7948            let worker = self.clone();
7949            let stop = Arc::clone(&stop);
7950            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7951        });
7952        let mut query_poller = (!self.queries.is_empty()).then(|| {
7953            let worker = self.clone();
7954            let stop = Arc::clone(&stop);
7955            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7956        });
7957
7958        loop {
7959            tokio::select! {
7960                _ = wait_for_worker_stop(&stop) => {
7961                    stop.store(true, Ordering::SeqCst);
7962                    break;
7963                }
7964                _ = &mut heartbeat => {
7965                    let result = self.retry_worker_operation(|| {
7966                        self.client.heartbeat_worker_with_sessions(
7967                            &self.worker_id,
7968                            self.max_concurrent_workflow_tasks,
7969                            self.max_concurrent_activity_tasks,
7970                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7971                        )
7972                    }).await;
7973                    heartbeat
7974                        .as_mut()
7975                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7976                    match result {
7977                        Ok(Some(acknowledgement)) => {
7978                            if let Some(observer) = &self.heartbeat_observer {
7979                                observer(&WorkerHeartbeatObservation {
7980                                    worker_id: self.worker_id.clone(),
7981                                    task_queue: self.task_queue.clone(),
7982                                    acknowledged_at_unix_millis: SystemTime::now()
7983                                        .duration_since(UNIX_EPOCH)
7984                                        .unwrap_or_default()
7985                                        .as_millis()
7986                                        .min(u64::MAX as u128)
7987                                        as u64,
7988                                    acknowledgement,
7989                                });
7990                            }
7991                        }
7992                        Ok(None) => break,
7993                        Err(error) => {
7994                            stop.store(true, Ordering::SeqCst);
7995                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7996                            return Err(error);
7997                        }
7998                    }
7999                }
8000                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
8001                    workflow_poller = None;
8002                    let stopped_by_server = stop.load(Ordering::SeqCst);
8003                    stop.store(true, Ordering::SeqCst);
8004                    let poller_result = optional_poller_result("workflow", result);
8005                    let join_result =
8006                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8007                    poller_result?;
8008                    join_result?;
8009                    if stopped_by_server {
8010                        return Ok(());
8011                    }
8012                    return Err(Error::WorkerLoop(
8013                        "workflow poller stopped unexpectedly".to_string(),
8014                    ));
8015                }
8016                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
8017                    activity_poller = None;
8018                    let stopped_by_server = stop.load(Ordering::SeqCst);
8019                    stop.store(true, Ordering::SeqCst);
8020                    let poller_result = optional_poller_result("activity", result);
8021                    let join_result =
8022                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8023                    poller_result?;
8024                    join_result?;
8025                    if stopped_by_server {
8026                        return Ok(());
8027                    }
8028                    return Err(Error::WorkerLoop(
8029                        "activity poller stopped unexpectedly".to_string(),
8030                    ));
8031                }
8032                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
8033                    query_poller = None;
8034                    let stopped_by_server = stop.load(Ordering::SeqCst);
8035                    stop.store(true, Ordering::SeqCst);
8036                    let poller_result = optional_poller_result("query", result);
8037                    let join_result =
8038                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8039                    poller_result?;
8040                    join_result?;
8041                    if stopped_by_server {
8042                        return Ok(());
8043                    }
8044                    return Err(Error::WorkerLoop(
8045                        "query poller stopped unexpectedly".to_string(),
8046                    ));
8047                }
8048            }
8049        }
8050
8051        join_pollers(
8052            workflow_poller.take(),
8053            activity_poller.take(),
8054            query_poller.take(),
8055        )
8056        .await
8057    }
8058
8059    /// Poll and settle at most one task from each enabled task family.
8060    ///
8061    /// A workflow may reach its server-enforced run deadline while this worker
8062    /// holds a task. When the completion endpoint authoritatively rejects that
8063    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8064    /// terminal `run_status=failed`, the workflow tick is considered settled:
8065    /// the late command was not recorded and cannot replace the terminal run.
8066    /// Every other completion rejection remains an error. This worker-level
8067    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8068    /// only bounds how long a client waits for a result.
8069    ///
8070    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8071    /// the original [`Error::Http`] status and response body.
8072    pub async fn run_once(&self) -> Result<usize> {
8073        self.validate_registration()?;
8074        if self.client.worker_sessions_enabled {
8075            self.require_session_registration()?;
8076        }
8077        if self.cooperative_cancellation_enabled
8078            && !self
8079                .cooperative_registration_confirmed
8080                .load(Ordering::SeqCst)
8081        {
8082            return Err(Error::CooperativeCancellationUnavailable(
8083                "register this cooperative worker before polling tasks".into(),
8084            ));
8085        }
8086        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8087        let mut handled = 0;
8088        match worker.poll_workflow_once().await? {
8089            ManagedPollOutcome::Handled => handled += 1,
8090            ManagedPollOutcome::Stop => return Ok(handled),
8091            ManagedPollOutcome::Idle => {}
8092        }
8093        match worker.poll_activity_once().await? {
8094            ManagedPollOutcome::Handled => handled += 1,
8095            ManagedPollOutcome::Stop => return Ok(handled),
8096            ManagedPollOutcome::Idle => {}
8097        }
8098        if !self.queries.is_empty() {
8099            match worker.poll_query_once().await? {
8100                ManagedPollOutcome::Handled => handled += 1,
8101                ManagedPollOutcome::Stop => return Ok(handled),
8102                ManagedPollOutcome::Idle => {}
8103            }
8104        }
8105        Ok(handled)
8106    }
8107
8108    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
8109        if self.client.sticky_cache.is_some()
8110            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8111        {
8112            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8113        }
8114        if self.client.local_activities_enabled
8115            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8116        {
8117            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8118        }
8119        if self.cooperative_cancellation_enabled {
8120            return self.poll_cooperative_workflow_once().await;
8121        }
8122        let poll_request_id = unique_request_id("rust-workflow-poll");
8123        let response = self
8124            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8125            .await;
8126        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8127            return Ok(ManagedPollOutcome::Idle);
8128        };
8129        if response.outcome().should_stop() {
8130            return Ok(ManagedPollOutcome::Stop);
8131        }
8132        let memo_updates_supported =
8133            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8134        let Some(task) = response.task else {
8135            return Ok(ManagedPollOutcome::Idle);
8136        };
8137
8138        let task_id = task.task_id.clone();
8139        let attempt = task.workflow_task_attempt;
8140        let run_id = task.run_id.clone();
8141        let lease_owner = task
8142            .lease_owner
8143            .clone()
8144            .unwrap_or_else(|| self.worker_id.clone());
8145
8146        let decision = match self.execute_workflow_with_local_activities(task).await {
8147            Ok(Some(decision)) => Ok(decision),
8148            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8149            Err(error) => Err(error),
8150        };
8151        self.settle_workflow_task_decision(
8152            &task_id,
8153            &lease_owner,
8154            attempt,
8155            run_id.as_deref(),
8156            decision,
8157            memo_updates_supported,
8158            snapshot,
8159        )
8160        .await
8161    }
8162
8163    #[allow(clippy::too_many_arguments)]
8164    async fn settle_workflow_task_decision(
8165        &self,
8166        task_id: &str,
8167        lease_owner: &str,
8168        attempt: u64,
8169        run_id: Option<&str>,
8170        decision: Result<WorkflowTaskDecision>,
8171        memo_updates_supported: bool,
8172        snapshot: Option<sticky_worker::StickySnapshot>,
8173    ) -> Result<ManagedPollOutcome> {
8174        match decision {
8175            Ok(decision)
8176                if decision.cancellation_delivery.is_some()
8177                    || decision.cancellation_scope_delivery.is_some()
8178                    || decision.cancellation_scope_opening.is_some() =>
8179            {
8180                return Err(Error::CooperativeCancellationUnavailable(
8181                    "worker cancellation delivery has not been negotiated".into(),
8182                ));
8183            }
8184            Ok(decision)
8185                if commands_use_workflow_memo_updates(&decision.commands)
8186                    && !memo_updates_supported =>
8187            {
8188                self.client
8189                    .fail_workflow_task(
8190                        task_id,
8191                        lease_owner,
8192                        attempt,
8193                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8194                    )
8195                    .await?;
8196            }
8197            Ok(decision) if decision.commands.is_empty() => {
8198                // A replay can consume a recorded pending durable command
8199                // without producing a new command. The standalone protocol
8200                // acknowledges that state through the typed waiting outcome;
8201                // an empty completion is rejected by servers that require at
8202                // least one executable command.
8203                self.client
8204                    .fail_workflow_task_with_type(
8205                        task_id,
8206                        lease_owner,
8207                        attempt,
8208                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8209                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8210                    )
8211                    .await?;
8212            }
8213            Ok(decision) => {
8214                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8215                let completion = self
8216                    .client
8217                    .complete_workflow_task_with_message_streams(
8218                        task_id,
8219                        lease_owner,
8220                        attempt,
8221                        decision.commands,
8222                        decision.message_stream_cursors,
8223                        decision.message_stream_waits,
8224                        sticky_claim,
8225                    )
8226                    .await;
8227                if let Err(error) = completion {
8228                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8229                    if !workflow_task_completion_is_terminal_timeout(
8230                        &error, task_id, attempt, run_id,
8231                    ) {
8232                        return Err(error);
8233                    }
8234                }
8235            }
8236            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8237            Err(error) => {
8238                self.discard_sticky_snapshot(snapshot.as_ref())?;
8239                self.client
8240                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8241                    .await?;
8242            }
8243        }
8244
8245        Ok(ManagedPollOutcome::Handled)
8246    }
8247
8248    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8249        while !stop.load(Ordering::SeqCst) {
8250            match self.poll_workflow_once().await {
8251                Ok(ManagedPollOutcome::Stop) => {
8252                    stop.store(true, Ordering::SeqCst);
8253                    break;
8254                }
8255                Err(error) => {
8256                    stop.store(true, Ordering::SeqCst);
8257                    return Err(error);
8258                }
8259                _ => {}
8260            }
8261        }
8262
8263        Ok(())
8264    }
8265
8266    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
8267        if self.client.worker_sessions_enabled {
8268            self.require_session_registration()?;
8269        }
8270        if self.cooperative_cancellation_enabled {
8271            return self.poll_cooperative_activity_once().await;
8272        }
8273        let poll_request_id = unique_request_id("rust-activity-poll");
8274        let response = self
8275            .retry_worker_operation(|| {
8276                self.client.poll_activity_task_response_with_request_id(
8277                    &self.worker_id,
8278                    &self.task_queue,
8279                    self.poll_timeout,
8280                    &poll_request_id,
8281                    0,
8282                )
8283            })
8284            .await;
8285        let response = match response {
8286            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8287            response => response,
8288        };
8289        let Some(response) = self.settle_worker_poll_response(response).await? else {
8290            return Ok(ManagedPollOutcome::Idle);
8291        };
8292        if response.outcome().should_stop() {
8293            return Ok(ManagedPollOutcome::Stop);
8294        }
8295        let Some(task) = response.task else {
8296            return Ok(ManagedPollOutcome::Idle);
8297        };
8298
8299        let session = self.track_session_task(task.worker_session.as_ref())?;
8300        let hydration_claim = task.hydration_claim;
8301        let task = task.task;
8302
8303        let task_id = task.task_id.clone();
8304        let attempt_id = task
8305            .activity_attempt_id
8306            .clone()
8307            .or(task.attempt_id.clone())
8308            .unwrap_or_default();
8309        let lease_owner = task
8310            .lease_owner
8311            .clone()
8312            .unwrap_or_else(|| self.worker_id.clone());
8313        let codec = task.payload_codec.clone();
8314        let result = self
8315            .execute_session_activity_task(task, session, hydration_claim.as_ref())
8316            .await;
8317        match result {
8318            Err(Error::ActivityExecutionAbandoned(_)) => {}
8319            Err(error) if activity_hydration::stopped(&error) => {}
8320            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8321            Ok(value) => {
8322                let completion = self
8323                    .client
8324                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
8325                    .await;
8326                if let Err(error) = completion {
8327                    if !activity_task_rejection_is_final(&error) {
8328                        return Err(error);
8329                    }
8330                }
8331            }
8332            Err(error) => {
8333                let failure = self
8334                    .client
8335                    .fail_activity_task(
8336                        &task_id,
8337                        &attempt_id,
8338                        &lease_owner,
8339                        error.to_string(),
8340                        false,
8341                    )
8342                    .await;
8343                if let Err(error) = failure {
8344                    if !activity_task_rejection_is_final(&error) {
8345                        return Err(error);
8346                    }
8347                }
8348            }
8349        }
8350
8351        Ok(ManagedPollOutcome::Handled)
8352    }
8353
8354    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8355        // Each lane retains its leased response through callback settlement.
8356        // A bounded independent activity must not occupy the cleanup lane too.
8357        // Preserve the existing serial loop unless cooperation is enabled.
8358        let lane_count = if self.cooperative_cancellation_enabled {
8359            self.max_concurrent_activity_tasks
8360        } else {
8361            1
8362        };
8363        let mut lanes = FuturesUnordered::new();
8364        for _ in 0..lane_count {
8365            let worker = self.clone();
8366            let stop = Arc::clone(&stop);
8367            lanes.push(async move {
8368                while !stop.load(Ordering::SeqCst) {
8369                    match worker.poll_activity_once().await {
8370                        Ok(ManagedPollOutcome::Stop) => {
8371                            stop.store(true, Ordering::SeqCst);
8372                            break;
8373                        }
8374                        Err(error) => {
8375                            stop.store(true, Ordering::SeqCst);
8376                            return Err(error);
8377                        }
8378                        _ => {}
8379                    }
8380                }
8381                Ok(())
8382            });
8383        }
8384        // Join every lane before deregistration, including after one fails.
8385        let mut first_error = None;
8386        while let Some(result) = lanes.next().await {
8387            if let Err(error) = result {
8388                first_error.get_or_insert(error);
8389            }
8390        }
8391        first_error.map_or(Ok(()), Err)
8392    }
8393
8394    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
8395        let poll_request_id = unique_request_id("rust-query-poll");
8396        let response = self
8397            .retry_worker_operation(|| {
8398                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
8399                    "poll_request_id":poll_request_id,
8400                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
8401                async move {
8402                    self.client
8403                        .poll_request_json_unresolved::<Value, Value>(
8404                            "/worker/query-tasks/poll",
8405                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
8406                            &body,
8407                            self.poll_timeout + Duration::from_secs(5),
8408                            0,
8409                        )
8410                        .await
8411                }
8412            })
8413            .await;
8414        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
8415            return Ok(ManagedPollOutcome::Idle);
8416        };
8417        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
8418            match query_authority::Authority::capture(&wire["task"], self) {
8419                Ok(authority) => authority,
8420                Err(_) => return Ok(ManagedPollOutcome::Handled),
8421            }
8422        } else {
8423            None
8424        };
8425        let loading = self.client.resolve_runtime_payloads(
8426            &mut wire,
8427            "/worker/query-tasks/poll",
8428            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
8429        );
8430        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
8431            Err(_) => return Ok(ManagedPollOutcome::Handled),
8432            Ok(result) => result?,
8433        }
8434        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
8435        if response.outcome().should_stop() {
8436            return Ok(ManagedPollOutcome::Stop);
8437        }
8438        let Some(task) = response.task else {
8439            return Ok(ManagedPollOutcome::Idle);
8440        };
8441
8442        let query_task_id = task.query_task_id.clone();
8443        let attempt = task.query_task_attempt;
8444        let lease_owner = task
8445            .lease_owner
8446            .clone()
8447            .unwrap_or_else(|| self.worker_id.clone());
8448        let codec = task.payload_codec.clone();
8449
8450        let execution = query_authority::Authority::protect(
8451            authority.as_ref(),
8452            self,
8453            self.execute_query_task_with_authority(task, authority.as_ref()),
8454        )
8455        .await;
8456        let execution = match execution {
8457            Err(_) => return Ok(ManagedPollOutcome::Handled),
8458            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
8459                return Ok(ManagedPollOutcome::Handled)
8460            }
8461            Ok(result) => result,
8462        };
8463        match execution {
8464            Ok(value) => {
8465                let result_envelope = match encode_typed_envelope(&value, &codec) {
8466                    Ok(result_envelope) => result_envelope,
8467                    Err(error) => {
8468                        let failure = query_authority::Authority::protect(
8469                            authority.as_ref(),
8470                            self,
8471                            self.client.fail_query_task(
8472                                &query_task_id,
8473                                &lease_owner,
8474                                attempt,
8475                                error.to_string(),
8476                                "query_result_encode_failed",
8477                                "QueryResultEncodeFailed",
8478                            ),
8479                        )
8480                        .await;
8481                        let Ok(failure) = failure else {
8482                            return Ok(ManagedPollOutcome::Handled);
8483                        };
8484                        if let Err(error) = failure {
8485                            if !query_task_rejection_is_final(&error) {
8486                                return Err(error);
8487                            }
8488                        }
8489                        return Ok(ManagedPollOutcome::Handled);
8490                    }
8491                };
8492
8493                let completion = query_authority::Authority::protect(
8494                    authority.as_ref(),
8495                    self,
8496                    self.client.complete_query_task_with_envelope(
8497                        &query_task_id,
8498                        &lease_owner,
8499                        attempt,
8500                        value.clone().into_json()?,
8501                        result_envelope,
8502                    ),
8503                )
8504                .await;
8505                let Ok(completion) = completion else {
8506                    return Ok(ManagedPollOutcome::Handled);
8507                };
8508                if let Err(error) = completion {
8509                    if !query_task_rejection_is_final(&error) {
8510                        return Err(error);
8511                    }
8512                }
8513            }
8514            Err(failure) => {
8515                let result = query_authority::Authority::protect(
8516                    authority.as_ref(),
8517                    self,
8518                    self.client.fail_query_task(
8519                        &query_task_id,
8520                        &lease_owner,
8521                        attempt,
8522                        failure.message,
8523                        failure.reason,
8524                        failure.failure_type,
8525                    ),
8526                )
8527                .await;
8528                let Ok(result) = result else {
8529                    return Ok(ManagedPollOutcome::Handled);
8530                };
8531                if let Err(error) = result {
8532                    if !query_task_rejection_is_final(&error) {
8533                        return Err(error);
8534                    }
8535                }
8536            }
8537        }
8538
8539        Ok(ManagedPollOutcome::Handled)
8540    }
8541
8542    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8543        while !stop.load(Ordering::SeqCst) {
8544            match self.poll_query_once().await {
8545                Ok(ManagedPollOutcome::Stop) => {
8546                    stop.store(true, Ordering::SeqCst);
8547                    break;
8548                }
8549                Err(error) => {
8550                    stop.store(true, Ordering::SeqCst);
8551                    return Err(error);
8552                }
8553                _ => {}
8554            }
8555        }
8556
8557        Ok(())
8558    }
8559
8560    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
8561    where
8562        F: FnMut() -> Fut,
8563        Fut: Future<Output = Result<T>>,
8564    {
8565        let mut retries = 0;
8566
8567        loop {
8568            if self
8569                .run_stop
8570                .as_ref()
8571                .is_some_and(|stop| stop.load(Ordering::SeqCst))
8572            {
8573                return Ok(None);
8574            }
8575            match operation().await {
8576                Err(error)
8577                    if (workflow_hydration::stopped(&error)
8578                        || activity_hydration::stopped(&error))
8579                        && self
8580                            .run_stop
8581                            .as_ref()
8582                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
8583                {
8584                    return Ok(None);
8585                }
8586                Err(error)
8587                    if worker_operation_is_retryable(&error)
8588                        && (retries < self.retry_policy.max_retries
8589                            || (self.recover_transient_outages
8590                                && self.run_stop.is_some()
8591                                && self.retry_policy.max_retries > 0)) =>
8592                {
8593                    retries = retries.saturating_add(1);
8594                    let delay = worker_retry_delay(self.retry_policy, retries)
8595                        .max(Duration::from_millis(1));
8596                    if let Some(stop) = &self.run_stop {
8597                        tokio::select! {
8598                            _ = tokio::time::sleep(delay) => {}
8599                            _ = wait_for_worker_stop(stop) => return Ok(None),
8600                        }
8601                    } else {
8602                        tokio::time::sleep(delay).await;
8603                    }
8604                }
8605                result => return result.map(Some),
8606            }
8607        }
8608    }
8609
8610    async fn settle_worker_poll_response<T>(
8611        &self,
8612        response: Result<Option<T>>,
8613    ) -> Result<Option<T>> {
8614        match response {
8615            Ok(response) => Ok(response),
8616            Err(error) => {
8617                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
8618                    return Err(error);
8619                };
8620                let minimum_delay = self
8621                    .retry_policy
8622                    .initial_backoff
8623                    .max(Duration::from_millis(1));
8624                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
8625                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
8626                Ok(None)
8627            }
8628        }
8629    }
8630
8631    #[cfg(test)]
8632    async fn execute_query_task(
8633        &self,
8634        task: QueryTask,
8635    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8636        self.execute_query_task_with_authority(task, None).await
8637    }
8638
8639    async fn execute_query_task_with_authority(
8640        &self,
8641        mut task: QueryTask,
8642        authority: Option<&query_authority::Authority>,
8643    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8644        validate_query_task_payloads(&task).map_err(|error| {
8645            QueryTaskExecutionFailure::new(
8646                "query_payload_decode_failed",
8647                error.to_string(),
8648                "QueryPayloadDecodeFailed",
8649            )
8650        })?;
8651
8652        if !self.workflows.contains_key(&task.workflow_type) {
8653            return Err(QueryTaskExecutionFailure::new(
8654                "query_workflow_type_not_registered",
8655                format!("no workflow registered for type {:?}", task.workflow_type),
8656                "WorkflowTypeNotRegistered",
8657            ));
8658        }
8659
8660        let Some(handlers) = self.queries.get(&task.workflow_type) else {
8661            return Err(QueryTaskExecutionFailure::new(
8662                "query_handler_unavailable",
8663                format!(
8664                    "query handlers are unavailable for workflow type {:?}",
8665                    task.workflow_type
8666                ),
8667                "QueryHandlerUnavailable",
8668            ));
8669        };
8670        let Some(query) = handlers.get(&task.query_name) else {
8671            return Err(QueryTaskExecutionFailure::new(
8672                "rejected_unknown_query",
8673                format!("unknown query {:?}", task.query_name),
8674                "QueryFailed",
8675            ));
8676        };
8677
8678        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
8679            .map_err(|error| {
8680            QueryTaskExecutionFailure::new(
8681                "query_payload_decode_failed",
8682                format!("cannot decode query arguments: {error}"),
8683                "QueryPayloadDecodeFailed",
8684            )
8685        })?;
8686        let workflow_input_typed =
8687            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8688                .map_err(|error| {
8689                    QueryTaskExecutionFailure::new(
8690                        "query_workflow_state_unavailable",
8691                        format!("cannot decode workflow start input: {error}"),
8692                        "QueryWorkflowStateUnavailable",
8693                    )
8694                })?;
8695        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8696            QueryTaskExecutionFailure::new(
8697                "query_workflow_state_unavailable",
8698                format!("cannot project workflow start input: {error}"),
8699                "QueryWorkflowStateUnavailable",
8700            )
8701        })?;
8702        hydrate_query_history_from_export(&mut task).map_err(|error| {
8703            QueryTaskExecutionFailure::new(
8704                "query_workflow_state_unavailable",
8705                format!("cannot restore query history snapshot: {error}"),
8706                "QueryWorkflowStateUnavailable",
8707            )
8708        })?;
8709        enrich_query_history_from_export(&mut task).map_err(|error| {
8710            QueryTaskExecutionFailure::new(
8711                "query_workflow_state_unavailable",
8712                format!("cannot restore compact query history payloads: {error}"),
8713                "QueryWorkflowStateUnavailable",
8714            )
8715        })?;
8716        let signal_events = query_signal_events(&task).map_err(|error| {
8717            QueryTaskExecutionFailure::new(
8718                "query_workflow_state_unavailable",
8719                format!("cannot decode committed workflow signals: {error}"),
8720                "QueryWorkflowStateUnavailable",
8721            )
8722        })?;
8723        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8724        let context = QueryContext {
8725            workflow_id: task.workflow_id,
8726            run_id: task.run_id,
8727            workflow_type: task.workflow_type.clone(),
8728            run_status: task.run_status,
8729            workflow_input,
8730            workflow_input_avro_value: workflow_input_typed.clone(),
8731            history_events: Arc::clone(&history_events),
8732            signal_events: Arc::new(signal_events),
8733        };
8734
8735        let future = match query {
8736            RegisteredQuery::Snapshot(handler) => {
8737                query_authority::before_handler(authority, &self.client).await?;
8738                handler(context, args)
8739            }
8740            RegisteredQuery::Replayed {
8741                state_type,
8742                handler,
8743            } => {
8744                let workflow = self
8745                    .workflows
8746                    .get(&task.workflow_type)
8747                    .expect("workflow registration was checked above");
8748                if workflow.state_type != Some(*state_type) {
8749                    return Err(QueryTaskExecutionFailure::new(
8750                        "query_workflow_state_unavailable",
8751                        "replayed query state type does not match its workflow registration",
8752                        "QueryWorkflowStateUnavailable",
8753                    ));
8754                }
8755                let replay = workflow.replay.as_ref().ok_or_else(|| {
8756                    QueryTaskExecutionFailure::new(
8757                        "query_workflow_state_unavailable",
8758                        format!(
8759                            "workflow type {:?} is not registered for instance-state replay",
8760                            task.workflow_type
8761                        ),
8762                        "QueryWorkflowStateUnavailable",
8763                    )
8764                })?;
8765                let workflow_state = Arc::new(Mutex::new(
8766                    WorkflowState::new_with_identity(
8767                        history_events.as_ref().clone(),
8768                        context.workflow_id.clone(),
8769                        context.run_id.clone(),
8770                        self.task_queue.clone(),
8771                        task.payload_codec,
8772                        None,
8773                    )
8774                    .map_err(|error| {
8775                        QueryTaskExecutionFailure::new(
8776                            "query_workflow_state_unavailable",
8777                            format!("workflow replay failed before query: {error}"),
8778                            "QueryWorkflowStateUnavailable",
8779                        )
8780                    })?,
8781                ));
8782                let workflow_context = WorkflowContext {
8783                    state: workflow_state,
8784                    cancellation_scope_id: "root".into(),
8785                };
8786                query_authority::before_handler(authority, &self.client).await?;
8787                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8788                let outcome = {
8789                    let mut cx = TaskContext::from_waker(noop_waker_ref());
8790                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8791                        .map_err(|error| {
8792                            QueryTaskExecutionFailure::new(
8793                                "query_workflow_state_unavailable",
8794                                error.to_string(),
8795                                "QueryWorkflowStateUnavailable",
8796                            )
8797                        })?;
8798                    invocation.future.as_mut().poll(&mut cx)
8799                };
8800                match outcome {
8801                    Poll::Ready(Ok(_)) => {
8802                        workflow_context
8803                            .ensure_history_consumed()
8804                            .map_err(|error| {
8805                                QueryTaskExecutionFailure::new(
8806                                    "query_workflow_state_unavailable",
8807                                    format!("workflow replay failed before query: {error}"),
8808                                    "QueryWorkflowStateUnavailable",
8809                                )
8810                            })?;
8811                    }
8812                    Poll::Ready(Err(error)) => {
8813                        return Err(QueryTaskExecutionFailure::new(
8814                            "query_workflow_state_unavailable",
8815                            format!("workflow replay failed before query: {error}"),
8816                            "QueryWorkflowStateUnavailable",
8817                        ));
8818                    }
8819                    Poll::Pending => {
8820                        let commands = workflow_context.take_commands().map_err(|error| {
8821                            QueryTaskExecutionFailure::new(
8822                                "query_workflow_state_unavailable",
8823                                format!("workflow replay failed before query: {error}"),
8824                                "QueryWorkflowStateUnavailable",
8825                            )
8826                        })?;
8827                        if commands.is_empty()
8828                            && !workflow_context
8829                                .matched_recorded_pending()
8830                                .map_err(|error| {
8831                                    QueryTaskExecutionFailure::new(
8832                                        "query_workflow_state_unavailable",
8833                                        format!("workflow replay failed before query: {error}"),
8834                                        "QueryWorkflowStateUnavailable",
8835                                    )
8836                                })?
8837                        {
8838                            return Err(QueryTaskExecutionFailure::new(
8839                                "query_workflow_state_unavailable",
8840                                "workflow replay yielded without a durable command",
8841                                "QueryWorkflowStateUnavailable",
8842                            ));
8843                        }
8844                    }
8845                }
8846                let state = (invocation.snapshot)().map_err(|error| {
8847                    QueryTaskExecutionFailure::new(
8848                        "query_workflow_state_unavailable",
8849                        format!("cannot snapshot replayed workflow state: {error}"),
8850                        "QueryWorkflowStateUnavailable",
8851                    )
8852                })?;
8853                query_authority::before_handler(authority, &self.client).await?;
8854                handler(context, state, args).map_err(|message| {
8855                    QueryTaskExecutionFailure::new(
8856                        "query_workflow_state_unavailable",
8857                        message,
8858                        "QueryWorkflowStateUnavailable",
8859                    )
8860                })?
8861            }
8862        };
8863
8864        future.await.map_err(|error| {
8865            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8866        })
8867    }
8868
8869    #[cfg(test)]
8870    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8871        Ok(self.execute_workflow_task_decision(task)?.commands)
8872    }
8873
8874    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8875        self.execute_workflow_task_decision_with_cancellation(task, None)
8876    }
8877
8878    fn execute_workflow_task_decision_with_cancellation(
8879        &self,
8880        task: WorkflowTask,
8881        observation: Option<&CancellationRequest>,
8882    ) -> Result<WorkflowTaskDecision> {
8883        match self.prepare_workflow_task_execution(task, observation)? {
8884            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8885            PreparedWorkflowTask::Execution {
8886                task,
8887                context,
8888                mut future,
8889            } => {
8890                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8891                self.finish_workflow_task_execution(&task, &context, outcome)
8892            }
8893        }
8894    }
8895
8896    fn prepare_workflow_task_execution(
8897        &self,
8898        task: WorkflowTask,
8899        observation: Option<&CancellationRequest>,
8900    ) -> Result<PreparedWorkflowTask> {
8901        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8902            && !self.cooperative_cancellation_enabled
8903        {
8904            return Err(Error::CancellationScopeExecutionUnavailable);
8905        }
8906        validate_workflow_task_payloads(&task)?;
8907        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8908            &task.history_events,
8909            self.allow_cancellation_scope_authoring,
8910            self.allow_cancellation_scope_delivery,
8911        )?;
8912        let cancellation_history = if let Some(observation) = observation {
8913            observation.validate_observation()?;
8914            cooperative_cancellation::cancellation_claim(&task)?;
8915            let canonical = CancellationHistory::from_events(
8916                &task.history_events,
8917                task.run_id.as_deref().unwrap_or_default(),
8918                Some(observation),
8919            )?;
8920            if canonical.request_index >= task.history_events.len() {
8921                return Err(Error::InvalidCooperativeCancellation(
8922                    "workflow replay requires the observed canonical request".into(),
8923                ));
8924            }
8925            Some(canonical)
8926        } else {
8927            None
8928        };
8929        if let Some(update_id) = task
8930            .workflow_update_id
8931            .as_deref()
8932            .filter(|update_id| !update_id.is_empty())
8933        {
8934            if self.allow_cancellation_scope_delivery {
8935                return Err(Error::CancellationScopeExecutionUnavailable);
8936            }
8937            CancellationHistory::from_events(
8938                &task.history_events,
8939                task.run_id.as_deref().unwrap_or_default(),
8940                None,
8941            )?;
8942            return self
8943                .execute_update_task(&task, update_id)
8944                .map(WorkflowTaskDecision::without_message_streams)
8945                .map(PreparedWorkflowTask::Decision);
8946        }
8947
8948        let workflow = self
8949            .workflows
8950            .get(&task.workflow_type)
8951            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8952        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8953        let resume_signal = decode_resume_signal(&task)?;
8954        let history_budget = WorkflowHistoryBudget {
8955            event_count: task
8956                .total_history_events
8957                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8958            size_bytes: task.history_size_bytes,
8959            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8960            pressure: task.history_budget_pressure.clone(),
8961        };
8962        let workflow_command_identity = task
8963            .workflow_command_id
8964            .clone()
8965            .filter(|identity| !identity.is_empty())
8966            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8967            .unwrap_or_default();
8968        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8969            task.history_events.clone(),
8970            task.workflow_id.clone(),
8971            task.run_id.clone(),
8972            self.task_queue.clone(),
8973            task.payload_codec.clone(),
8974            resume_signal,
8975            self.allow_cancellation_scope_authoring,
8976            self.allow_cancellation_scope_delivery,
8977        )?;
8978        workflow_state.history_budget = history_budget;
8979        workflow_state.workflow_command_identity = workflow_command_identity;
8980        if let Some(canonical) = cancellation_history {
8981            workflow_state.cancellation_history = canonical;
8982            workflow_state.cancellation_delivery_enabled = true;
8983        }
8984        if workflow_state.cancellation_history.request.is_none() {
8985            workflow_state.cancel_requested = task.cancel_requested;
8986        }
8987        let state = Arc::new(Mutex::new(workflow_state));
8988        let ctx = WorkflowContext {
8989            state,
8990            cancellation_scope_id: "root".into(),
8991        };
8992        let future = (workflow.execute)(ctx.clone(), input);
8993        Ok(PreparedWorkflowTask::Execution {
8994            task,
8995            context: ctx,
8996            future,
8997        })
8998    }
8999
9000    fn poll_workflow_future(
9001        ctx: &WorkflowContext,
9002        future: &mut WorkflowFuture,
9003    ) -> Result<Poll<Result<AvroValue>>> {
9004        let mut cx = TaskContext::from_waker(noop_waker_ref());
9005        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
9006        Ok(future.as_mut().poll(&mut cx))
9007    }
9008
9009    fn finish_workflow_task_execution(
9010        &self,
9011        task: &WorkflowTask,
9012        ctx: &WorkflowContext,
9013        outcome: Poll<Result<AvroValue>>,
9014    ) -> Result<WorkflowTaskDecision> {
9015        if !ctx
9016            .state
9017            .lock()
9018            .map_err(|_| Error::WorkflowStatePoisoned)?
9019            .local_activity_requests
9020            .is_empty()
9021        {
9022            return Err(Error::CooperativeCancellationUnavailable(
9023                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
9024            ));
9025        }
9026        let awaiting_canonical_boundary = {
9027            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9028            state.cancellation_delivery_intent.is_some()
9029                || state.cancellation_scope_opening.is_some()
9030                || state
9031                    .scope_delivery
9032                    .as_ref()
9033                    .is_some_and(|replay| replay.intent.is_some())
9034        };
9035        if awaiting_canonical_boundary {
9036            // A private delivery intent never becomes an application error.
9037            // Even a custom future which ignores a pending durable call cannot
9038            // publish terminal commands before canonical delivery and replay.
9039            if let Poll::Ready(Err(error)) = outcome {
9040                if workflow_task_integrity_error(&error) {
9041                    return Err(error);
9042                }
9043            }
9044            return self.message_stream_decision(&ctx, ctx.take_commands()?);
9045        }
9046
9047        match outcome {
9048            Poll::Ready(Ok(result)) => {
9049                ctx.ensure_history_consumed()?;
9050                let result = encode_typed_envelope(&result, &task.payload_codec)?;
9051                let mut commands = ctx.take_commands()?;
9052                commands.push(json!({
9053                    "type": "complete_workflow",
9054                    "result": result
9055                }));
9056                self.message_stream_decision(&ctx, commands)
9057            }
9058            Poll::Ready(Err(error)) => {
9059                if let Error::ContinueAsNew(request) = error {
9060                    let mut commands = ctx.take_commands()?;
9061                    if let Some(command) = ctx.continue_as_new_command(request)? {
9062                        commands.push(command);
9063                    }
9064                    ctx.ensure_history_consumed()?;
9065                    return self.message_stream_decision(&ctx, commands);
9066                }
9067                if workflow_task_integrity_error(&error) {
9068                    // Replay and protocol failures describe the workflow-task
9069                    // decision itself. Preserve their specific failure reason
9070                    // instead of replacing it with the derivative fact that
9071                    // recorded commands remain unconsumed.
9072                    return Err(error);
9073                }
9074                // A handler error must not hide a committed durable command that
9075                // upgraded workflow code no longer consumes.
9076                ctx.ensure_history_consumed()?;
9077                let mut commands = ctx.take_commands()?;
9078                commands.push(workflow_failure_command(
9079                    &error,
9080                    recorded_activity_failure_boundary(&ctx, &error),
9081                ));
9082                self.message_stream_decision(&ctx, commands)
9083            }
9084            Poll::Pending => {
9085                let commands = ctx.take_commands()?;
9086                if commands.is_empty() && !ctx.matched_recorded_pending()? {
9087                    Err(Error::WorkflowYieldedWithoutCommand)
9088                } else {
9089                    self.message_stream_decision(&ctx, commands)
9090                }
9091            }
9092        }
9093    }
9094
9095    fn message_stream_decision(
9096        &self,
9097        ctx: &WorkflowContext,
9098        commands: Vec<Value>,
9099    ) -> Result<WorkflowTaskDecision> {
9100        if !self.cooperative_cancellation_enabled
9101            && commands.iter().any(|command| {
9102                command["type"] == "schedule_activity"
9103                    && command.get("cancellation_policy").is_some()
9104            })
9105        {
9106            return Err(Error::CooperativeCancellationUnavailable(format!(
9107                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9108                self.worker_id,
9109            )));
9110        }
9111        if !self.cooperative_cancellation_enabled
9112            && commands.iter().any(|command| {
9113                command["type"] == "start_child_workflow"
9114                    && (command["parent_close_policy"] == "request_cancellation"
9115                        || matches!(
9116                            command["cancellation_policy"].as_str(),
9117                            Some("try_cancel" | "wait_cancellation_completed")
9118                        ))
9119            })
9120        {
9121            return Err(Error::CooperativeCancellationUnavailable(format!(
9122                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9123                self.worker_id,
9124            )));
9125        }
9126        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
9127        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9128        let scope_delivery = state
9129            .scope_delivery
9130            .as_ref()
9131            .and_then(|replay| replay.intent.clone());
9132        if scope_delivery
9133            .as_ref()
9134            .is_some_and(|intent| commands.len() != intent.command_count)
9135        {
9136            return Err(invalid_recorded_history(
9137                "cancellation_scope_pending_call_escaped",
9138                scope_delivery.as_ref().unwrap().boundary.sequence,
9139                "commands preceding the pending scoped call",
9140                "commands after suspension",
9141                "workflow cannot publish beyond an uncommitted scope delivery",
9142            ));
9143        }
9144        if let Some(opening) = &state.cancellation_scope_opening {
9145            if commands.len() != opening.command_count {
9146                return Err(invalid_recorded_history(
9147                    "cancellation_scope_pending_call_escaped",
9148                    opening.sequence,
9149                    "commands before original scope opening",
9150                    "commands after suspended opening",
9151                    "workflow cannot publish beyond an uncommitted scope opening",
9152                ));
9153            }
9154        }
9155        if state.cancellation_delivery_intent.is_some()
9156            && commands.len() != state.cancellation_delivery_command_count
9157        {
9158            return Err(invalid_recorded_history(
9159                "cooperative_cancellation_pending_call_escaped",
9160                state
9161                    .cancellation_delivery_intent
9162                    .as_ref()
9163                    .expect("pending delivery")
9164                    .sequence,
9165                "only commands preceding the pending cancellation call",
9166                "commands authored after a suspended call",
9167                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
9168            ));
9169        }
9170        Ok(WorkflowTaskDecision {
9171            commands,
9172            message_stream_cursors,
9173            message_stream_waits,
9174            cancellation_delivery: state.cancellation_delivery_intent.clone(),
9175            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
9176            cancellation_scope_delivery: scope_delivery,
9177        })
9178    }
9179
9180    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
9181        if !self.workflows.contains_key(&task.workflow_type) {
9182            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
9183        }
9184
9185        let accepted = task.history_events.iter().rev().find_map(|event| {
9186            (event.event_type == "UpdateAccepted"
9187                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
9188            .then_some(&event.payload)
9189        });
9190        let update_name = accepted
9191            .and_then(|payload| payload.get("update_name"))
9192            .and_then(Value::as_str)
9193            .or(task.update_name.as_deref())
9194            .unwrap_or_default();
9195        let Some(handler) = self
9196            .updates
9197            .get(&task.workflow_type)
9198            .and_then(|handlers| handlers.get(update_name))
9199        else {
9200            return Ok(vec![json!({
9201                "type": "fail_update",
9202                "update_id": update_id,
9203                "message": format!(
9204                    "no update handler is registered for {}.{update_name}",
9205                    task.workflow_type
9206                ),
9207                "exception_type": "UnknownUpdate",
9208                "non_retryable": true,
9209            })]);
9210        };
9211        let arguments = accepted
9212            .and_then(|payload| payload.get("arguments"))
9213            .or(task.arguments.as_ref());
9214        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9215        let workflow_input_avro_value =
9216            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9217        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9218        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9219        let context = QueryContext {
9220            workflow_id: task.workflow_id.clone(),
9221            run_id: task.run_id.clone(),
9222            workflow_type: task.workflow_type.clone(),
9223            run_status: Some("running".to_string()),
9224            workflow_input,
9225            workflow_input_avro_value,
9226            history_events: Arc::new(task.history_events.clone()),
9227            signal_events: Arc::new(signal_events),
9228        };
9229        let mut future = handler(context, arguments);
9230        let mut cx = TaskContext::from_waker(noop_waker_ref());
9231
9232        match future.as_mut().poll(&mut cx) {
9233            Poll::Ready(Ok(result)) => Ok(vec![json!({
9234                "type": "complete_update",
9235                "update_id": update_id,
9236                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9237            })]),
9238            Poll::Ready(Err(error)) => Ok(vec![json!({
9239                "type": "fail_update",
9240                "update_id": update_id,
9241                "message": error.to_string(),
9242                "exception_type": "UpdateFailed",
9243                "non_retryable": true,
9244            })]),
9245            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9246        }
9247    }
9248
9249    #[cfg(test)]
9250    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9251        self.execute_session_activity_task(task, None, None).await
9252    }
9253
9254    async fn execute_session_activity_task(
9255        &self,
9256        task: ActivityTask,
9257        worker_session: Option<WorkerSession>,
9258        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9259    ) -> Result<AvroValue> {
9260        validate_activity_task_payloads(&task)?;
9261        if worker_session.is_some() {
9262            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9263                || task
9264                    .activity_attempt_id
9265                    .as_deref()
9266                    .or(task.attempt_id.as_deref())
9267                    .is_none_or(str::is_empty)
9268                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9269            {
9270                return Err(Error::ActivityExecutionAbandoned(
9271                    "session activity requires this worker's exact immutable claim".into(),
9272                ));
9273            }
9274        }
9275
9276        let handler = self
9277            .activities
9278            .get(&task.activity_type)
9279            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9280        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9281        let attempt_id = task
9282            .activity_attempt_id
9283            .clone()
9284            .or(task.attempt_id.clone())
9285            .unwrap_or_default();
9286        let lease_owner = task
9287            .lease_owner
9288            .clone()
9289            .unwrap_or_else(|| self.worker_id.clone());
9290        let session = worker_session.clone();
9291        let ctx = ActivityContext {
9292            client: self.client.clone(),
9293            task_id: task.task_id,
9294            activity_attempt_id: attempt_id,
9295            lease_owner,
9296            activity_type: task.activity_type,
9297            attempt_number: task.attempt_number,
9298            task_queue: self.task_queue.clone(),
9299            worker_id: self.worker_id.clone(),
9300            claim_guard: None,
9301            local_heartbeats: None,
9302            worker_session,
9303        };
9304
9305        if let Some(claim) = hydration_claim {
9306            claim.confirm(&self.client).await?;
9307        }
9308        let callback = handler(ctx, args);
9309        if let Some(session) = session {
9310            tokio::select! {
9311                biased;
9312                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
9313                result = callback => if session.active() { result } else {
9314                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
9315                },
9316            }
9317        } else {
9318            callback.await
9319        }
9320    }
9321}
9322
9323fn poller_result(
9324    kind: &str,
9325    result: std::result::Result<Result<()>, tokio::task::JoinError>,
9326) -> Result<()> {
9327    match result {
9328        Ok(result) => result,
9329        Err(error) => Err(Error::WorkerLoop(format!(
9330            "{kind} poller join error: {error}"
9331        ))),
9332    }
9333}
9334
9335fn optional_poller_result(
9336    kind: &str,
9337    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
9338) -> Result<()> {
9339    match result {
9340        Some(result) => poller_result(kind, result),
9341        None => Ok(()),
9342    }
9343}
9344
9345async fn join_pollers(
9346    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9347    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9348    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9349) -> Result<()> {
9350    let mut first_error = None;
9351
9352    if let Some(handle) = workflow_poller {
9353        if let Err(error) = poller_result("workflow", handle.await) {
9354            first_error.get_or_insert(error);
9355        }
9356    }
9357
9358    if let Some(handle) = activity_poller {
9359        if let Err(error) = poller_result("activity", handle.await) {
9360            first_error.get_or_insert(error);
9361        }
9362    }
9363
9364    if let Some(handle) = query_poller {
9365        if let Err(error) = poller_result("query", handle.await) {
9366            first_error.get_or_insert(error);
9367        }
9368    }
9369
9370    if let Some(error) = first_error {
9371        Err(error)
9372    } else {
9373        Ok(())
9374    }
9375}
9376
9377fn default_worker_id() -> String {
9378    let millis = SystemTime::now()
9379        .duration_since(UNIX_EPOCH)
9380        .unwrap_or_default()
9381        .as_millis();
9382    format!("rust-worker-{}-{millis}", std::process::id())
9383}
9384
9385fn percent_encode_path_segment(segment: &str) -> String {
9386    const HEX: &[u8; 16] = b"0123456789ABCDEF";
9387    let mut encoded = String::with_capacity(segment.len());
9388
9389    for byte in segment.bytes() {
9390        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
9391            encoded.push(char::from(byte));
9392        } else {
9393            encoded.push('%');
9394            encoded.push(char::from(HEX[(byte >> 4) as usize]));
9395            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
9396        }
9397    }
9398
9399    encoded
9400}
9401
9402fn unique_request_id(prefix: &str) -> String {
9403    let nanos = SystemTime::now()
9404        .duration_since(UNIX_EPOCH)
9405        .unwrap_or_default()
9406        .as_nanos();
9407    format!("{prefix}-{}-{nanos}", std::process::id())
9408}
9409
9410#[derive(Debug)]
9411struct QueryTaskExecutionFailure {
9412    reason: String,
9413    message: String,
9414    failure_type: String,
9415}
9416
9417impl QueryTaskExecutionFailure {
9418    fn new(
9419        reason: impl Into<String>,
9420        message: impl Into<String>,
9421        failure_type: impl Into<String>,
9422    ) -> Self {
9423        Self {
9424            reason: reason.into(),
9425            message: message.into(),
9426            failure_type: failure_type.into(),
9427        }
9428    }
9429}
9430
9431/// Typed local state owned by one deterministic workflow invocation.
9432///
9433/// Use [`WorkflowInstance::update`] for the same state transitions during
9434/// ordinary execution and replay. A replayed query receives a detached
9435/// immutable `Arc<S>` rather than this mutation-capable handle.
9436#[derive(Clone, Debug)]
9437pub struct WorkflowInstance<S> {
9438    state: Arc<Mutex<S>>,
9439}
9440
9441impl<S> WorkflowInstance<S> {
9442    fn new(state: S) -> Self {
9443        Self {
9444            state: Arc::new(Mutex::new(state)),
9445        }
9446    }
9447
9448    /// Read the current workflow-instance state without changing it.
9449    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
9450        let state = self
9451            .state
9452            .lock()
9453            .map_err(|_| Error::WorkflowStatePoisoned)?;
9454        Ok(reader(&state))
9455    }
9456
9457    /// Apply one deterministic workflow-instance state transition.
9458    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
9459        let mut state = self
9460            .state
9461            .lock()
9462            .map_err(|_| Error::WorkflowStatePoisoned)?;
9463        Ok(transition(&mut state))
9464    }
9465}
9466
9467impl<S: Clone> WorkflowInstance<S> {
9468    fn snapshot(&self) -> Result<S> {
9469        self.read(Clone::clone)
9470    }
9471}
9472
9473#[derive(Clone, Debug, PartialEq)]
9474pub struct MessageStreamMessage {
9475    pub stream_name: String,
9476    pub message_id: String,
9477    pub position: u64,
9478    pub arguments: Vec<AvroValue>,
9479}
9480
9481#[derive(Clone, Debug)]
9482pub struct MessageStream {
9483    ctx: WorkflowContext,
9484    name: String,
9485}
9486
9487impl MessageStream {
9488    /// Wait for one message, then return a bounded currently-available batch.
9489    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
9490        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
9491            return Err(Error::Codec(format!(
9492                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
9493            )));
9494        }
9495        loop {
9496            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
9497                return Ok(batch);
9498            }
9499
9500            self.ctx.record_message_stream_wait(&self.name)?;
9501            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
9502            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
9503            self.ctx.buffer_message_stream_delivery(arguments)?;
9504            if let Some(sequence) = replay_wait_sequence {
9505                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
9506            }
9507        }
9508    }
9509
9510    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
9511        self.receive(1)
9512            .await?
9513            .into_iter()
9514            .next()
9515            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
9516    }
9517}
9518
9519#[derive(Clone, Debug)]
9520pub struct WorkflowContext {
9521    state: Arc<Mutex<WorkflowState>>,
9522    cancellation_scope_id: String,
9523}
9524
9525fn valid_memo_key(key: &str) -> bool {
9526    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
9527
9528    !key.is_empty()
9529        && key.len() <= 64
9530        && (numeric_candidate.is_empty()
9531            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
9532        && key
9533            .bytes()
9534            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
9535}
9536
9537fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
9538    BASE64
9539        .decode(encode_avro_value(value)?.blob)
9540        .map(|bytes| bytes.len())
9541        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
9542}
9543
9544fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
9545    let AvroValue::Map(entries) = value else {
9546        return Err(Error::InvalidMemoUpdate(
9547            "entries must serialize to an Avro string-keyed map".to_string(),
9548        ));
9549    };
9550    if require_entries && entries.is_empty() {
9551        return Err(Error::InvalidMemoUpdate(
9552            "at least one entry is required".to_string(),
9553        ));
9554    }
9555    if entries.len() > MAX_MEMO_ENTRIES {
9556        return Err(Error::InvalidMemoUpdate(format!(
9557            "at most {MAX_MEMO_ENTRIES} entries are allowed"
9558        )));
9559    }
9560
9561    for (key, value) in &entries {
9562        if !valid_memo_key(&key) {
9563            return Err(Error::InvalidMemoUpdate(
9564                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
9565            ));
9566        }
9567        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
9568            return Err(Error::InvalidMemoUpdate(format!(
9569                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
9570            )));
9571        }
9572    }
9573
9574    let value = AvroValue::Map(entries);
9575    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
9576        return Err(Error::InvalidMemoUpdate(format!(
9577            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
9578        )));
9579    }
9580    Ok(value)
9581}
9582
9583fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
9584    let object = envelope.as_object().ok_or_else(|| {
9585        Error::InvalidMemoUpdate(
9586            "history field must use the public {codec, blob} payload envelope".to_string(),
9587        )
9588    })?;
9589    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
9590        return Err(Error::InvalidMemoUpdate(
9591            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
9592        ));
9593    }
9594
9595    canonical_memo_entries(
9596        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
9597        require_entries,
9598    )
9599}
9600
9601impl WorkflowContext {
9602    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
9603        let name = name.into();
9604        if name.is_empty()
9605            || name.len() > 128
9606            || !name.bytes().all(|byte| {
9607                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
9608            })
9609        {
9610            return Err(Error::Codec(
9611                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
9612                    .to_string(),
9613            ));
9614        }
9615        Ok(MessageStream {
9616            ctx: self.clone(),
9617            name,
9618        })
9619    }
9620
9621    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
9622        let mut state = self
9623            .state
9624            .lock()
9625            .map_err(|_| Error::WorkflowStatePoisoned)?;
9626        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9627        state
9628            .message_stream_waits
9629            .insert(name.to_string(), position);
9630        Ok(())
9631    }
9632
9633    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
9634        let mut state = self
9635            .state
9636            .lock()
9637            .map_err(|_| Error::WorkflowStatePoisoned)?;
9638        let cursor = state
9639            .message_stream_cursors
9640            .get(&message.stream_name)
9641            .copied()
9642            .unwrap_or(0);
9643        if message.position <= cursor {
9644            return Ok(());
9645        }
9646        let pending = state
9647            .message_stream_messages
9648            .entry(message.stream_name.clone())
9649            .or_default();
9650        if pending.iter().any(|candidate| {
9651            candidate.position == message.position || candidate.message_id == message.message_id
9652        }) {
9653            return Ok(());
9654        }
9655        pending.push(message);
9656        pending.sort_by_key(|candidate| candidate.position);
9657        Ok(())
9658    }
9659
9660    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
9661        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
9662            match delivery {
9663                MessageStreamDelivery::Message(message) => {
9664                    let stream_name = message.stream_name.clone();
9665                    self.buffer_message_stream(message)?;
9666                    return Ok(Some(stream_name));
9667                }
9668                MessageStreamDelivery::Cursor {
9669                    stream_name,
9670                    through_position,
9671                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
9672            }
9673        }
9674        Ok(None)
9675    }
9676
9677    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
9678        let state = self
9679            .state
9680            .lock()
9681            .map_err(|_| Error::WorkflowStatePoisoned)?;
9682        Ok(match state.recorded_commands.get(state.command_cursor) {
9683            Some(RecordedCommand::SignalWait {
9684                sequence,
9685                signal_name,
9686                ..
9687            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
9688            _ => None,
9689        })
9690    }
9691
9692    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
9693        let (history, payload_codec) = {
9694            let state = self
9695                .state
9696                .lock()
9697                .map_err(|_| Error::WorkflowStatePoisoned)?;
9698            (
9699                Arc::clone(&state.history_events),
9700                state.payload_codec.clone(),
9701            )
9702        };
9703
9704        let Some(opened_index) = history.iter().position(|event| {
9705            event.event_type == "SignalWaitOpened"
9706                && durable_event_sequence(event) == Some(wait_sequence)
9707                && event.payload.get("signal_name").and_then(Value::as_str)
9708                    == Some(MESSAGE_STREAM_SIGNAL)
9709        }) else {
9710            return Ok(());
9711        };
9712        let boundary_index = history
9713            .iter()
9714            .enumerate()
9715            .skip(opened_index + 1)
9716            .find_map(|(index, event)| {
9717                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9718                    && is_authored_command_open_event(event))
9719                .then_some(index)
9720            })
9721            .unwrap_or(history.len());
9722
9723        for event in history[opened_index + 1..boundary_index]
9724            .iter()
9725            .filter(|event| {
9726                event.event_type == "SignalReceived"
9727                    && event.payload.get("signal_name").and_then(Value::as_str)
9728                        == Some(MESSAGE_STREAM_SIGNAL)
9729            })
9730        {
9731            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9732                .into_iter()
9733                .map(AvroValue::into_json)
9734                .collect::<Result<Vec<_>>>()?;
9735            self.buffer_message_stream_delivery(arguments)?;
9736        }
9737        Ok(())
9738    }
9739
9740    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9741        let mut state = self
9742            .state
9743            .lock()
9744            .map_err(|_| Error::WorkflowStatePoisoned)?;
9745        let cursor = state
9746            .message_stream_cursors
9747            .entry(name.to_string())
9748            .or_default();
9749        *cursor = (*cursor).max(through_position);
9750        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9751            pending.retain(|message| message.position > through_position);
9752        }
9753        Ok(())
9754    }
9755
9756    fn take_message_stream_batch(
9757        &self,
9758        name: &str,
9759        max_items: usize,
9760    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9761        let mut state = self
9762            .state
9763            .lock()
9764            .map_err(|_| Error::WorkflowStatePoisoned)?;
9765        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9766        let pending = state
9767            .message_stream_messages
9768            .entry(name.to_string())
9769            .or_default();
9770        let count = contiguous_message_stream_count(pending, cursor, max_items);
9771        if count == 0 {
9772            return Ok(None);
9773        }
9774        let batch = pending.drain(..count).collect::<Vec<_>>();
9775        let position = batch.last().map(|message| message.position).unwrap_or(0);
9776        state
9777            .message_stream_cursors
9778            .insert(name.to_string(), position);
9779        state.message_stream_waits.remove(name);
9780        Ok(Some(batch))
9781    }
9782
9783    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9784        let state = self
9785            .state
9786            .lock()
9787            .map_err(|_| Error::WorkflowStatePoisoned)?;
9788        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9789        cursors.sort_by_key(|(name, _)| *name);
9790        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9791        waits.sort_by_key(|(name, _)| *name);
9792        Ok((
9793            cursors
9794                .into_iter()
9795                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9796                .collect(),
9797            waits
9798                .into_iter()
9799                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9800                .collect(),
9801        ))
9802    }
9803    /// Identity of the parent workflow currently being replayed.
9804    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9805        let state = self
9806            .state
9807            .lock()
9808            .map_err(|_| Error::WorkflowStatePoisoned)?;
9809        Ok(WorkflowIdentity {
9810            workflow_id: state.workflow_id.clone(),
9811            run_id: state.run_id.clone(),
9812        })
9813    }
9814
9815    /// Return the server-published history budget for this workflow task.
9816    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9817        let state = self
9818            .state
9819            .lock()
9820            .map_err(|_| Error::WorkflowStatePoisoned)?;
9821        Ok(state.history_budget.clone())
9822    }
9823
9824    /// Continue this workflow instance as a fresh run with replacement arguments.
9825    ///
9826    /// Return this value directly from the workflow handler. The worker converts
9827    /// it to the terminal protocol command only after replay has consumed every
9828    /// recorded durable command.
9829    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9830        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9831    }
9832
9833    /// Continue as new with optional workflow-type and task-queue overrides.
9834    pub fn continue_as_new_with_options<T: Serialize>(
9835        &self,
9836        options: ContinueAsNewOptions,
9837        args: T,
9838    ) -> Result<Value> {
9839        options.validate()?;
9840        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9841            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9842            options,
9843        }))
9844    }
9845
9846    pub fn activity<T: Serialize>(
9847        &self,
9848        activity_type: impl Into<String>,
9849        args: T,
9850    ) -> ActivityCall {
9851        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9852    }
9853
9854    pub fn activity_on_queue<T, Q>(
9855        &self,
9856        activity_type: impl Into<String>,
9857        task_queue: Option<Q>,
9858        args: T,
9859    ) -> ActivityCall
9860    where
9861        T: Serialize,
9862        Q: Into<String>,
9863    {
9864        let mut options = ActivityOptions::new();
9865        options.task_queue = task_queue.map(Into::into);
9866        self.activity_with_options(activity_type, options, args)
9867    }
9868
9869    /// Schedule one durable activity with retry, routing, and timeout options.
9870    ///
9871    /// Options are validated before the command is emitted. Once the command is
9872    /// recorded, replay consumes the same activity lifecycle at this command
9873    /// position and never emits a duplicate schedule.
9874    ///
9875    /// ```no_run
9876    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9877    /// # use std::time::Duration;
9878    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9879    /// let result = ctx
9880    ///     .activity_with_options(
9881    ///         "charge-card",
9882    ///         ActivityOptions::new()
9883    ///             .task_queue("payments")
9884    ///             .retry_policy(
9885    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9886    ///                     Duration::from_secs(1),
9887    ///                     2,
9888    ///                     Some(Duration::from_secs(30)),
9889    ///                 ),
9890    ///             )
9891    ///             .start_to_close_timeout(Duration::from_secs(60))
9892    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9893    ///             .heartbeat_timeout(Duration::from_secs(15)),
9894    ///         json!([{"order_id": "order-42"}]),
9895    ///     )
9896    ///     .await;
9897    /// match result {
9898    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9899    ///         "reason": failure.reason,
9900    ///         "timeout_kind": failure.timeout_kind,
9901    ///     })),
9902    ///     other => other,
9903    /// }
9904    /// # }
9905    /// ```
9906    pub fn activity_with_options<T: Serialize>(
9907        &self,
9908        activity_type: impl Into<String>,
9909        options: ActivityOptions,
9910        args: T,
9911    ) -> ActivityCall {
9912        ActivityCall {
9913            ctx: self.clone(),
9914            activity_type: activity_type.into(),
9915            options,
9916            worker_session: None,
9917            args: Some(AvroValue::from_serialize(&args)),
9918            scheduled: false,
9919            local: false,
9920            local_result: None,
9921            parallel_group_path: Vec::new(),
9922        }
9923    }
9924
9925    pub async fn activity_avro_value<T: Serialize>(
9926        &self,
9927        activity_type: impl Into<String>,
9928        args: T,
9929    ) -> Result<AvroValue> {
9930        let mut call = self.activity(activity_type, args);
9931        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9932    }
9933
9934    pub async fn activity_avro_value_with_options<T: Serialize>(
9935        &self,
9936        activity_type: impl Into<String>,
9937        options: ActivityOptions,
9938        args: T,
9939    ) -> Result<AvroValue> {
9940        let mut call = self.activity_with_options(activity_type, options, args);
9941        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9942    }
9943
9944    /// Schedule an activity with a Serde request and decode its Serde result.
9945    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9946    where
9947        I: Serialize,
9948        O: DeserializeOwned,
9949    {
9950        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9951            .await
9952    }
9953
9954    /// Schedule an activity with options and decode its result into `O`.
9955    ///
9956    /// Both directions use the fixed Avro Value codec. In particular, this
9957    /// method does not deserialize the JSON-safe inspection projection returned
9958    /// by the dynamic [`ActivityCall`] future.
9959    pub async fn activity_typed_with_options<I, O>(
9960        &self,
9961        activity_type: impl Into<String>,
9962        options: ActivityOptions,
9963        args: I,
9964    ) -> Result<O>
9965    where
9966        I: Serialize,
9967        O: DeserializeOwned,
9968    {
9969        let activity_type = activity_type.into();
9970        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9971            handler_type_error::<I>(
9972                HandlerKind::Activity,
9973                &activity_type,
9974                HandlerValueKind::Input,
9975                error.to_string(),
9976            )
9977        });
9978        let mut call = ActivityCall {
9979            ctx: self.clone(),
9980            activity_type: activity_type.clone(),
9981            options,
9982            worker_session: None,
9983            args: Some(encoded),
9984            scheduled: false,
9985            local: false,
9986            local_result: None,
9987            parallel_group_path: Vec::new(),
9988        };
9989        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9990        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9991    }
9992
9993    /// Schedule and join a deterministic activity/child/timer group.
9994    ///
9995    /// Nested groups retain their input shape. Every durable leaf is scheduled
9996    /// before this future yields, results are assembled by declaration order,
9997    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9998    /// declaration path, stable group metadata, and completed siblings.
9999    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10000        ParallelCall::new(self.clone(), operations)
10001    }
10002
10003    /// Alias for [`WorkflowContext::parallel`].
10004    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10005        self.parallel(operations)
10006    }
10007
10008    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10009    pub async fn parallel_avro_value(
10010        &self,
10011        operations: Vec<ParallelOperation>,
10012    ) -> Result<Vec<ParallelAvroResult>> {
10013        let mut call = self.parallel(operations);
10014        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10015    }
10016
10017    /// Start every durable operation and resume from the one winner persisted
10018    /// by Server. Non-winning operations continue and remain addressable.
10019    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10020        let operations = operations
10021            .into_iter()
10022            .enumerate()
10023            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10024            .collect();
10025        SelectCall::new(self.clone(), operations)
10026    }
10027
10028    /// Named-key variant of [`WorkflowContext::select`].
10029    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10030    where
10031        K: Into<SelectionKey>,
10032    {
10033        SelectCall::new(
10034            self.clone(),
10035            operations
10036                .into_iter()
10037                .map(|(key, operation)| (key.into(), operation))
10038                .collect(),
10039        )
10040    }
10041
10042    /// Create a workflow-local deterministic compensation registry.
10043    pub fn saga(&self) -> Saga {
10044        Saga::new(self.clone())
10045    }
10046
10047    /// Whether cancellation has reached this replay's authored boundary.
10048    ///
10049    /// Server's current `/cancel` route is terminal and does not set this flag.
10050    /// A canonical service request remains pending until its committed delivery
10051    /// is consumed. Request observation alone does not authorize an exception.
10052    pub fn is_cancellation_requested(&self) -> Result<bool> {
10053        let state = self
10054            .state
10055            .lock()
10056            .map_err(|_| Error::WorkflowStatePoisoned)?;
10057        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10058            return Ok(state
10059                .scope_delivery
10060                .as_ref()
10061                .unwrap()
10062                .contexts
10063                .contains_key(&self.cancellation_scope_id));
10064        }
10065        Ok(state.cancel_requested
10066            || state
10067                .scope_delivery
10068                .as_ref()
10069                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10070    }
10071
10072    /// Raise a typed cooperative cancellation at an author-controlled point.
10073    ///
10074    /// Passing this result to [`Saga::finish`] compensates already registered
10075    /// forward steps before the cancellation remains the initiating outcome.
10076    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10077        let mut state = self
10078            .state
10079            .lock()
10080            .map_err(|_| Error::WorkflowStatePoisoned)?;
10081        if state.cancellation_shield_depth == 0 {
10082            if let Some(replay) = &state.scope_delivery {
10083                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10084                    let delivered = replay
10085                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10086                        .ok_or_else(|| {
10087                            Error::InvalidCooperativeCancellation(
10088                                "scoped request lacks its consumed original delivery".into(),
10089                            )
10090                        })?;
10091                    return Err(Error::CancellationScopeRequested(
10092                        CancellationScopeRequested {
10093                            context: context
10094                                .clone()
10095                                .with_replay(Some(Arc::downgrade(&self.state))),
10096                            delivery: delivered.boundary.clone(),
10097                        },
10098                    ));
10099                }
10100            }
10101        }
10102        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10103            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10104                return Ok(());
10105            }
10106            return Err(state.cancellation_error());
10107        }
10108        Ok(())
10109    }
10110
10111    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10112        SignalCall {
10113            ctx: self.clone(),
10114            signal_name: signal_name.into(),
10115            runtime_reserved_allowed: false,
10116            opened_wait: false,
10117            matched_pending: false,
10118            parallel_group_path: Vec::new(),
10119        }
10120    }
10121
10122    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10123        SignalCall {
10124            ctx: self.clone(),
10125            signal_name: signal_name.into(),
10126            runtime_reserved_allowed: true,
10127            opened_wait: false,
10128            matched_pending: false,
10129            parallel_group_path: Vec::new(),
10130        }
10131    }
10132
10133    pub async fn wait_signal_avro_value(
10134        &self,
10135        signal_name: impl Into<String>,
10136    ) -> Result<Vec<AvroValue>> {
10137        let mut call = self.wait_signal(signal_name);
10138        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10139    }
10140
10141    /// Return every committed signal argument list with the given name.
10142    ///
10143    /// This history-backed view is deterministic and is intended for
10144    /// condition predicates that must be re-evaluated after a signal while the
10145    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10146    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10147        self.signals_avro_value(signal_name)?
10148            .into_iter()
10149            .map(|arguments| {
10150                arguments
10151                    .into_iter()
10152                    .map(AvroValue::into_json)
10153                    .collect::<Result<Vec<_>>>()
10154            })
10155            .collect()
10156    }
10157
10158    /// Lossless fixed Avro Value view of committed signals with the given name.
10159    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10160        let state = self
10161            .state
10162            .lock()
10163            .map_err(|_| Error::WorkflowStatePoisoned)?;
10164        state
10165            .history_events
10166            .iter()
10167            .filter(|event| {
10168                event.event_type == "SignalReceived"
10169                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10170            })
10171            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10172            .collect()
10173    }
10174
10175    /// Return every committed update argument list with the given name.
10176    ///
10177    /// Accepted and applied records for the same update ID are de-duplicated.
10178    /// A Server task created after an update therefore replays the workflow and
10179    /// re-evaluates an open condition without application polling.
10180    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10181        self.updates_avro_value(update_name)?
10182            .into_iter()
10183            .map(|arguments| {
10184                arguments
10185                    .into_iter()
10186                    .map(AvroValue::into_json)
10187                    .collect::<Result<Vec<_>>>()
10188            })
10189            .collect()
10190    }
10191
10192    /// Lossless fixed Avro Value view of committed updates with the given name.
10193    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10194        let state = self
10195            .state
10196            .lock()
10197            .map_err(|_| Error::WorkflowStatePoisoned)?;
10198        let mut seen = Vec::new();
10199        let mut updates = Vec::new();
10200        for event in state.history_events.iter() {
10201            if !matches!(
10202                event.event_type.as_str(),
10203                "UpdateAccepted" | "UpdateApplied"
10204            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
10205                || event.payload.get("arguments").is_none()
10206            {
10207                continue;
10208            }
10209            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
10210                if seen.iter().any(|recorded| recorded == update_id) {
10211                    continue;
10212                }
10213                seen.push(update_id.to_string());
10214            }
10215            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
10216        }
10217        Ok(updates)
10218    }
10219
10220    /// Wait for a deterministic predicate to become true or for its durable
10221    /// timeout to elapse.
10222    ///
10223    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
10224    /// predicate tokens automatically change the recorded definition
10225    /// fingerprint. Direct callers must provide an equally stable identity in
10226    /// [`ConditionWaitOptions`].
10227    pub fn wait_condition<F>(
10228        &self,
10229        options: ConditionWaitOptions,
10230        predicate: F,
10231    ) -> ConditionWaitCall
10232    where
10233        F: Fn() -> Result<bool> + Send + 'static,
10234    {
10235        ConditionWaitCall {
10236            ctx: self.clone(),
10237            options,
10238            predicate: Box::new(predicate),
10239            occurrence_id: None,
10240            opened_wait: false,
10241            parallel_group_path: Vec::new(),
10242        }
10243    }
10244
10245    /// Wait for server-backed durable time without blocking the worker executor.
10246    ///
10247    /// Polling this future emits one `start_timer` command and yields. The
10248    /// server records the deadline, so neither worker nor server restarts reset
10249    /// the wait. Replay resolves the future only from a `TimerScheduled` and
10250    /// `TimerFired` pair at the same position in the shared durable-command
10251    /// stream, with matching sequence, timer identity, and delay. Sub-second
10252    /// durations round up because protocol deadlines use whole seconds.
10253    ///
10254    /// ```no_run
10255    /// # use durable_workflow::{json, Client, Worker};
10256    /// # use std::time::Duration;
10257    /// # fn configure(client: Client) {
10258    /// let mut worker = Worker::new(client, "rust-workers");
10259    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
10260    ///     ctx.sleep(Duration::from_secs(5)).await?;
10261    ///     Ok(json!({"status": "timer fired"}))
10262    /// });
10263    /// # }
10264    /// ```
10265    pub fn sleep(&self, duration: Duration) -> TimerCall {
10266        let delay_seconds = duration
10267            .as_secs()
10268            .checked_add(u64::from(duration.subsec_nanos() > 0));
10269        TimerCall {
10270            ctx: self.clone(),
10271            delay_seconds,
10272            scheduled: false,
10273            matched_pending: false,
10274            parallel_group_path: Vec::new(),
10275        }
10276    }
10277
10278    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
10279    pub fn start_timer(&self, duration: Duration) -> TimerCall {
10280        self.sleep(duration)
10281    }
10282
10283    /// Evaluate a non-deterministic callback once and durably record its typed value.
10284    ///
10285    /// On replay the callback is not invoked: the value is decoded from the
10286    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
10287    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
10288    /// small values that must remain fixed for the lifetime of a workflow run.
10289    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
10290    where
10291        T: Serialize + DeserializeOwned,
10292        F: FnOnce() -> T,
10293    {
10294        {
10295            let mut state = self
10296                .state
10297                .lock()
10298                .map_err(|_| Error::WorkflowStatePoisoned)?;
10299            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10300                return match recorded {
10301                    RecordedCommand::SideEffect { sequence, value } => {
10302                        state.command_cursor += 1;
10303                        value.deserialize().map_err(|error| {
10304                            Error::NonDeterministicReplay(ReplayFailure::new(
10305                                "side_effect_type_mismatch",
10306                                Some(sequence),
10307                                Some(std::any::type_name::<T>().to_string()),
10308                                Some(error.to_string()),
10309                                "recorded side-effect value is incompatible with the requested Rust type",
10310                            ))
10311                        })
10312                    }
10313                    other => Err(command_mismatch(&other, "side effect")),
10314                };
10315            }
10316        }
10317
10318        let value = callback();
10319        let avro_value = AvroValue::from_serialize(&value)?;
10320        let mut state = self
10321            .state
10322            .lock()
10323            .map_err(|_| Error::WorkflowStatePoisoned)?;
10324        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
10325        state.commands.push(json!({
10326            "type": "record_side_effect",
10327            "result": result,
10328        }));
10329        Ok(value)
10330    }
10331
10332    /// Record or replay a lossless fixed Avro Value side effect.
10333    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
10334    where
10335        F: FnOnce() -> AvroValue,
10336    {
10337        {
10338            let mut state = self
10339                .state
10340                .lock()
10341                .map_err(|_| Error::WorkflowStatePoisoned)?;
10342            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10343                return match recorded {
10344                    RecordedCommand::SideEffect { value, .. } => {
10345                        state.command_cursor += 1;
10346                        Ok(value)
10347                    }
10348                    other => Err(command_mismatch(&other, "side effect")),
10349                };
10350            }
10351        }
10352
10353        let value = callback();
10354        let mut state = self
10355            .state
10356            .lock()
10357            .map_err(|_| Error::WorkflowStatePoisoned)?;
10358        let result = encode_typed_envelope(&value, &state.payload_codec)?;
10359        state.commands.push(json!({
10360            "type": "record_side_effect",
10361            "result": result,
10362        }));
10363        Ok(value)
10364    }
10365
10366    /// Append output items at a deterministic workflow command boundary.
10367    ///
10368    /// Stable idempotency keys are derived from the server-provided durable
10369    /// workflow command identity, command ordinal, and item index. Replay
10370    /// consumes the recorded side effect and never emits another append.
10371    pub fn append_workflow_stream(
10372        &self,
10373        stream_name: impl Into<String>,
10374        items: &[WorkflowStreamAppendItem],
10375        max_pending_items: Option<u64>,
10376    ) -> Result<()> {
10377        if items.is_empty() {
10378            return Err(Error::Codec(
10379                "workflow_stream_items_empty: append requires at least one item".to_string(),
10380            ));
10381        }
10382        if max_pending_items == Some(0) {
10383            return Err(Error::Codec(
10384                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
10385                    .to_string(),
10386            ));
10387        }
10388        let stream_name = stream_name.into();
10389        if stream_name.is_empty() {
10390            return Err(Error::Codec(
10391                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10392            ));
10393        }
10394
10395        let mut state = self
10396            .state
10397            .lock()
10398            .map_err(|_| Error::WorkflowStatePoisoned)?;
10399        let command_ordinal = state.workflow_stream_command_counter;
10400        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10401            state.workflow_stream_command_counter += 1;
10402            return match recorded {
10403                RecordedCommand::SideEffect { .. } => {
10404                    state.command_cursor += 1;
10405                    Ok(())
10406                }
10407                other => Err(command_mismatch(&other, "workflow stream append")),
10408            };
10409        }
10410
10411        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10412        state.workflow_stream_command_counter += 1;
10413        let wire_items = items
10414            .iter()
10415            .enumerate()
10416            .map(|(item_index, item)| {
10417                item.wire_value(Some(format!(
10418                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
10419                )))
10420            })
10421            .collect::<Vec<_>>();
10422        let mut directive = json!({
10423            "operation": "append",
10424            "stream_name": stream_name,
10425            "command_identity": identity,
10426            "command_ordinal": command_ordinal,
10427            "items": wire_items,
10428        });
10429        if let Some(max_pending_items) = max_pending_items {
10430            directive["max_pending_items"] = json!(max_pending_items);
10431        }
10432        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10433        state.commands.push(json!({
10434            "type": "record_side_effect",
10435            "result": result,
10436            "workflow_stream": directive,
10437        }));
10438        Ok(())
10439    }
10440
10441    /// Close a run-scoped output stream at a deterministic command boundary.
10442    pub fn close_workflow_stream(
10443        &self,
10444        stream_name: impl Into<String>,
10445        retention_seconds: Option<u64>,
10446    ) -> Result<()> {
10447        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
10448    }
10449
10450    /// Mark a run-scoped output stream errored at a deterministic command boundary.
10451    pub fn error_workflow_stream(
10452        &self,
10453        stream_name: impl Into<String>,
10454        error_reason: impl Into<String>,
10455        retention_seconds: Option<u64>,
10456    ) -> Result<()> {
10457        let error_reason = error_reason.into();
10458        if error_reason.is_empty() {
10459            return Err(Error::Codec(
10460                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
10461            ));
10462        }
10463        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
10464    }
10465
10466    fn finish_workflow_stream(
10467        &self,
10468        stream_name: String,
10469        error_reason: Option<String>,
10470        retention_seconds: Option<u64>,
10471    ) -> Result<()> {
10472        if stream_name.is_empty() {
10473            return Err(Error::Codec(
10474                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10475            ));
10476        }
10477        if retention_seconds == Some(0) {
10478            return Err(Error::Codec(
10479                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
10480            ));
10481        }
10482        let mut state = self
10483            .state
10484            .lock()
10485            .map_err(|_| Error::WorkflowStatePoisoned)?;
10486        let command_ordinal = state.workflow_stream_command_counter;
10487        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10488            state.workflow_stream_command_counter += 1;
10489            return match recorded {
10490                RecordedCommand::SideEffect { .. } => {
10491                    state.command_cursor += 1;
10492                    Ok(())
10493                }
10494                other => Err(command_mismatch(&other, "workflow stream close")),
10495            };
10496        }
10497        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10498        state.workflow_stream_command_counter += 1;
10499        let mut directive = json!({
10500            "operation": if error_reason.is_some() { "error" } else { "close" },
10501            "stream_name": stream_name,
10502            "command_identity": identity,
10503            "command_ordinal": command_ordinal,
10504        });
10505        if let Some(error_reason) = error_reason {
10506            directive["error_reason"] = json!(error_reason);
10507        }
10508        if let Some(retention_seconds) = retention_seconds {
10509            directive["retention_seconds"] = json!(retention_seconds);
10510        }
10511        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10512        state.commands.push(json!({
10513            "type": "record_side_effect",
10514            "result": result,
10515            "workflow_stream": directive,
10516        }));
10517        Ok(())
10518    }
10519
10520    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
10521        let identity = state.workflow_command_identity.as_str();
10522        if identity.is_empty() {
10523            return Err(Error::MissingWorkflowCommandIdentity);
10524        }
10525        Ok(identity)
10526    }
10527
10528    /// Validate, emit, or replay a typed workflow search-attribute update.
10529    ///
10530    /// The command is non-blocking within a workflow decision, but its
10531    /// `SearchAttributesUpserted` event occupies the same deterministic command
10532    /// stream as activities, timers, conditions, and other durable operations.
10533    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
10534        update.validate()?;
10535        let (attributes, attribute_types) = update.into_wire_parts();
10536        let mut state = self
10537            .state
10538            .lock()
10539            .map_err(|_| Error::WorkflowStatePoisoned)?;
10540
10541        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10542            return match recorded {
10543                RecordedCommand::SearchAttributes {
10544                    sequence,
10545                    attributes: recorded_attributes,
10546                    attribute_types: recorded_attribute_types,
10547                } => {
10548                    if recorded_attributes != attributes {
10549                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10550                            "search_attribute_value_mismatch",
10551                            Some(sequence),
10552                            Some(recorded_attributes.to_string()),
10553                            Some(attributes.to_string()),
10554                            "search-attribute values differ from the recorded durable command",
10555                        )));
10556                    }
10557                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
10558                        if recorded_types != attribute_types {
10559                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10560                                "search_attribute_type_mismatch",
10561                                Some(sequence),
10562                                Some(json!(recorded_types).to_string()),
10563                                Some(json!(attribute_types).to_string()),
10564                                "search-attribute declared types differ from the recorded durable command",
10565                            )));
10566                        }
10567                    }
10568                    state.command_cursor += 1;
10569                    Ok(())
10570                }
10571                other => Err(command_mismatch(&other, "search-attribute update")),
10572            };
10573        }
10574
10575        let mut command = serde_json::Map::from_iter([
10576            ("type".to_string(), json!("upsert_search_attributes")),
10577            ("attributes".to_string(), attributes),
10578        ]);
10579        if !attribute_types.is_empty() {
10580            command.insert("attribute_types".to_string(), json!(attribute_types));
10581        }
10582        state.commands.push(Value::Object(command));
10583        Ok(())
10584    }
10585
10586    /// Record a UUIDv4 once and return the same UUID on every replay.
10587    pub fn uuid_v4(&self) -> Result<Uuid> {
10588        self.side_effect(Uuid::new_v4)
10589    }
10590
10591    /// Select the newest supported version for a change, or replay the version
10592    /// already committed for that stable change ID.
10593    ///
10594    /// An unmarked old history that reached its next durable operation, or
10595    /// already completed, selects `-1` when that version is supported. This
10596    /// leaves the original operation available and writes no additional marker.
10597    /// Consistent markers written by older workers retain their original ordered
10598    /// positions. Repeated calls consume a matching marker at the current cursor.
10599    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
10600    pub fn get_version(
10601        &self,
10602        change_id: impl Into<String>,
10603        min_supported: i32,
10604        max_supported: i32,
10605    ) -> Result<i32> {
10606        let change_id = change_id.into();
10607        if change_id.trim().is_empty() {
10608            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10609                "version_change_id_invalid",
10610                None,
10611                Some("non-empty change ID".to_string()),
10612                Some(change_id),
10613                "version markers require a stable non-empty change ID",
10614            )));
10615        }
10616        if min_supported > max_supported {
10617            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10618                "version_range_invalid",
10619                None,
10620                Some("min_supported <= max_supported".to_string()),
10621                Some(format!("{min_supported}..={max_supported}")),
10622                "version marker supported range is invalid",
10623            )));
10624        }
10625
10626        let mut state = self
10627            .state
10628            .lock()
10629            .map_err(|_| Error::WorkflowStatePoisoned)?;
10630        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
10631            if let Some(RecordedCommand::VersionMarker {
10632                sequence: alias_sequence,
10633                change_id: alias_change_id,
10634                version: alias_version,
10635            }) = state.recorded_commands.get(state.command_cursor)
10636            {
10637                if alias_change_id == &change_id {
10638                    if *alias_version != version {
10639                        return Err(invalid_recorded_history(
10640                            "version_marker_conflict",
10641                            *alias_sequence,
10642                            &format!("selected version {version} for change ID {change_id:?}"),
10643                            &format!("recorded version {alias_version}"),
10644                            "recorded marker conflicts with the decision already selected during replay",
10645                        ));
10646                    }
10647                    ensure_version_supported(
10648                        &change_id,
10649                        version,
10650                        min_supported,
10651                        max_supported,
10652                        *alias_sequence,
10653                    )?;
10654                    // Older workers could record the same decision again. Keep
10655                    // each physical boundary without skipping intervening work.
10656                    state.command_cursor += 1;
10657                    return Ok(version);
10658                }
10659            }
10660            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
10661            return Ok(version);
10662        }
10663
10664        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10665            return match recorded {
10666                RecordedCommand::VersionMarker {
10667                    sequence,
10668                    change_id: recorded_change_id,
10669                    version,
10670                    ..
10671                } => {
10672                    if recorded_change_id != change_id {
10673                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10674                            "version_change_id_mismatch",
10675                            Some(sequence),
10676                            Some(recorded_change_id),
10677                            Some(change_id),
10678                            "recorded version marker change ID differs from current workflow code",
10679                        )));
10680                    }
10681                    ensure_version_supported(
10682                        &change_id,
10683                        version,
10684                        min_supported,
10685                        max_supported,
10686                        sequence,
10687                    )?;
10688                    state.command_cursor += 1;
10689                    state.version_markers.insert(change_id, (version, sequence));
10690                    Ok(version)
10691                }
10692                other => {
10693                    let version = -1;
10694                    let sequence = other.sequence();
10695                    ensure_version_supported(
10696                        &change_id,
10697                        version,
10698                        min_supported,
10699                        max_supported,
10700                        sequence,
10701                    )?;
10702                    // The existing operation proves this patch site was reached
10703                    // before its marker existed. Keep its original cursor.
10704                    state.version_markers.insert(change_id, (version, sequence));
10705                    Ok(version)
10706                }
10707            };
10708        }
10709
10710        if state
10711            .history_events
10712            .iter()
10713            .any(|event| event.event_type == "WorkflowCompleted")
10714        {
10715            let version = -1;
10716            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
10717            state.version_markers.insert(change_id, (version, 0));
10718            return Ok(version);
10719        }
10720
10721        let version = max_supported;
10722        state.commands.push(json!({
10723            "type": "record_version_marker",
10724            "change_id": change_id,
10725            "version": version,
10726            "min_supported": min_supported,
10727            "max_supported": max_supported,
10728        }));
10729        // Sequence numbers are assigned by the server. Zero identifies a marker
10730        // selected in this uncommitted decision batch for duplicate-call checks.
10731        state.version_markers.insert(change_id, (version, 0));
10732        Ok(version)
10733    }
10734
10735    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
10736    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
10737        Ok(self.get_version(change_id, -1, 1)? == 1)
10738    }
10739
10740    /// Keep a patch marker in history after the legacy branch has been removed.
10741    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
10742        self.get_version(change_id, -1, 1).map(|_| ())
10743    }
10744
10745    /// Merge non-indexed workflow memo metadata through durable history.
10746    ///
10747    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
10748    /// public Avro payload envelope consumed by Server and Cloud runtimes.
10749    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
10750        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
10751        let mut state = self
10752            .state
10753            .lock()
10754            .map_err(|_| Error::WorkflowStatePoisoned)?;
10755
10756        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10757            return match recorded {
10758                RecordedCommand::Memo {
10759                    sequence,
10760                    entries: recorded_entries,
10761                } => {
10762                    if recorded_entries != entries {
10763                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10764                            "memo_update_mismatch",
10765                            Some(sequence),
10766                            Some(format!("{recorded_entries:?}")),
10767                            Some(format!("{entries:?}")),
10768                            "recorded memo entries differ from the current workflow update",
10769                        )));
10770                    }
10771                    state.command_cursor += 1;
10772                    Ok(())
10773                }
10774                other => Err(command_mismatch(&other, "memo upsert")),
10775            };
10776        }
10777
10778        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10779        state.commands.push(json!({
10780            "type": "upsert_memo",
10781            "entries": entries_envelope,
10782        }));
10783        Ok(())
10784    }
10785
10786    /// Start a named durable child on an explicit queue and await its result.
10787    ///
10788    /// The command is recorded in the parent's sequence-ordered durable command
10789    /// stream. Replay keeps a scheduled child pending without emitting another
10790    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10791    /// values preserve the history payload codec and include both sides of the
10792    /// durable relationship; failures are returned as
10793    /// [`Error::ChildWorkflowFailed`].
10794    ///
10795    /// ```no_run
10796    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10797    /// # fn configure(client: Client) {
10798    /// let mut worker = Worker::new(client, "parent-workers");
10799    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10800    ///     let child = ctx
10801    ///         .start_child_workflow(
10802    ///             "fulfil-order",
10803    ///             ChildWorkflowOptions::new("fulfilment-workers")
10804    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10805    ///             json!([{"order_id": "order-42"}]),
10806    ///         )
10807    ///         .await?;
10808    ///     Ok(child.result)
10809    /// });
10810    /// # }
10811    /// ```
10812    pub fn start_child_workflow<T: Serialize>(
10813        &self,
10814        workflow_type: impl Into<String>,
10815        options: ChildWorkflowOptions,
10816        args: T,
10817    ) -> ChildWorkflowCall {
10818        ChildWorkflowCall {
10819            ctx: self.clone(),
10820            workflow_type: workflow_type.into(),
10821            options,
10822            args: Some(AvroValue::from_serialize(&args)),
10823            scheduled: false,
10824            matched_pending: false,
10825            parallel_group_path: Vec::new(),
10826        }
10827    }
10828
10829    pub async fn start_child_workflow_avro_value<T: Serialize>(
10830        &self,
10831        workflow_type: impl Into<String>,
10832        options: ChildWorkflowOptions,
10833        args: T,
10834    ) -> Result<ChildWorkflowAvroResult> {
10835        let mut call = self.start_child_workflow(workflow_type, options, args);
10836        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10837    }
10838
10839    fn take_commands(&self) -> Result<Vec<Value>> {
10840        let mut state = self
10841            .state
10842            .lock()
10843            .map_err(|_| Error::WorkflowStatePoisoned)?;
10844        Ok(std::mem::take(&mut state.commands))
10845    }
10846
10847    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10848        let mut state = self
10849            .state
10850            .lock()
10851            .map_err(|_| Error::WorkflowStatePoisoned)?;
10852
10853        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10854            return Err(command_mismatch(&recorded, "continue as new"));
10855        }
10856        if state.recorded_continue_as_new_sequence.is_some() {
10857            state.continue_as_new_consumed = true;
10858            return Ok(None);
10859        }
10860
10861        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10862        let mut command = serde_json::Map::from_iter([
10863            ("type".to_string(), json!("continue_as_new")),
10864            ("arguments".to_string(), arguments),
10865            ("queue".to_string(), json!(state.task_queue.clone())),
10866        ]);
10867        if let Some(workflow_type) = request.options.workflow_type {
10868            command.insert("workflow_type".to_string(), json!(workflow_type));
10869        }
10870        if let Some(task_queue) = request.options.task_queue {
10871            command.insert("queue".to_string(), json!(task_queue));
10872        }
10873        Ok(Some(Value::Object(command)))
10874    }
10875
10876    fn matched_recorded_pending(&self) -> Result<bool> {
10877        let state = self
10878            .state
10879            .lock()
10880            .map_err(|_| Error::WorkflowStatePoisoned)?;
10881        Ok(state.matched_recorded_pending)
10882    }
10883
10884    fn ensure_history_consumed(&self) -> Result<()> {
10885        let state = self
10886            .state
10887            .lock()
10888            .map_err(|_| Error::WorkflowStatePoisoned)?;
10889        if let Some(replay) = &state.scope_delivery {
10890            if let Some((&sequence, _)) = replay
10891                .canonical
10892                .deliveries
10893                .iter()
10894                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10895            {
10896                return Err(invalid_recorded_history(
10897                    "cancellation_scope_delivery_unconsumed",
10898                    sequence,
10899                    "original scoped delivery",
10900                    "workflow completion",
10901                    "workflow completed without consuming its committed scope delivery",
10902                ));
10903            }
10904        }
10905        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10906            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10907                "recorded_commands_unconsumed",
10908                Some(command.sequence()),
10909                Some(command.shape().to_string()),
10910                Some("workflow completion".to_string()),
10911                "workflow completed before consuming all recorded durable commands",
10912            )));
10913        }
10914        if let Some(delivery) = state
10915            .cancellation_history
10916            .delivery
10917            .as_ref()
10918            .filter(|_| !state.cancellation_consumed)
10919        {
10920            return Err(invalid_recorded_history(
10921                "cooperative_cancellation_unconsumed",
10922                delivery.sequence,
10923                "committed cancellation call",
10924                "workflow completion",
10925                "workflow completed without reaching its committed cancellation boundary",
10926            ));
10927        }
10928        if let Some(sequence) = state
10929            .recorded_continue_as_new_sequence
10930            .filter(|_| !state.continue_as_new_consumed)
10931        {
10932            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10933                "recorded_continue_as_new_unconsumed",
10934                Some(sequence),
10935                Some("continue as new".to_string()),
10936                Some("workflow completion".to_string()),
10937                "workflow completed without consuming its recorded continue-as-new transition",
10938            )));
10939        }
10940        Ok(())
10941    }
10942}
10943
10944fn contiguous_message_stream_count(
10945    pending: &[MessageStreamMessage],
10946    cursor: u64,
10947    max_items: usize,
10948) -> usize {
10949    pending
10950        .iter()
10951        .take(max_items)
10952        .enumerate()
10953        .take_while(|(offset, message)| {
10954            u64::try_from(*offset)
10955                .ok()
10956                .and_then(|offset| cursor.checked_add(offset + 1))
10957                == Some(message.position)
10958        })
10959        .count()
10960}
10961
10962fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10963    matches!(
10964        event.event_type.as_str(),
10965        "ActivityScheduled"
10966            | "TimerScheduled"
10967            | "ChildWorkflowScheduled"
10968            | "SignalWaitOpened"
10969            | "ConditionWaitOpened"
10970            | "SearchAttributesUpserted"
10971            | "SideEffectRecorded"
10972            | "VersionMarkerRecorded"
10973            | "MemoUpserted"
10974            | "WorkflowContinuedAsNew"
10975    )
10976}
10977
10978#[derive(Debug)]
10979struct WorkflowState {
10980    workflow_id: Option<String>,
10981    run_id: Option<String>,
10982    task_queue: String,
10983    payload_codec: String,
10984    history_events: Arc<Vec<HistoryEvent>>,
10985    history_budget: WorkflowHistoryBudget,
10986    cancel_requested: bool,
10987    cancellation_history: CancellationHistory,
10988    cancellation_consumed: bool,
10989    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10990    cancellation_shield_depth: u64,
10991    cancellation_delivery_enabled: bool,
10992    cancellation_delivery_intent: Option<CancellationDelivery>,
10993    cancellation_delivery_command_count: usize,
10994    allow_cancellation_scope_authoring: bool,
10995    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10996    cancellation_scope_memberships: BTreeMap<u64, String>,
10997    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10998    resume_signal: Option<ResumeSignal>,
10999    recorded_commands: Vec<RecordedCommand>,
11000    selection_markers: Vec<SelectionMarker>,
11001    selection_marker_cursor: usize,
11002    cancelled_selection_members: Vec<SelectionCancellation>,
11003    recorded_continue_as_new_sequence: Option<u64>,
11004    continue_as_new_consumed: bool,
11005    command_cursor: usize,
11006    condition_wait_occurrence_counter: u64,
11007    matched_recorded_pending: bool,
11008    version_markers: HashMap<String, (i32, u64)>,
11009    workflow_command_identity: String,
11010    workflow_stream_command_counter: u64,
11011    commands: Vec<Value>,
11012    local_activity_requests: Vec<local_activity::Request>,
11013    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11014    message_stream_cursors: HashMap<String, u64>,
11015    message_stream_waits: HashMap<String, u64>,
11016}
11017
11018impl WorkflowState {
11019    #[cfg(test)]
11020    fn new(
11021        history: Vec<HistoryEvent>,
11022        task_queue: String,
11023        payload_codec: String,
11024        resume_signal: Option<ResumeSignal>,
11025    ) -> Result<Self> {
11026        Self::new_with_identity(
11027            history,
11028            None,
11029            None,
11030            task_queue,
11031            payload_codec,
11032            resume_signal,
11033        )
11034    }
11035
11036    fn new_with_identity(
11037        history: Vec<HistoryEvent>,
11038        workflow_id: Option<String>,
11039        run_id: Option<String>,
11040        task_queue: String,
11041        payload_codec: String,
11042        resume_signal: Option<ResumeSignal>,
11043    ) -> Result<Self> {
11044        Self::new_with_identity_and_scopes(
11045            history,
11046            workflow_id,
11047            run_id,
11048            task_queue,
11049            payload_codec,
11050            resume_signal,
11051            false,
11052        )
11053    }
11054
11055    fn new_with_identity_and_scopes(
11056        history: Vec<HistoryEvent>,
11057        workflow_id: Option<String>,
11058        run_id: Option<String>,
11059        task_queue: String,
11060        payload_codec: String,
11061        resume_signal: Option<ResumeSignal>,
11062        allow_cancellation_scope_authoring: bool,
11063    ) -> Result<Self> {
11064        Self::new_with_identity_and_scope_delivery(
11065            history,
11066            workflow_id,
11067            run_id,
11068            task_queue,
11069            payload_codec,
11070            resume_signal,
11071            allow_cancellation_scope_authoring,
11072            false,
11073        )
11074    }
11075
11076    fn new_with_identity_and_scope_delivery(
11077        history: Vec<HistoryEvent>,
11078        workflow_id: Option<String>,
11079        run_id: Option<String>,
11080        task_queue: String,
11081        payload_codec: String,
11082        resume_signal: Option<ResumeSignal>,
11083        allow_cancellation_scope_authoring: bool,
11084        allow_cancellation_scope_delivery: bool,
11085    ) -> Result<Self> {
11086        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11087            &history,
11088            allow_cancellation_scope_authoring,
11089            allow_cancellation_scope_delivery,
11090        )?;
11091        let scopes = if allow_cancellation_scope_authoring {
11092            cancellation_scope::CancellationScopeHistory::read(
11093                &history,
11094                run_id.as_deref().unwrap_or_default(),
11095            )?
11096        } else {
11097            cancellation_scope::CancellationScopeHistory::default()
11098        };
11099        let cancellation_history = CancellationHistory::from_events(
11100            &history,
11101            run_id.as_deref().unwrap_or_default(),
11102            None,
11103        )?;
11104        if allow_cancellation_scope_authoring
11105            && cancellation_history.request.is_some()
11106            && !allow_cancellation_scope_delivery
11107        {
11108            return Err(Error::CancellationScopeExecutionUnavailable);
11109        }
11110        let scope_delivery = if allow_cancellation_scope_delivery {
11111            Some(cancellation_scope_replay::ScopeReplay::read(
11112                &history,
11113                &scopes,
11114                run_id.as_deref().unwrap_or_default(),
11115                workflow_id.as_deref().unwrap_or_default(),
11116            )?)
11117        } else {
11118            None
11119        };
11120        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11121            &history,
11122            &payload_codec,
11123            WorkflowIdentity {
11124                workflow_id: workflow_id.clone(),
11125                run_id: run_id.clone(),
11126            },
11127        )?)?;
11128        for (sequence, opening) in &scopes.openings {
11129            if recorded_commands
11130                .iter()
11131                .any(|command| command.sequence() == *sequence)
11132            {
11133                return Err(invalid_recorded_history(
11134                    "invalid_cancellation_scope_history",
11135                    *sequence,
11136                    "distinct authored scope opening",
11137                    "operation collision",
11138                    "scope opening collides with a command",
11139                ));
11140            }
11141            recorded_commands.push(RecordedCommand::CancellationScope {
11142                sequence: *sequence,
11143                scope_id: opening.scope_id.clone(),
11144                parent_scope_id: opening.parent_scope_id.clone(),
11145                shield_parent: opening.shield_parent,
11146            });
11147        }
11148        recorded_commands.sort_by_key(RecordedCommand::sequence);
11149        if let Some(replay) = &scope_delivery {
11150            replay.bind_commands(&mut recorded_commands)?;
11151        }
11152        let selection_markers = recorded_selection_markers(&history)?;
11153        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11154        let recorded_continue_as_new = history
11155            .iter()
11156            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11157            .collect::<Vec<_>>();
11158        if recorded_continue_as_new.len() > 1 {
11159            return Err(invalid_recorded_history(
11160                "duplicate_continue_as_new_transition",
11161                recorded_continue_as_new
11162                    .last()
11163                    .and_then(|event| durable_event_sequence(event))
11164                    .unwrap_or(0),
11165                "one WorkflowContinuedAsNew event",
11166                &format!(
11167                    "{} WorkflowContinuedAsNew events",
11168                    recorded_continue_as_new.len()
11169                ),
11170                "workflow history records one continue-as-new transition more than once",
11171            ));
11172        }
11173        let recorded_continue_as_new_sequence = recorded_continue_as_new
11174            .first()
11175            .map(|event| {
11176                durable_event_sequence(event).ok_or_else(|| {
11177                    Error::NonDeterministicReplay(ReplayFailure::new(
11178                        "continue_as_new_sequence_missing",
11179                        None,
11180                        Some("recorded transition sequence".to_string()),
11181                        Some("missing sequence".to_string()),
11182                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11183                    ))
11184                })
11185            })
11186            .transpose()?;
11187        let mut message_stream_cursors = HashMap::new();
11188        for event in &history {
11189            if !matches!(
11190                event.event_type.as_str(),
11191                "SignalReceived" | "SignalApplied"
11192            ) || event.payload.get("signal_name").and_then(Value::as_str)
11193                != Some(MESSAGE_STREAM_SIGNAL)
11194            {
11195                continue;
11196            }
11197            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
11198            if arguments.len() != 1 {
11199                continue;
11200            }
11201            let envelope = arguments[0].clone().into_json()?;
11202            let Some(envelope) = envelope.as_object() else {
11203                continue;
11204            };
11205            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
11206            {
11207                continue;
11208            }
11209            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11210                continue;
11211            };
11212            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11213            else {
11214                continue;
11215            };
11216            let cursor = message_stream_cursors
11217                .entry(stream_name.to_string())
11218                .or_insert(0);
11219            *cursor = (*cursor).max(through_position);
11220        }
11221        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
11222        let cancel_requested = history.iter().any(|event| {
11223            matches!(
11224                event.event_type.as_str(),
11225                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
11226            )
11227        });
11228        let cancellation_clock = cancellation_history
11229            .request
11230            .as_ref()
11231            .and_then(|request| request.context.as_ref())
11232            .map(|_| {
11233                cancellation_replay_clock::ReplayClock::new(
11234                    &history,
11235                    &recorded_commands,
11236                    cancellation_history.delivery_index,
11237                )
11238            })
11239            .or_else(|| {
11240                scope_delivery.as_ref().map(|_| {
11241                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
11242                })
11243            });
11244        Ok(Self {
11245            workflow_command_identity: String::new(),
11246            workflow_stream_command_counter: 0,
11247            workflow_id,
11248            run_id,
11249            task_queue,
11250            payload_codec,
11251            history_events: Arc::new(history),
11252            history_budget: WorkflowHistoryBudget {
11253                event_count,
11254                ..WorkflowHistoryBudget::default()
11255            },
11256            cancel_requested,
11257            cancellation_history,
11258            cancellation_consumed: false,
11259            cancellation_clock,
11260            cancellation_shield_depth: 0,
11261            cancellation_delivery_enabled: false,
11262            cancellation_delivery_intent: None,
11263            cancellation_delivery_command_count: 0,
11264            allow_cancellation_scope_authoring,
11265            cancellation_scope_opening: None,
11266            cancellation_scope_memberships: scopes.memberships,
11267            scope_delivery,
11268            resume_signal,
11269            recorded_commands,
11270            selection_markers,
11271            selection_marker_cursor: 0,
11272            cancelled_selection_members,
11273            recorded_continue_as_new_sequence,
11274            continue_as_new_consumed: false,
11275            command_cursor: 0,
11276            condition_wait_occurrence_counter: 0,
11277            matched_recorded_pending: false,
11278            version_markers: HashMap::new(),
11279            commands: Vec::new(),
11280            local_activity_requests: Vec::new(),
11281            message_stream_messages: HashMap::new(),
11282            message_stream_cursors,
11283            message_stream_waits: HashMap::new(),
11284        })
11285    }
11286}
11287
11288enum MessageStreamDelivery {
11289    Message(MessageStreamMessage),
11290    Cursor {
11291        stream_name: String,
11292        through_position: u64,
11293    },
11294}
11295
11296fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
11297    if arguments.len() != 1 {
11298        return Ok(None);
11299    }
11300    let envelope = arguments
11301        .into_iter()
11302        .next()
11303        .expect("one argument was checked");
11304    let Some(envelope) = envelope.as_object() else {
11305        return Ok(None);
11306    };
11307    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11308        return Ok(None);
11309    };
11310    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
11311        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11312        else {
11313            return Ok(None);
11314        };
11315        return Ok(Some(MessageStreamDelivery::Cursor {
11316            stream_name: stream_name.to_string(),
11317            through_position,
11318        }));
11319    }
11320    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
11321        return Ok(None);
11322    }
11323    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
11324        return Ok(None);
11325    };
11326    let Some(position) = envelope
11327        .get("position")
11328        .and_then(Value::as_u64)
11329        .filter(|value| *value > 0)
11330    else {
11331        return Ok(None);
11332    };
11333    let Some(payload_envelope) = envelope.get("payload_envelope") else {
11334        return Ok(None);
11335    };
11336    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
11337    else {
11338        return Ok(None);
11339    };
11340    let decoded = decode_avro_value(&payload_envelope)?;
11341    let AvroValue::Array(values) = decoded else {
11342        return Ok(None);
11343    };
11344    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
11345        stream_name: stream_name.to_string(),
11346        message_id: message_id.to_string(),
11347        position,
11348        arguments: values,
11349    })))
11350}
11351
11352#[derive(Clone, Debug)]
11353enum RecordedCommand {
11354    CancellationScope {
11355        sequence: u64,
11356        scope_id: String,
11357        parent_scope_id: String,
11358        shield_parent: bool,
11359    },
11360    CancellationGroup {
11361        sequence: u64,
11362        span: u64,
11363        original: Vec<RecordedCommand>,
11364    },
11365    CancellationBoundary {
11366        sequence: u64,
11367        call_kind: CancellationCallKind,
11368        original: Option<Box<RecordedCommand>>,
11369    },
11370    Activity {
11371        sequence: u64,
11372        activity_type: Option<String>,
11373        cancellation_policy: String,
11374        options: Option<RecordedActivityOptions>,
11375        outcome: Option<ActivityOutcome>,
11376        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11377    },
11378    Timer {
11379        sequence: u64,
11380        delay_seconds: u64,
11381        fired: bool,
11382        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11383    },
11384    ChildWorkflow {
11385        sequence: u64,
11386        workflow_type: Option<String>,
11387        policies: RecordedChildPolicies,
11388        outcome: Option<ChildWorkflowOutcome>,
11389        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11390    },
11391    SignalWait {
11392        sequence: u64,
11393        signal_name: String,
11394        value: Option<Vec<AvroValue>>,
11395        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11396    },
11397    ConditionWait {
11398        sequence: u64,
11399        occurrence_id: String,
11400        condition_key: Option<String>,
11401        predicate_identity: String,
11402        timeout_seconds: Option<u64>,
11403        result: Option<ConditionWaitResult>,
11404        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11405    },
11406    SearchAttributes {
11407        sequence: u64,
11408        attributes: Value,
11409        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
11410    },
11411    SideEffect {
11412        sequence: u64,
11413        value: AvroValue,
11414    },
11415    VersionMarker {
11416        sequence: u64,
11417        change_id: String,
11418        version: i32,
11419    },
11420    Memo {
11421        sequence: u64,
11422        entries: AvroValue,
11423    },
11424}
11425
11426#[derive(Clone, Debug, PartialEq, Eq)]
11427struct SelectionMarker {
11428    selection_group_id: String,
11429    selection_group_base_sequence: u64,
11430    selection_group_size: usize,
11431    member_key: SelectionKey,
11432    member_index: usize,
11433    member_base_sequence: u64,
11434    member_size: usize,
11435    operation_kind: String,
11436    operation_identity: String,
11437    outcome: String,
11438    resolution_event_id: String,
11439    resolution_event_type: String,
11440}
11441
11442#[derive(Clone, Debug, PartialEq, Eq)]
11443struct SelectionCancellation {
11444    selection_group_id: String,
11445    member_key: SelectionKey,
11446    member_index: usize,
11447    member_base_sequence: u64,
11448    member_size: usize,
11449    operation_kind: String,
11450    operation_identity: String,
11451}
11452
11453fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
11454    let mut markers: Vec<SelectionMarker> = Vec::new();
11455    for event in events
11456        .iter()
11457        .filter(|event| event.event_type == "SelectionResolved")
11458    {
11459        let payload = &event.payload;
11460        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
11461        let group_size = required_selection_usize(payload, "selection_group_size")?;
11462        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
11463        let member_size = required_selection_usize(payload, "member_size")?;
11464        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
11465        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
11466            invalid_recorded_history(
11467                "selection_marker_invalid",
11468                base_sequence,
11469                "non-empty selection_group_id",
11470                &payload.to_string(),
11471                "selection winner history is missing its durable group identity",
11472            )
11473        })?;
11474        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
11475        if group_id != expected_group_id {
11476            return Err(invalid_recorded_history(
11477                "selection_marker_invalid",
11478                base_sequence,
11479                &expected_group_id,
11480                &group_id,
11481                "selection winner history contains an incompatible group identity",
11482            ));
11483        }
11484        let group_end = base_sequence
11485            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
11486            .unwrap_or(u64::MAX);
11487        let member_end = member_base_sequence
11488            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
11489            .unwrap_or(u64::MAX);
11490        if member_index >= group_size
11491            || member_base_sequence < base_sequence
11492            || member_end > group_end
11493        {
11494            return Err(invalid_recorded_history(
11495                "selection_marker_invalid",
11496                base_sequence,
11497                "winner member within selection group bounds",
11498                &payload.to_string(),
11499                "selection winner history contains an invalid member range",
11500            ));
11501        }
11502        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
11503            invalid_recorded_history(
11504                "selection_marker_invalid",
11505                base_sequence,
11506                "selection operation kind",
11507                &payload.to_string(),
11508                "selection winner history is missing its operation kind",
11509            )
11510        })?;
11511        if !matches!(
11512            operation_kind.as_str(),
11513            "activity" | "child" | "timer" | "signal" | "condition" | "group"
11514        ) {
11515            return Err(invalid_recorded_history(
11516                "selection_marker_invalid",
11517                base_sequence,
11518                "activity, child, timer, signal, condition, or group",
11519                &operation_kind,
11520                "selection winner history contains an unsupported operation kind",
11521            ));
11522        }
11523        let operation_identity =
11524            payload_string(payload, "operation_identity").ok_or_else(|| {
11525                invalid_recorded_history(
11526                    "selection_marker_invalid",
11527                    base_sequence,
11528                    "non-empty operation identity",
11529                    &payload.to_string(),
11530                    "selection winner history is missing its durable operation identity",
11531                )
11532            })?;
11533        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
11534            invalid_recorded_history(
11535                "selection_marker_invalid",
11536                base_sequence,
11537                "completed or failed selection outcome",
11538                &payload.to_string(),
11539                "selection winner history is missing its outcome",
11540            )
11541        })?;
11542        if !matches!(outcome.as_str(), "completed" | "failed") {
11543            return Err(invalid_recorded_history(
11544                "selection_marker_invalid",
11545                base_sequence,
11546                "completed or failed selection outcome",
11547                &outcome,
11548                "selection winner history contains an unsupported outcome",
11549            ));
11550        }
11551        let marker = SelectionMarker {
11552            selection_group_id: group_id,
11553            selection_group_base_sequence: base_sequence,
11554            selection_group_size: group_size,
11555            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
11556            member_index,
11557            member_base_sequence,
11558            member_size,
11559            operation_kind,
11560            operation_identity,
11561            outcome,
11562            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
11563                || {
11564                    invalid_recorded_history(
11565                        "selection_marker_invalid",
11566                        base_sequence,
11567                        "durable resolution_event_id",
11568                        &payload.to_string(),
11569                        "selection winner history is missing its terminal event identity",
11570                    )
11571                },
11572            )?,
11573            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
11574                || {
11575                    invalid_recorded_history(
11576                        "selection_marker_invalid",
11577                        base_sequence,
11578                        "durable resolution_event_type",
11579                        &payload.to_string(),
11580                        "selection winner history is missing its terminal event type",
11581                    )
11582                },
11583            )?,
11584        };
11585        if let Some(existing) = markers
11586            .iter()
11587            .find(|existing| existing.selection_group_id == marker.selection_group_id)
11588        {
11589            if existing != &marker {
11590                return Err(invalid_recorded_history(
11591                    "selection_marker_conflict",
11592                    base_sequence,
11593                    &format!("one winner for {}", marker.selection_group_id),
11594                    &payload.to_string(),
11595                    "selection history records conflicting winners for one durable group",
11596                ));
11597            }
11598            continue;
11599        }
11600        markers.push(marker);
11601    }
11602    Ok(markers)
11603}
11604
11605fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
11606    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
11607    for event in events
11608        .iter()
11609        .filter(|event| event.event_type == "SelectionOperationCancelled")
11610    {
11611        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
11612            invalid_recorded_history(
11613                "selection_cancellation_invalid",
11614                0,
11615                "non-empty selection_group_id",
11616                &event.payload.to_string(),
11617                "selection cancellation history is missing its group identity",
11618            )
11619        })?;
11620        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
11621        let marker = SelectionCancellation {
11622            selection_group_id: group_id,
11623            member_key: selection_key_from_value(
11624                event.payload.get("member_key"),
11625                member_base_sequence,
11626            )?,
11627            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
11628            member_base_sequence,
11629            member_size: required_selection_usize(&event.payload, "member_size")?,
11630            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
11631                invalid_recorded_history(
11632                    "selection_cancellation_invalid",
11633                    member_base_sequence,
11634                    "selection operation kind",
11635                    &event.payload.to_string(),
11636                    "selection cancellation is missing its operation kind",
11637                )
11638            })?,
11639            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
11640                || {
11641                    invalid_recorded_history(
11642                        "selection_cancellation_invalid",
11643                        member_base_sequence,
11644                        "selection operation identity",
11645                        &event.payload.to_string(),
11646                        "selection cancellation is missing its operation identity",
11647                    )
11648                },
11649            )?,
11650        };
11651        if let Some(existing) = cancelled.iter().find(|recorded| {
11652            recorded.selection_group_id == marker.selection_group_id
11653                && recorded.member_base_sequence == marker.member_base_sequence
11654        }) {
11655            if existing != &marker {
11656                return Err(invalid_recorded_history(
11657                    "selection_cancellation_conflict",
11658                    member_base_sequence,
11659                    "one stable SelectionOperationCancelled marker",
11660                    &event.payload.to_string(),
11661                    "selection cancellation history contains conflicting member metadata",
11662                ));
11663            }
11664        } else {
11665            cancelled.push(marker);
11666        }
11667    }
11668    Ok(cancelled)
11669}
11670
11671fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
11672    payload
11673        .get(field)
11674        .and_then(value_as_u64)
11675        .filter(|value| *value > 0)
11676        .ok_or_else(|| {
11677            invalid_recorded_history(
11678                "selection_marker_invalid",
11679                0,
11680                &format!("positive integer {field}"),
11681                &payload.to_string(),
11682                "selection history contains invalid durable identity metadata",
11683            )
11684        })
11685}
11686
11687fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
11688    required_selection_usize_allow_zero(payload, field).and_then(|value| {
11689        if value > 0 {
11690            Ok(value)
11691        } else {
11692            Err(invalid_recorded_history(
11693                "selection_marker_invalid",
11694                0,
11695                &format!("positive integer {field}"),
11696                &payload.to_string(),
11697                "selection history contains invalid durable identity metadata",
11698            ))
11699        }
11700    })
11701}
11702
11703fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
11704    payload
11705        .get(field)
11706        .and_then(value_as_u64)
11707        .and_then(|value| usize::try_from(value).ok())
11708        .ok_or_else(|| {
11709            invalid_recorded_history(
11710                "selection_marker_invalid",
11711                0,
11712                &format!("non-negative integer {field}"),
11713                &payload.to_string(),
11714                "selection history contains invalid durable identity metadata",
11715            )
11716        })
11717}
11718
11719#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11720struct RecordedActivityOptions {
11721    task_queue: RecordedSnapshotValue<Option<String>>,
11722    execution_mode: RecordedSnapshotValue<Option<String>>,
11723    retry_policy: ActivityRetrySnapshot,
11724    worker_session: Option<Value>,
11725}
11726
11727#[derive(Clone, Debug)]
11728struct RecordedChildPolicies {
11729    parent_close_policy: String,
11730    cancellation_policy: String,
11731}
11732
11733fn recorded_activity_cancellation_policy(
11734    events: &[&HistoryEvent],
11735    sequence: u64,
11736) -> Result<String> {
11737    let mut policy: Option<String> = None;
11738    for event in events.iter().filter(|event| {
11739        matches!(
11740            event.event_type.as_str(),
11741            "ActivityScheduled"
11742                | "ActivityStarted"
11743                | "ActivityCompleted"
11744                | "ActivityFailed"
11745                | "ActivityTimedOut"
11746                | "ActivityCancelled"
11747        )
11748    }) {
11749        for source in [Some(&event.payload), event.payload.get("activity")]
11750            .into_iter()
11751            .flatten()
11752        {
11753            let Some(value) = source.get("cancellation_policy") else {
11754                continue;
11755            };
11756            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11757                value.as_str()
11758            else {
11759                return Err(invalid_recorded_history(
11760                    "invalid_activity_cancellation_policy_history",
11761                    sequence,
11762                    "supported Activity cancellation policy",
11763                    &value.to_string(),
11764                    "Activity history contains an invalid cancellation policy",
11765                ));
11766            };
11767            if let Some(previous) = policy.as_deref() {
11768                if previous != incoming {
11769                    return Err(invalid_recorded_history(
11770                        "activity_cancellation_policy_history_conflict",
11771                        sequence,
11772                        previous,
11773                        incoming,
11774                        "Activity cancellation policy changed between history events",
11775                    ));
11776                }
11777            }
11778            policy = Some(incoming.to_string());
11779        }
11780        policy.get_or_insert_with(|| "try_cancel".to_string());
11781    }
11782    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11783}
11784
11785fn recorded_child_policy_value<'a>(
11786    payload: &'a Value,
11787    field: &str,
11788    sequence: u64,
11789) -> Result<Option<&'a str>> {
11790    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11791        return Ok(None);
11792    };
11793    let valid = match (field, value.as_str()) {
11794        (
11795            "parent_close_policy",
11796            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11797        ) => true,
11798        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11799            true
11800        }
11801        _ => false,
11802    };
11803    if !valid {
11804        return Err(invalid_recorded_history(
11805            "invalid_child_workflow_policy_history",
11806            sequence,
11807            "supported child workflow policy",
11808            &value.to_string(),
11809            "child workflow history contains an invalid policy",
11810        ));
11811    }
11812    Ok(value.as_str())
11813}
11814
11815fn recorded_child_policies(
11816    events: &[&HistoryEvent],
11817    scheduled: &HistoryEvent,
11818    sequence: u64,
11819) -> Result<RecordedChildPolicies> {
11820    let parent_close_policy =
11821        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11822            .unwrap_or("abandon")
11823            .to_string();
11824    let cancellation_policy =
11825        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11826            .unwrap_or("abandon")
11827            .to_string();
11828    for event in events {
11829        for (field, expected) in [
11830            ("parent_close_policy", parent_close_policy.as_str()),
11831            ("cancellation_policy", cancellation_policy.as_str()),
11832        ] {
11833            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11834                if actual != expected {
11835                    return Err(invalid_recorded_history(
11836                        "child_workflow_policy_history_conflict",
11837                        sequence,
11838                        expected,
11839                        actual,
11840                        "child workflow policy changed between history events",
11841                    ));
11842                }
11843            }
11844        }
11845    }
11846    Ok(RecordedChildPolicies {
11847        parent_close_policy,
11848        cancellation_policy,
11849    })
11850}
11851
11852fn ensure_child_policies_match(
11853    sequence: u64,
11854    recorded: &RecordedChildPolicies,
11855    current: &ChildWorkflowOptions,
11856) -> Result<()> {
11857    for (field, expected, actual) in [
11858        (
11859            "parent_close_policy",
11860            recorded.parent_close_policy.as_str(),
11861            current.parent_close_policy.as_str(),
11862        ),
11863        (
11864            "cancellation_policy",
11865            recorded.cancellation_policy.as_str(),
11866            current.cancellation_policy.as_str(),
11867        ),
11868    ] {
11869        if expected != actual {
11870            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11871                "child_workflow_policy_changed",
11872                Some(sequence),
11873                Some(expected.to_string()),
11874                Some(actual.to_string()),
11875                format!("child workflow {field} changed during replay"),
11876            )));
11877        }
11878    }
11879    Ok(())
11880}
11881
11882#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11883enum RecordedSnapshotValue<T> {
11884    /// Older history did not persist this field, so it cannot constrain replay.
11885    Unknown,
11886    Known(T),
11887}
11888
11889impl<T: PartialEq> RecordedSnapshotValue<T> {
11890    fn matches_current(&self, current: &Self) -> bool {
11891        match self {
11892            Self::Unknown => true,
11893            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11894        }
11895    }
11896}
11897
11898#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11899struct ActivityRetrySnapshot {
11900    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11901    max_attempts: RecordedSnapshotValue<Option<u64>>,
11902    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11903    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11904    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11905    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11906    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11907    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11908}
11909
11910impl ActivityRetrySnapshot {
11911    fn matches_current(&self, current: &Self) -> bool {
11912        self.snapshot_version
11913            .matches_current(&current.snapshot_version)
11914            && self.max_attempts.matches_current(&current.max_attempts)
11915            && self
11916                .backoff_seconds
11917                .matches_current(&current.backoff_seconds)
11918            && self
11919                .start_to_close_timeout
11920                .matches_current(&current.start_to_close_timeout)
11921            && self
11922                .schedule_to_start_timeout
11923                .matches_current(&current.schedule_to_start_timeout)
11924            && self
11925                .schedule_to_close_timeout
11926                .matches_current(&current.schedule_to_close_timeout)
11927            && self
11928                .heartbeat_timeout
11929                .matches_current(&current.heartbeat_timeout)
11930            && self
11931                .non_retryable_error_types
11932                .matches_current(&current.non_retryable_error_types)
11933    }
11934}
11935
11936fn recorded_optional_u64(
11937    object: Option<&serde_json::Map<String, Value>>,
11938    field: &str,
11939) -> RecordedSnapshotValue<Option<u64>> {
11940    match object.and_then(|object| object.get(field)) {
11941        None => RecordedSnapshotValue::Unknown,
11942        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11943        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11944    }
11945}
11946
11947fn recorded_optional_string(
11948    object: &serde_json::Map<String, Value>,
11949    field: &str,
11950) -> RecordedSnapshotValue<Option<String>> {
11951    match object.get(field) {
11952        None => RecordedSnapshotValue::Unknown,
11953        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11954        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11955    }
11956}
11957
11958fn recorded_activity_execution_mode(
11959    events: &[&HistoryEvent],
11960    sequence: u64,
11961) -> Result<RecordedSnapshotValue<Option<String>>> {
11962    let mut recorded = RecordedSnapshotValue::Unknown;
11963    for event in events {
11964        for object in [
11965            event.payload.as_object(),
11966            event.payload.get("activity").and_then(Value::as_object),
11967        ]
11968        .into_iter()
11969        .flatten()
11970        {
11971            let mode = match object.get("execution_mode") {
11972                None => None,
11973                Some(Value::Null) => Some(None),
11974                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11975                Some(_) => {
11976                    return Err(invalid_recorded_history(
11977                        "activity_execution_mode_invalid",
11978                        sequence,
11979                        "null or a non-empty execution mode",
11980                        "invalid execution_mode",
11981                        "activity history contains an invalid execution mode",
11982                    ))
11983                }
11984            };
11985            let legacy_mode = match object.get("local_activity") {
11986                None => None,
11987                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11988                Some(_) => {
11989                    return Err(invalid_recorded_history(
11990                        "activity_execution_mode_invalid",
11991                        sequence,
11992                        "boolean local_activity",
11993                        "invalid local_activity",
11994                        "activity history contains an invalid local-activity marker",
11995                    ))
11996                }
11997            };
11998            for mode in [mode, legacy_mode].into_iter().flatten() {
11999                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12000                {
12001                    return Err(invalid_recorded_history(
12002                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12003                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12004                    ));
12005                }
12006                recorded = RecordedSnapshotValue::Known(mode);
12007            }
12008        }
12009    }
12010    Ok(recorded)
12011}
12012
12013fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12014    let policy = policy.and_then(Value::as_object);
12015    let backoff_seconds = policy
12016        .and_then(|policy| policy.get("backoff_seconds"))
12017        .and_then(Value::as_array)
12018        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12019        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12020    let mut non_retryable_error_types = Vec::new();
12021    for error_type in policy
12022        .and_then(|policy| policy.get("non_retryable_error_types"))
12023        .and_then(Value::as_array)
12024        .into_iter()
12025        .flatten()
12026        .filter_map(Value::as_str)
12027        .map(str::trim)
12028        .filter(|error_type| !error_type.is_empty())
12029    {
12030        if !non_retryable_error_types
12031            .iter()
12032            .any(|recorded| recorded == error_type)
12033        {
12034            non_retryable_error_types.push(error_type.to_string());
12035        }
12036    }
12037
12038    ActivityRetrySnapshot {
12039        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12040        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12041        backoff_seconds,
12042        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12043        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12044        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12045        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12046        non_retryable_error_types: if policy
12047            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12048        {
12049            RecordedSnapshotValue::Known(non_retryable_error_types)
12050        } else {
12051            RecordedSnapshotValue::Unknown
12052        },
12053    }
12054}
12055
12056fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12057    let policy = options.retry_policy.as_ref();
12058    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12059        Some(Value::Null) => None,
12060        Some(value) => value_as_u64(value),
12061        None => Some(1),
12062    };
12063    let backoff_seconds = policy
12064        .and_then(|policy| policy.get("backoff_seconds"))
12065        .and_then(Value::as_array)
12066        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12067        .unwrap_or_default();
12068    let non_retryable_error_types = policy
12069        .and_then(|policy| policy.get("non_retryable_error_types"))
12070        .and_then(Value::as_array)
12071        .into_iter()
12072        .flatten()
12073        .filter_map(Value::as_str)
12074        .map(str::to_string)
12075        .collect();
12076
12077    ActivityRetrySnapshot {
12078        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12079        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12080        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12081        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12082        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12083        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12084        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12085        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12086    }
12087}
12088
12089fn activity_options_description(options: &RecordedActivityOptions) -> String {
12090    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12091}
12092
12093impl RecordedCommand {
12094    fn sequence(&self) -> u64 {
12095        match self {
12096            Self::CancellationGroup { sequence, .. }
12097            | Self::CancellationScope { sequence, .. }
12098            | Self::CancellationBoundary { sequence, .. }
12099            | Self::Activity { sequence, .. }
12100            | Self::Timer { sequence, .. }
12101            | Self::ChildWorkflow { sequence, .. }
12102            | Self::SignalWait { sequence, .. }
12103            | Self::ConditionWait { sequence, .. }
12104            | Self::SearchAttributes { sequence, .. }
12105            | Self::SideEffect { sequence, .. }
12106            | Self::VersionMarker { sequence, .. }
12107            | Self::Memo { sequence, .. } => *sequence,
12108        }
12109    }
12110
12111    fn shape(&self) -> &'static str {
12112        match self {
12113            Self::CancellationScope { .. } => "cancellation scope",
12114            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12115                "cooperative cancellation"
12116            }
12117            Self::Activity { .. } => "activity",
12118            Self::Timer { .. } => "timer",
12119            Self::ChildWorkflow { .. } => "child workflow",
12120            Self::SignalWait { .. } => "signal wait",
12121            Self::ConditionWait { .. } => "condition wait",
12122            Self::SearchAttributes { .. } => "search-attribute update",
12123            Self::SideEffect { .. } => "side effect",
12124            Self::VersionMarker { .. } => "version marker",
12125            Self::Memo { .. } => "memo upsert",
12126        }
12127    }
12128}
12129
12130fn ensure_version_supported(
12131    change_id: &str,
12132    version: i32,
12133    min_supported: i32,
12134    max_supported: i32,
12135    sequence: u64,
12136) -> Result<()> {
12137    if (min_supported..=max_supported).contains(&version) {
12138        return Ok(());
12139    }
12140    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12141        "version_marker_incompatible_range",
12142        (sequence != 0).then_some(sequence),
12143        Some(format!("{min_supported}..={max_supported}")),
12144        Some(format!("{change_id}:{version}")),
12145        "recorded workflow version is outside the range supported by current code",
12146    )))
12147}
12148
12149#[derive(Clone, Debug)]
12150struct ResumeSignal {
12151    signal_name: String,
12152    arguments: Vec<AvroValue>,
12153}
12154
12155const MAX_PARALLEL_OPERATIONS: usize = 1000;
12156
12157fn parallel_group_prefix(kind: &str) -> &'static str {
12158    match kind {
12159        "activity" => "parallel-activities",
12160        "child" => "parallel-children",
12161        "timer" => "parallel-timers",
12162        _ => "parallel-calls",
12163    }
12164}
12165
12166fn parallel_group_entry(
12167    base_sequence: u64,
12168    size: usize,
12169    index: usize,
12170    kind: &str,
12171) -> ParallelGroupMetadata {
12172    ParallelGroupMetadata {
12173        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12174        parallel_group_kind: kind.to_string(),
12175        parallel_group_base_sequence: base_sequence,
12176        parallel_group_size: size,
12177        parallel_group_index: index,
12178        parallel_group_mode: None,
12179        selection_member_key: None,
12180        selection_member_index: None,
12181        selection_member_base_sequence: None,
12182        selection_member_size: None,
12183        selection_member_kind: None,
12184    }
12185}
12186
12187struct SelectionMemberMetadata {
12188    key: SelectionKey,
12189    index: usize,
12190    base_sequence: u64,
12191    size: usize,
12192    kind: String,
12193}
12194
12195fn selection_group_entry(
12196    base_sequence: u64,
12197    size: usize,
12198    index: usize,
12199    kind: &str,
12200    member: &SelectionMemberMetadata,
12201) -> ParallelGroupMetadata {
12202    ParallelGroupMetadata {
12203        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
12204        parallel_group_kind: kind.to_string(),
12205        parallel_group_base_sequence: base_sequence,
12206        parallel_group_size: size,
12207        parallel_group_index: index,
12208        parallel_group_mode: Some("select".to_string()),
12209        selection_member_key: Some(member.key.clone()),
12210        selection_member_index: Some(member.index),
12211        selection_member_base_sequence: Some(member.base_sequence),
12212        selection_member_size: Some(member.size),
12213        selection_member_kind: Some(member.kind.clone()),
12214    }
12215}
12216
12217fn apply_parallel_group_path(
12218    command: &mut serde_json::Map<String, Value>,
12219    path: &[ParallelGroupMetadata],
12220) {
12221    let Some(inner) = path.last() else {
12222        return;
12223    };
12224    command.insert(
12225        "parallel_group_id".to_string(),
12226        json!(inner.parallel_group_id),
12227    );
12228    command.insert(
12229        "parallel_group_kind".to_string(),
12230        json!(inner.parallel_group_kind),
12231    );
12232    command.insert(
12233        "parallel_group_base_sequence".to_string(),
12234        json!(inner.parallel_group_base_sequence),
12235    );
12236    command.insert(
12237        "parallel_group_size".to_string(),
12238        json!(inner.parallel_group_size),
12239    );
12240    command.insert(
12241        "parallel_group_index".to_string(),
12242        json!(inner.parallel_group_index),
12243    );
12244    if let Some(mode) = &inner.parallel_group_mode {
12245        command.insert("parallel_group_mode".to_string(), json!(mode));
12246    }
12247    if let Some(key) = &inner.selection_member_key {
12248        command.insert("selection_member_key".to_string(), json!(key));
12249    }
12250    if let Some(index) = inner.selection_member_index {
12251        command.insert("selection_member_index".to_string(), json!(index));
12252    }
12253    if let Some(base_sequence) = inner.selection_member_base_sequence {
12254        command.insert(
12255            "selection_member_base_sequence".to_string(),
12256            json!(base_sequence),
12257        );
12258    }
12259    if let Some(size) = inner.selection_member_size {
12260        command.insert("selection_member_size".to_string(), json!(size));
12261    }
12262    if let Some(kind) = &inner.selection_member_kind {
12263        command.insert("selection_member_kind".to_string(), json!(kind));
12264    }
12265    command.insert("parallel_group_path".to_string(), json!(path));
12266}
12267
12268fn ensure_parallel_path_matches(
12269    sequence: u64,
12270    recorded: Option<&[ParallelGroupMetadata]>,
12271    expected: &[ParallelGroupMetadata],
12272) -> Result<()> {
12273    match (recorded, expected.is_empty()) {
12274        (None, true) => Ok(()),
12275        (Some(recorded), false) if recorded == expected => Ok(()),
12276        (None, false) => Err(invalid_recorded_history(
12277            "parallel_group_metadata_missing",
12278            sequence,
12279            &serde_json::to_string(expected).unwrap_or_default(),
12280            "<missing>",
12281            "recorded parallel member is missing its durable group path",
12282        )),
12283        (Some(recorded), true) => Err(invalid_recorded_history(
12284            "parallel_group_shape_mismatch",
12285            sequence,
12286            "sequential command",
12287            &serde_json::to_string(recorded).unwrap_or_default(),
12288            "recorded command belonged to a parallel group but current code schedules it sequentially",
12289        )),
12290        (Some(recorded), false) => Err(invalid_recorded_history(
12291            "parallel_group_shape_mismatch",
12292            sequence,
12293            &serde_json::to_string(recorded).unwrap_or_default(),
12294            &serde_json::to_string(expected).unwrap_or_default(),
12295            "recorded parallel-group identity or path changed during replay",
12296        )),
12297    }
12298}
12299
12300#[derive(Clone, Debug)]
12301enum ParallelShape {
12302    Leaf,
12303    Group(Vec<ParallelShape>),
12304}
12305
12306struct ParallelDescriptor {
12307    operation: ParallelOperation,
12308    offset: usize,
12309    member_path: Vec<usize>,
12310    group_path: Vec<ParallelGroupMetadata>,
12311}
12312
12313fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
12314    operations
12315        .iter()
12316        .map(|operation| match operation {
12317            ParallelOperation::Group(children) => parallel_leaf_count(children),
12318            _ => 1,
12319        })
12320        .sum()
12321}
12322
12323fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
12324    match operation {
12325        ParallelOperation::Activity { .. } => Some("activity"),
12326        ParallelOperation::ChildWorkflow { .. } => Some("child"),
12327        ParallelOperation::Timer(_) => Some("timer"),
12328        ParallelOperation::Signal(_) => Some("signal"),
12329        ParallelOperation::Condition { .. } => Some("condition"),
12330        ParallelOperation::Group(children) => parallel_group_kind(children),
12331    }
12332}
12333
12334fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
12335    let mut kind = None;
12336    for operation in operations {
12337        let Some(operation_kind) = parallel_operation_kind(operation) else {
12338            continue;
12339        };
12340        match kind {
12341            None => kind = Some(operation_kind),
12342            Some(current) if current == operation_kind => {}
12343            Some(_) => return Some("mixed"),
12344        }
12345    }
12346    kind
12347}
12348
12349fn validate_parallel_operations(
12350    operations: &[ParallelOperation],
12351    member_path: &mut Vec<usize>,
12352    root: bool,
12353) -> Result<()> {
12354    let leaves = parallel_leaf_count(operations);
12355    if leaves > MAX_PARALLEL_OPERATIONS {
12356        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12357            reason: "fan_out_limit_exceeded",
12358            member_path: member_path.clone(),
12359            message: format!(
12360                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12361            ),
12362        }));
12363    }
12364    if !root && operations.is_empty() {
12365        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12366            reason: "nested_group_empty",
12367            member_path: member_path.clone(),
12368            message: "a nested group must contain at least one durable leaf".to_string(),
12369        }));
12370    }
12371
12372    for (index, operation) in operations.iter().enumerate() {
12373        member_path.push(index);
12374        match operation {
12375            ParallelOperation::Activity {
12376                options, arguments, ..
12377            } => {
12378                options
12379                    .validate()
12380                    .map_err(|error| Error::InvalidActivityOptions(error))?;
12381                if let Err(error) = arguments {
12382                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12383                        reason: "arguments_invalid",
12384                        member_path: member_path.clone(),
12385                        message: error.to_string(),
12386                    }));
12387                }
12388            }
12389            ParallelOperation::ChildWorkflow {
12390                options, arguments, ..
12391            } => {
12392                validate_parallel_child_options(options)?;
12393                if let Err(error) = arguments {
12394                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12395                        reason: "arguments_invalid",
12396                        member_path: member_path.clone(),
12397                        message: error.to_string(),
12398                    }));
12399                }
12400            }
12401            ParallelOperation::Timer(duration)
12402                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
12403            {
12404                return Err(Error::TimerDurationOverflow);
12405            }
12406            ParallelOperation::Timer(_) => {}
12407            ParallelOperation::Signal(signal_name) => {
12408                validate_user_signal_name(signal_name)?;
12409                if signal_name.trim().is_empty() {
12410                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12411                        reason: "signal_name_empty",
12412                        member_path: member_path.clone(),
12413                        message: "signal wait name must not be empty".to_string(),
12414                    }));
12415                }
12416            }
12417            ParallelOperation::Condition { options, .. } => {
12418                options.validate()?;
12419            }
12420            ParallelOperation::Group(children) => {
12421                validate_parallel_operations(children, member_path, false)?;
12422            }
12423        }
12424        member_path.pop();
12425    }
12426    Ok(())
12427}
12428
12429fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
12430    if options.task_queue.trim().is_empty() {
12431        return Err(Error::InvalidChildWorkflowOptions(
12432            "task_queue must not be empty".to_string(),
12433        ));
12434    }
12435    for (name, value) in [
12436        (
12437            "execution_timeout_seconds",
12438            options.execution_timeout_seconds,
12439        ),
12440        ("run_timeout_seconds", options.run_timeout_seconds),
12441    ] {
12442        if value == Some(0) {
12443            return Err(Error::InvalidChildWorkflowOptions(format!(
12444                "{name} must be at least 1"
12445            )));
12446        }
12447    }
12448    if options
12449        .retry_policy
12450        .as_ref()
12451        .is_some_and(|policy| policy.max_attempts == Some(0))
12452    {
12453        return Err(Error::InvalidChildWorkflowOptions(
12454            "retry_policy.max_attempts must be at least 1".to_string(),
12455        ));
12456    }
12457    Ok(())
12458}
12459
12460fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
12461    ParallelShape::Group(
12462        operations
12463            .iter()
12464            .map(|operation| match operation {
12465                ParallelOperation::Group(children) => parallel_shape(children),
12466                _ => ParallelShape::Leaf,
12467            })
12468            .collect(),
12469    )
12470}
12471
12472fn parallel_descriptors(
12473    operations: Vec<ParallelOperation>,
12474    base_sequence: u64,
12475) -> Result<Vec<ParallelDescriptor>> {
12476    let size = parallel_leaf_count(&operations);
12477    let kind = parallel_group_kind(&operations).unwrap_or("activity");
12478    let mut descriptors = Vec::with_capacity(size);
12479    let mut cursor = 0;
12480
12481    for (index, operation) in operations.into_iter().enumerate() {
12482        match operation {
12483            ParallelOperation::Group(children) => {
12484                let child_base = base_sequence
12485                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12486                    .ok_or(Error::TimerDurationOverflow)?;
12487                for mut descriptor in parallel_descriptors(children, child_base)? {
12488                    let outer_index = cursor + descriptor.offset;
12489                    descriptor.group_path.insert(
12490                        0,
12491                        parallel_group_entry(base_sequence, size, outer_index, kind),
12492                    );
12493                    descriptor.member_path.insert(0, index);
12494                    descriptor.offset = outer_index;
12495                    descriptors.push(descriptor);
12496                }
12497                cursor = descriptors.len();
12498            }
12499            operation => {
12500                descriptors.push(ParallelDescriptor {
12501                    operation,
12502                    offset: cursor,
12503                    member_path: vec![index],
12504                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
12505                });
12506                cursor += 1;
12507            }
12508        }
12509    }
12510    Ok(descriptors)
12511}
12512
12513enum ParallelLeafCall {
12514    Activity(ActivityCall),
12515    ChildWorkflow(ChildWorkflowCall),
12516    Timer(TimerCall),
12517    Signal(SignalCall),
12518    Condition(ConditionWaitCall),
12519}
12520
12521fn parallel_leaf_call(
12522    ctx: &WorkflowContext,
12523    operation: ParallelOperation,
12524    parallel_group_path: Vec<ParallelGroupMetadata>,
12525) -> ParallelLeafCall {
12526    match operation {
12527        ParallelOperation::Activity {
12528            activity_type,
12529            options,
12530            arguments,
12531        } => ParallelLeafCall::Activity(ActivityCall {
12532            ctx: ctx.clone(),
12533            activity_type,
12534            options,
12535            worker_session: None,
12536            args: Some(arguments),
12537            scheduled: false,
12538            local: false,
12539            local_result: None,
12540            parallel_group_path,
12541        }),
12542        ParallelOperation::ChildWorkflow {
12543            workflow_type,
12544            options,
12545            arguments,
12546        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
12547            ctx: ctx.clone(),
12548            workflow_type,
12549            options,
12550            args: Some(arguments),
12551            scheduled: false,
12552            matched_pending: false,
12553            parallel_group_path,
12554        }),
12555        ParallelOperation::Timer(duration) => {
12556            let delay_seconds = duration
12557                .as_secs()
12558                .checked_add(u64::from(duration.subsec_nanos() > 0));
12559            ParallelLeafCall::Timer(TimerCall {
12560                ctx: ctx.clone(),
12561                delay_seconds,
12562                scheduled: false,
12563                matched_pending: false,
12564                parallel_group_path,
12565            })
12566        }
12567        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
12568            ctx: ctx.clone(),
12569            signal_name,
12570            runtime_reserved_allowed: false,
12571            opened_wait: false,
12572            matched_pending: false,
12573            parallel_group_path,
12574        }),
12575        ParallelOperation::Condition { options, predicate } => {
12576            ParallelLeafCall::Condition(ConditionWaitCall {
12577                ctx: ctx.clone(),
12578                options,
12579                predicate,
12580                occurrence_id: None,
12581                opened_wait: false,
12582                parallel_group_path,
12583            })
12584        }
12585        ParallelOperation::Group(_) => {
12586            unreachable!("parallel descriptors contain only durable leaves")
12587        }
12588    }
12589}
12590
12591impl ParallelLeafCall {
12592    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
12593        match self {
12594            Self::Activity(call) => Pin::new(call)
12595                .poll_avro_value(cx)
12596                .map_ok(ParallelAvroResult::Activity),
12597            Self::ChildWorkflow(call) => Pin::new(call)
12598                .poll_avro_value(cx)
12599                .map_ok(ParallelAvroResult::ChildWorkflow),
12600            Self::Timer(call) => Pin::new(call)
12601                .poll(cx)
12602                .map_ok(|()| ParallelAvroResult::Timer),
12603            Self::Signal(call) => Pin::new(call)
12604                .poll_avro_value(cx)
12605                .map_ok(ParallelAvroResult::Signal),
12606            Self::Condition(call) => Pin::new(call)
12607                .poll(cx)
12608                .map_ok(ParallelAvroResult::Condition),
12609        }
12610    }
12611}
12612
12613struct ParallelLeaf {
12614    call: ParallelLeafCall,
12615    sequence: u64,
12616    member_path: Vec<usize>,
12617    group_path: Vec<ParallelGroupMetadata>,
12618    result: Option<ParallelAvroResult>,
12619}
12620
12621/// Future returned by [`WorkflowContext::parallel`].
12622pub struct ParallelCall {
12623    ctx: WorkflowContext,
12624    operations: Option<Vec<ParallelOperation>>,
12625    shape: Option<ParallelShape>,
12626    leaves: Vec<ParallelLeaf>,
12627    pending_scope_delivery: bool,
12628    worker_session: Option<WorkerSessionOptions>,
12629}
12630
12631impl ParallelCall {
12632    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
12633        Self {
12634            ctx,
12635            operations: Some(operations),
12636            shape: None,
12637            leaves: Vec::new(),
12638            pending_scope_delivery: false,
12639            worker_session: None,
12640        }
12641    }
12642
12643    fn initialize(&mut self) -> Result<()> {
12644        if let Some(session) = &self.worker_session {
12645            session.to_wire()?;
12646        }
12647        let operations = self.operations.take().unwrap_or_default();
12648        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
12649        self.shape = Some(parallel_shape(&operations));
12650        if operations.is_empty() {
12651            return Ok(());
12652        }
12653
12654        let base_sequence = {
12655            let state = self
12656                .ctx
12657                .state
12658                .lock()
12659                .map_err(|_| Error::WorkflowStatePoisoned)?;
12660            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12661                recorded.sequence()
12662            } else {
12663                let last = state
12664                    .recorded_commands
12665                    .last()
12666                    .map(RecordedCommand::sequence)
12667                    .unwrap_or(0);
12668                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12669                    .and_then(|sequence| sequence.checked_add(1))
12670                    .ok_or_else(|| {
12671                        Error::InvalidParallelGroup(ParallelGroupError {
12672                            reason: "sequence_overflow",
12673                            member_path: Vec::new(),
12674                            message: "parallel group sequence identity overflowed u64".to_string(),
12675                        })
12676                    })?
12677            }
12678        };
12679
12680        let descriptors = parallel_descriptors(operations, base_sequence)?;
12681        {
12682            let mut state = self
12683                .ctx
12684                .state
12685                .lock()
12686                .map_err(|_| Error::WorkflowStatePoisoned)?;
12687            let cursor = state.command_cursor;
12688            self.ctx.validate_scope_membership(&mut state, cursor)?;
12689            if state.prepare_parallel_scope_cancellation(&descriptors)? {
12690                self.pending_scope_delivery = true;
12691                return Ok(());
12692            }
12693            state.expand_cancellation_group(&descriptors)?;
12694            state.prepare_group_cancellation(&descriptors)?;
12695        }
12696        self.leaves = descriptors
12697            .into_iter()
12698            .map(|descriptor| {
12699                let mut call = parallel_leaf_call(
12700                    &self.ctx,
12701                    descriptor.operation,
12702                    descriptor.group_path.clone(),
12703                );
12704                if let (Some(session), ParallelLeafCall::Activity(activity)) =
12705                    (&self.worker_session, &mut call)
12706                {
12707                    activity.worker_session = Some(session.clone());
12708                }
12709                ParallelLeaf {
12710                    call,
12711                    sequence: base_sequence + descriptor.offset as u64,
12712                    member_path: descriptor.member_path,
12713                    group_path: descriptor.group_path,
12714                    result: None,
12715                }
12716            })
12717            .collect();
12718        Ok(())
12719    }
12720
12721    fn poll_avro_value(
12722        mut self: Pin<&mut Self>,
12723        cx: &mut TaskContext<'_>,
12724    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
12725        if self.operations.is_some() {
12726            if let Err(error) = self.initialize() {
12727                return Poll::Ready(Err(error));
12728            }
12729        }
12730        if self.pending_scope_delivery {
12731            return Poll::Pending;
12732        }
12733        if self.leaves.is_empty() {
12734            return Poll::Ready(Ok(Vec::new()));
12735        }
12736
12737        let mut failures = Vec::new();
12738        let mut pending = false;
12739        for (index, leaf) in self.leaves.iter_mut().enumerate() {
12740            if leaf.result.is_some() {
12741                continue;
12742            }
12743            match leaf.call.poll_avro_value(cx) {
12744                Poll::Ready(Ok(result)) => leaf.result = Some(result),
12745                Poll::Ready(Err(error)) => failures.push((index, error)),
12746                Poll::Pending => pending = true,
12747            }
12748        }
12749
12750        if !failures.is_empty() {
12751            if let Some(position) = failures
12752                .iter()
12753                .position(|(_, error)| workflow_task_integrity_error(error))
12754            {
12755                return Poll::Ready(Err(failures.remove(position).1));
12756            }
12757            if self
12758                .ctx
12759                .state
12760                .lock()
12761                .map_err(|_| Error::WorkflowStatePoisoned)?
12762                .cancellation_delivery_intent
12763                .is_some()
12764            {
12765                return Poll::Pending;
12766            }
12767            if let Some(position) = failures
12768                .iter()
12769                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12770            {
12771                return Poll::Ready(Err(failures.remove(position).1));
12772            }
12773            failures.sort_by_key(|(index, _)| *index);
12774            let (failed_index, cause) = failures.remove(0);
12775            let failed = &self.leaves[failed_index];
12776            let completed = self
12777                .leaves
12778                .iter()
12779                .filter_map(|leaf| {
12780                    leaf.result
12781                        .clone()
12782                        .and_then(|result| result.into_json_result().ok())
12783                        .map(|result| ParallelCompletion {
12784                            member_path: leaf.member_path.clone(),
12785                            result,
12786                        })
12787                })
12788                .collect();
12789            let group_id = failed
12790                .group_path
12791                .first()
12792                .map(|entry| entry.parallel_group_id.clone())
12793                .unwrap_or_default();
12794            let sequences = self
12795                .leaves
12796                .iter()
12797                .map(|leaf| leaf.sequence)
12798                .collect::<Vec<_>>();
12799            self.ctx
12800                .state
12801                .lock()
12802                .map_err(|_| Error::WorkflowStatePoisoned)?
12803                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12804            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12805                group_id,
12806                member_path: failed.member_path.clone(),
12807                group_path: failed.group_path.clone(),
12808                completed,
12809                cause: Box::new(cause),
12810            })));
12811        }
12812        if pending
12813            || self
12814                .ctx
12815                .state
12816                .lock()
12817                .map_err(|_| Error::WorkflowStatePoisoned)?
12818                .cancellation_delivery_intent
12819                .is_some()
12820        {
12821            return Poll::Pending;
12822        }
12823
12824        let mut flat_results = self
12825            .leaves
12826            .iter_mut()
12827            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12828            .collect::<Vec<_>>()
12829            .into_iter();
12830        let results = parallel_results_for_shape(
12831            self.shape.as_ref().expect("initialized parallel shape"),
12832            &mut flat_results,
12833        );
12834        let sequences = self
12835            .leaves
12836            .iter()
12837            .map(|leaf| leaf.sequence)
12838            .collect::<Vec<_>>();
12839        self.ctx
12840            .state
12841            .lock()
12842            .map_err(|_| Error::WorkflowStatePoisoned)?
12843            .advance_cancellation_sequences(&sequences, None);
12844        Poll::Ready(Ok(match results {
12845            ParallelAvroResult::Group(results) => results,
12846            ParallelAvroResult::Activity(_)
12847            | ParallelAvroResult::ChildWorkflow(_)
12848            | ParallelAvroResult::Timer
12849            | ParallelAvroResult::Signal(_)
12850            | ParallelAvroResult::Condition(_) => {
12851                unreachable!("root parallel shape is a group")
12852            }
12853        }))
12854    }
12855}
12856
12857fn parallel_results_for_shape(
12858    shape: &ParallelShape,
12859    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12860) -> ParallelAvroResult {
12861    match shape {
12862        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12863        ParallelShape::Group(children) => ParallelAvroResult::Group(
12864            children
12865                .iter()
12866                .map(|child| parallel_results_for_shape(child, flat_results))
12867                .collect(),
12868        ),
12869    }
12870}
12871
12872impl Future for ParallelCall {
12873    type Output = Result<Vec<ParallelResult>>;
12874
12875    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12876        self.poll_avro_value(cx)
12877            .map_ok(|results| {
12878                results
12879                    .into_iter()
12880                    .map(ParallelAvroResult::into_json_result)
12881                    .collect::<Result<Vec<_>>>()
12882            })
12883            .map_ok(|result| result)
12884            .flatten_result()
12885    }
12886}
12887
12888#[derive(Clone, Debug)]
12889struct SelectionMemberPlan {
12890    key: SelectionKey,
12891    index: usize,
12892    base_sequence: u64,
12893    size: usize,
12894    kind: String,
12895    shape: ParallelShape,
12896    leaf_start: usize,
12897}
12898
12899fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12900    match operation {
12901        ParallelOperation::Activity { .. } => "activity",
12902        ParallelOperation::ChildWorkflow { .. } => "child",
12903        ParallelOperation::Timer(_) => "timer",
12904        ParallelOperation::Signal(_) => "signal",
12905        ParallelOperation::Condition { .. } => "condition",
12906        ParallelOperation::Group(_) => "group",
12907    }
12908}
12909
12910fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12911    match operation {
12912        ParallelOperation::Group(children) => parallel_shape(children),
12913        _ => ParallelShape::Leaf,
12914    }
12915}
12916
12917fn selection_descriptors(
12918    operations: Vec<(SelectionKey, ParallelOperation)>,
12919    base_sequence: u64,
12920) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12921    if operations.is_empty() {
12922        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12923            reason: "selection_empty",
12924            member_path: Vec::new(),
12925            message: "durable selection requires at least one operation".to_string(),
12926        }));
12927    }
12928    let operation_refs = operations
12929        .iter()
12930        .map(|(_, operation)| operation)
12931        .collect::<Vec<_>>();
12932    let total_size = operation_refs
12933        .iter()
12934        .map(|operation| match operation {
12935            ParallelOperation::Group(children) => parallel_leaf_count(children),
12936            _ => 1,
12937        })
12938        .sum::<usize>();
12939    if total_size > MAX_PARALLEL_OPERATIONS {
12940        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12941            reason: "fan_out_limit_exceeded",
12942            member_path: Vec::new(),
12943            message: format!(
12944                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12945            ),
12946        }));
12947    }
12948    let group_kind = {
12949        let mut kind = None;
12950        for operation in &operation_refs {
12951            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12952            match kind {
12953                None => kind = Some(operation_kind),
12954                Some(current) if current == operation_kind => {}
12955                Some(_) => {
12956                    kind = Some("mixed");
12957                    break;
12958                }
12959            }
12960        }
12961        kind.unwrap_or("mixed")
12962    };
12963
12964    let mut descriptors = Vec::with_capacity(total_size);
12965    let mut members = Vec::with_capacity(operations.len());
12966    let mut cursor = 0usize;
12967    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12968    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12969        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12970            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12971                reason: "selection_key_invalid",
12972                member_path: vec![member_index],
12973                message: "selection member keys must be non-empty strings or non-negative integers"
12974                    .to_string(),
12975            }));
12976        }
12977        if seen_keys.contains(&key) {
12978            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12979                reason: "selection_key_duplicate",
12980                member_path: vec![member_index],
12981                message: format!("selection member key {key:?} is duplicated"),
12982            }));
12983        }
12984        seen_keys.push(key.clone());
12985        let member_size = match &operation {
12986            ParallelOperation::Group(children) => parallel_leaf_count(children),
12987            _ => 1,
12988        };
12989        if member_size == 0 {
12990            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12991                reason: "selection_member_empty",
12992                member_path: vec![member_index],
12993                message: "a selection member must contain at least one durable leaf".to_string(),
12994            }));
12995        }
12996        let member_base = base_sequence
12997            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12998            .ok_or(Error::TimerDurationOverflow)?;
12999        let member_kind = selection_operation_kind(&operation).to_string();
13000        let member_shape = selection_operation_shape(&operation);
13001        let leaf_start = descriptors.len();
13002        match operation {
13003            ParallelOperation::Group(children) => {
13004                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13005                for mut descriptor in parallel_descriptors(children, member_base)? {
13006                    let flat_index = cursor + descriptor.offset;
13007                    descriptor.group_path.insert(
13008                        0,
13009                        selection_group_entry(
13010                            base_sequence,
13011                            total_size,
13012                            flat_index,
13013                            group_kind,
13014                            &SelectionMemberMetadata {
13015                                key: key.clone(),
13016                                index: member_index,
13017                                base_sequence: member_base,
13018                                size: member_size,
13019                                kind: member_kind.clone(),
13020                            },
13021                        ),
13022                    );
13023                    descriptor.member_path.insert(0, member_index);
13024                    descriptor.offset = flat_index;
13025                    descriptors.push(descriptor);
13026                }
13027            }
13028            operation => {
13029                validate_parallel_operations(
13030                    std::slice::from_ref(&operation),
13031                    &mut Vec::new(),
13032                    true,
13033                )?;
13034                descriptors.push(ParallelDescriptor {
13035                    operation,
13036                    offset: cursor,
13037                    member_path: vec![member_index],
13038                    group_path: vec![selection_group_entry(
13039                        base_sequence,
13040                        total_size,
13041                        cursor,
13042                        group_kind,
13043                        &SelectionMemberMetadata {
13044                            key: key.clone(),
13045                            index: member_index,
13046                            base_sequence: member_base,
13047                            size: member_size,
13048                            kind: member_kind.clone(),
13049                        },
13050                    )],
13051                });
13052            }
13053        }
13054        members.push(SelectionMemberPlan {
13055            key,
13056            index: member_index,
13057            base_sequence: member_base,
13058            size: member_size,
13059            kind: member_kind,
13060            shape: member_shape,
13061            leaf_start,
13062        });
13063        cursor += member_size;
13064    }
13065    Ok((descriptors, members))
13066}
13067
13068struct SelectionLeaf {
13069    call: ParallelLeafCall,
13070    outcome: Option<Result<ParallelAvroResult>>,
13071}
13072
13073/// Stable reference to one member of a durable selection group.
13074#[derive(Clone)]
13075pub struct DurableOperationHandle {
13076    ctx: WorkflowContext,
13077    pub key: SelectionKey,
13078    pub index: usize,
13079    pub kind: String,
13080    pub identity: String,
13081    pub base_sequence: u64,
13082    pub size: usize,
13083    pub selection_group_id: String,
13084    shape: ParallelShape,
13085}
13086
13087impl std::fmt::Debug for DurableOperationHandle {
13088    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13089        formatter
13090            .debug_struct("DurableOperationHandle")
13091            .field("key", &self.key)
13092            .field("index", &self.index)
13093            .field("kind", &self.kind)
13094            .field("identity", &self.identity)
13095            .field("base_sequence", &self.base_sequence)
13096            .field("size", &self.size)
13097            .field("selection_group_id", &self.selection_group_id)
13098            .finish()
13099    }
13100}
13101
13102impl DurableOperationHandle {
13103    /// Await this member after another member has already won the selection.
13104    pub fn await_result(&self) -> DurableOperationAwaitCall {
13105        DurableOperationAwaitCall {
13106            handle: self.clone(),
13107        }
13108    }
13109
13110    /// Request cancellation without affecting siblings. The future resolves
13111    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13112    /// beat a concurrently committed terminal result.
13113    pub fn cancel(&self) -> CancelDurableOperationCall {
13114        CancelDurableOperationCall {
13115            handle: self.clone(),
13116            emitted: false,
13117        }
13118    }
13119}
13120
13121/// The one winner committed for a durable selection group.
13122#[derive(Debug)]
13123pub struct SelectionResult {
13124    pub key: SelectionKey,
13125    pub index: usize,
13126    pub kind: String,
13127    pub identity: String,
13128    pub value: Option<ParallelResult>,
13129    pub failure: Option<Error>,
13130    pub winner: DurableOperationHandle,
13131    pub handles: Vec<DurableOperationHandle>,
13132}
13133
13134impl SelectionResult {
13135    pub fn succeeded(&self) -> bool {
13136        self.failure.is_none()
13137    }
13138
13139    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13140        self.handles.iter().find(|handle| &handle.key == key)
13141    }
13142
13143    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13144        self.handles
13145            .iter()
13146            .filter(|handle| handle.index != self.index)
13147            .collect()
13148    }
13149
13150    pub fn into_result(self) -> Result<ParallelResult> {
13151        match (self.value, self.failure) {
13152            (Some(value), None) => Ok(value),
13153            (_, Some(error)) => Err(error),
13154            _ => Err(Error::WorkerLoop(
13155                "selection result contained neither a value nor a failure".to_string(),
13156            )),
13157        }
13158    }
13159}
13160
13161/// Future returned by [`WorkflowContext::select`].
13162pub struct SelectCall {
13163    ctx: WorkflowContext,
13164    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13165    members: Vec<SelectionMemberPlan>,
13166    leaves: Vec<SelectionLeaf>,
13167    group_id: Option<String>,
13168}
13169
13170impl SelectCall {
13171    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13172        Self {
13173            ctx,
13174            operations: Some(operations),
13175            members: Vec::new(),
13176            leaves: Vec::new(),
13177            group_id: None,
13178        }
13179    }
13180
13181    fn initialize(&mut self) -> Result<()> {
13182        let operations = self.operations.take().unwrap_or_default();
13183        let base_sequence = {
13184            let state = self
13185                .ctx
13186                .state
13187                .lock()
13188                .map_err(|_| Error::WorkflowStatePoisoned)?;
13189            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
13190                state.recorded_commands.get(state.command_cursor)
13191            {
13192                *sequence
13193            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
13194            {
13195                marker.selection_group_base_sequence
13196            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13197                recorded.sequence()
13198            } else {
13199                let last = state
13200                    .recorded_commands
13201                    .last()
13202                    .map(RecordedCommand::sequence)
13203                    .unwrap_or(0);
13204                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13205                    .and_then(|sequence| sequence.checked_add(1))
13206                    .ok_or(Error::TimerDurationOverflow)?
13207            }
13208        };
13209        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
13210        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
13211        {
13212            let mut state = self
13213                .ctx
13214                .state
13215                .lock()
13216                .map_err(|_| Error::WorkflowStatePoisoned)?;
13217            state.expand_cancellation_group(&descriptors)?;
13218            state.prepare_group_cancellation(&descriptors)?;
13219        }
13220        self.leaves = descriptors
13221            .into_iter()
13222            .map(|descriptor| SelectionLeaf {
13223                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
13224                outcome: None,
13225            })
13226            .collect();
13227        self.members = members;
13228        self.group_id = Some(group_id);
13229        Ok(())
13230    }
13231}
13232
13233impl Future for SelectCall {
13234    type Output = Result<SelectionResult>;
13235
13236    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13237        if self.operations.is_some() {
13238            if let Err(error) = self.initialize() {
13239                return Poll::Ready(Err(error));
13240            }
13241        }
13242
13243        for leaf in &mut self.leaves {
13244            if leaf.outcome.is_some() {
13245                continue;
13246            }
13247            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
13248                if outcome
13249                    .as_ref()
13250                    .err()
13251                    .is_some_and(workflow_task_integrity_error)
13252                {
13253                    return Poll::Ready(outcome.map(|_| unreachable!()));
13254                }
13255                leaf.outcome = Some(outcome);
13256            }
13257        }
13258
13259        if self
13260            .ctx
13261            .state
13262            .lock()
13263            .map_err(|_| Error::WorkflowStatePoisoned)?
13264            .cancellation_delivery_intent
13265            .is_some()
13266        {
13267            return Poll::Pending;
13268        }
13269
13270        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
13271            matches!(
13272                leaf.outcome,
13273                Some(Err(Error::CooperativeCancellationRequested(_)))
13274            )
13275        }) {
13276            return Poll::Ready(
13277                leaf.outcome
13278                    .take()
13279                    .expect("matched cancellation")
13280                    .map(|_| unreachable!()),
13281            );
13282        }
13283
13284        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
13285        let selection_member_range = self
13286            .members
13287            .first()
13288            .map(|member| member.base_sequence)
13289            .zip(self.leaves.len().try_into().ok())
13290            .map(|(base_sequence, size): (u64, u64)| {
13291                base_sequence..base_sequence.saturating_add(size)
13292            });
13293        let marker = {
13294            let mut state = match self.ctx.state.lock() {
13295                Ok(state) => state,
13296                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13297            };
13298            let marker = state
13299                .selection_markers
13300                .get(state.selection_marker_cursor)
13301                .cloned();
13302            if marker.is_none()
13303                && all_members_terminal
13304                && selection_member_range.as_ref().is_some_and(|member_range| {
13305                    state
13306                        .recorded_commands
13307                        .iter()
13308                        .any(|command| member_range.contains(&command.sequence()))
13309                })
13310            {
13311                // Terminal member history can be committed before the server's
13312                // SelectionResolved marker becomes visible to this task. That
13313                // marker is the durable barrier the selection is still waiting
13314                // on, so an otherwise commandless replay remains legitimately
13315                // pending instead of failing as an untracked yield.
13316                state.matched_recorded_pending = true;
13317            }
13318            marker
13319        };
13320        let Some(marker) = marker else {
13321            return Poll::Pending;
13322        };
13323        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
13324            || marker.selection_group_size != self.leaves.len()
13325            || self.members.first().map(|member| member.base_sequence)
13326                != Some(marker.selection_group_base_sequence)
13327        {
13328            return Poll::Ready(Err(invalid_recorded_history(
13329                "selection_group_shape_mismatch",
13330                marker.selection_group_base_sequence,
13331                self.group_id
13332                    .as_deref()
13333                    .unwrap_or("initialized selection group"),
13334                &marker.selection_group_id,
13335                "recorded selection group differs from current workflow code",
13336            )));
13337        }
13338        let Some(member_position) = self.members.iter().position(|member| {
13339            member.key == marker.member_key
13340                && member.index == marker.member_index
13341                && member.base_sequence == marker.member_base_sequence
13342                && member.size == marker.member_size
13343                && member.kind == marker.operation_kind
13344        }) else {
13345            return Poll::Ready(Err(invalid_recorded_history(
13346                "selection_member_shape_mismatch",
13347                marker.member_base_sequence,
13348                "winner member matching current workflow code",
13349                &format!("{:?}", marker.member_key),
13350                "recorded selection winner differs from the authored member identity",
13351            )));
13352        };
13353        let member = self.members[member_position].clone();
13354        let (handles, resolution_sequence) = {
13355            let mut state = match self.ctx.state.lock() {
13356                Ok(state) => state,
13357                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13358            };
13359            let identities = self
13360                .members
13361                .iter()
13362                .map(|candidate| {
13363                    selection_operation_identity(
13364                        &state,
13365                        &candidate.kind,
13366                        candidate.base_sequence,
13367                        candidate.size,
13368                    )
13369                })
13370                .collect::<Vec<_>>();
13371            if let Some((position, missing)) = identities
13372                .iter()
13373                .enumerate()
13374                .find(|(_, identity)| identity.is_empty())
13375                .map(|(position, identity)| (position, identity.clone()))
13376            {
13377                let candidate = &self.members[position];
13378                return Poll::Ready(Err(invalid_recorded_history(
13379                    "selection_operation_identity_missing",
13380                    candidate.base_sequence,
13381                    &format!(
13382                        "durable {} resource identity from scheduled/open history",
13383                        candidate.kind
13384                    ),
13385                    &missing,
13386                    "selection member history is missing its canonical durable identity",
13387                )));
13388            }
13389            let expected_winner_identity = &identities[member_position];
13390            let resolution_sequence = match validated_selection_resolution_sequence(
13391                &state,
13392                &marker,
13393                &member,
13394                expected_winner_identity,
13395            ) {
13396                Ok(sequence) => sequence,
13397                Err(error) => return Poll::Ready(Err(error)),
13398            };
13399            let handles = self
13400                .members
13401                .iter()
13402                .zip(identities)
13403                .map(|(member, identity)| DurableOperationHandle {
13404                    ctx: self.ctx.clone(),
13405                    key: member.key.clone(),
13406                    index: member.index,
13407                    kind: member.kind.clone(),
13408                    identity,
13409                    base_sequence: member.base_sequence,
13410                    size: member.size,
13411                    selection_group_id: marker.selection_group_id.clone(),
13412                    shape: member.shape.clone(),
13413                })
13414                .collect::<Vec<_>>();
13415            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
13416                return Poll::Ready(Err(error));
13417            }
13418            state.selection_marker_cursor += 1;
13419            (handles, resolution_sequence)
13420        };
13421
13422        let mut winner_failure = None;
13423        let mut flat_results = Vec::with_capacity(member.size);
13424        if marker.outcome == "failed" {
13425            let resolution_offset = match resolution_sequence
13426                .checked_sub(member.base_sequence)
13427                .and_then(|offset| usize::try_from(offset).ok())
13428            {
13429                Some(offset) if offset < member.size => offset,
13430                _ => {
13431                    return Poll::Ready(Err(invalid_recorded_history(
13432                        "selection_resolution_event_mismatch",
13433                        member.base_sequence,
13434                        "failure event within selected member bounds",
13435                        &resolution_sequence.to_string(),
13436                        "selection failure event is outside the authored member",
13437                    )))
13438                }
13439            };
13440            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
13441            match leaf.outcome.take() {
13442                Some(Err(error)) => winner_failure = Some(error),
13443                _ => {
13444                    return Poll::Ready(Err(invalid_recorded_history(
13445                        "selection_winner_outcome_mismatch",
13446                        member.base_sequence,
13447                        "exact failed terminal history referenced by SelectionResolved",
13448                        "missing or successful resolution event",
13449                        "selection winner marker disagrees with terminal operation history",
13450                    )))
13451                }
13452            }
13453        } else {
13454            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
13455                match leaf.outcome.take() {
13456                    Some(Ok(result)) => flat_results.push(result),
13457                    Some(Err(_)) => {
13458                        return Poll::Ready(Err(invalid_recorded_history(
13459                            "selection_winner_outcome_mismatch",
13460                            member.base_sequence,
13461                            "fully completed nested selection member",
13462                            "failed durable leaf",
13463                            "completed selection winner contains a failed leaf",
13464                        )))
13465                    }
13466                    None => {
13467                        return Poll::Ready(Err(invalid_recorded_history(
13468                            "selection_winner_unresolved",
13469                            member.base_sequence,
13470                            "terminal history for every completed winner leaf",
13471                            "pending member history",
13472                            "completed SelectionResolved member has an unfinished durable barrier",
13473                        )))
13474                    }
13475                }
13476            }
13477        }
13478        let value = if winner_failure.is_none() {
13479            let mut flat_results = flat_results.into_iter();
13480            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
13481            match value.into_json_result() {
13482                Ok(value) => Some(value),
13483                Err(error) => return Poll::Ready(Err(error)),
13484            }
13485        } else {
13486            None
13487        };
13488        let winner = handles[member_position].clone();
13489        self.ctx
13490            .state
13491            .lock()
13492            .map_err(|_| Error::WorkflowStatePoisoned)?
13493            .advance_cancellation_selection(&marker.selection_group_id);
13494        Poll::Ready(Ok(SelectionResult {
13495            key: winner.key.clone(),
13496            index: winner.index,
13497            kind: winner.kind.clone(),
13498            identity: winner.identity.clone(),
13499            value,
13500            failure: winner_failure,
13501            winner,
13502            handles,
13503        }))
13504    }
13505}
13506
13507fn selection_operation_identity(
13508    state: &WorkflowState,
13509    kind: &str,
13510    base_sequence: u64,
13511    size: usize,
13512) -> String {
13513    if kind == "group" {
13514        return format!("group:{base_sequence}:{size}");
13515    }
13516    let fields: &[&str] = match kind {
13517        "activity" => &["activity_execution_id"],
13518        "child" => &["child_workflow_run_id"],
13519        "timer" => &["timer_id"],
13520        "signal" => &["signal_wait_id"],
13521        "condition" => &["condition_wait_id"],
13522        _ => &[],
13523    };
13524    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
13525        for event in state
13526            .history_events
13527            .iter()
13528            .filter(|event| durable_event_sequence(event) == Some(sequence))
13529        {
13530            for field in fields {
13531                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
13532                    if !identity.is_empty() {
13533                        return identity.to_string();
13534                    }
13535                }
13536            }
13537        }
13538    }
13539    String::new()
13540}
13541
13542fn validated_selection_resolution_sequence(
13543    state: &WorkflowState,
13544    marker: &SelectionMarker,
13545    member: &SelectionMemberPlan,
13546    expected_identity: &str,
13547) -> Result<u64> {
13548    if expected_identity.is_empty() {
13549        return Err(invalid_recorded_history(
13550            "selection_operation_identity_missing",
13551            member.base_sequence,
13552            &format!(
13553                "durable {} resource identity from scheduled/open history",
13554                member.kind
13555            ),
13556            "missing operation identity",
13557            "selection member history is missing its canonical durable identity",
13558        ));
13559    }
13560    if marker.operation_identity != expected_identity {
13561        return Err(invalid_recorded_history(
13562            "selection_operation_identity_mismatch",
13563            member.base_sequence,
13564            expected_identity,
13565            &marker.operation_identity,
13566            "selection winner identity does not match durable scheduled/open history",
13567        ));
13568    }
13569
13570    let failure_types = [
13571        "ActivityFailed",
13572        "ActivityCancelled",
13573        "ActivityTimedOut",
13574        "ChildRunFailed",
13575        "ChildRunCancelled",
13576        "ChildRunTerminated",
13577    ];
13578    let success_types = [
13579        "ActivityCompleted",
13580        "ChildRunCompleted",
13581        "TimerFired",
13582        "SignalApplied",
13583        "ConditionWaitSatisfied",
13584        "ConditionWaitTimedOut",
13585    ];
13586    let terminal_types: &[&str] = if marker.outcome == "failed" {
13587        &failure_types
13588    } else {
13589        &success_types
13590    };
13591    let mut candidates = Vec::new();
13592    let member_commands = (member.base_sequence
13593        ..member.base_sequence.saturating_add(member.size as u64))
13594        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
13595        .map(|command| (command.sequence(), command))
13596        .collect::<BTreeMap<_, _>>();
13597    let mut resolved_conditions = BTreeSet::new();
13598    for event in state.history_events.iter() {
13599        let Some(sequence) = durable_event_sequence(event) else {
13600            continue;
13601        };
13602        let Some(command) = member_commands.get(&sequence) else {
13603            continue;
13604        };
13605        if !terminal_types.contains(&event.event_type.as_str()) {
13606            continue;
13607        }
13608        if matches!(command, RecordedCommand::ConditionWait { .. }) {
13609            if !matches!(
13610                event.event_type.as_str(),
13611                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
13612            ) && !(event.event_type == "TimerFired"
13613                && event.payload.get("timer_kind").and_then(Value::as_str)
13614                    == Some("condition_timeout"))
13615            {
13616                continue;
13617            }
13618            if !resolved_conditions.insert(sequence) {
13619                continue;
13620            }
13621        }
13622        let event_id = event
13623            .raw
13624            .get("id")
13625            .or_else(|| event.raw.get("event_id"))
13626            .and_then(Value::as_str)
13627            .filter(|value| !value.is_empty())
13628            .ok_or_else(|| {
13629                invalid_recorded_history(
13630                    "selection_resolution_event_id_missing",
13631                    member.base_sequence,
13632                    "terminal selection history with a durable event id",
13633                    &event.payload.to_string(),
13634                    "selection terminal history cannot be bound to its winner marker",
13635                )
13636            })?;
13637        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
13638    }
13639    let resolution = if marker.outcome == "failed" {
13640        candidates.first()
13641    } else {
13642        candidates.last()
13643    };
13644    let Some((event_id, event_type, sequence)) = resolution else {
13645        return Err(invalid_recorded_history(
13646            "selection_resolution_event_missing",
13647            member.base_sequence,
13648            "terminal history for the selected member",
13649            &format!("{:?}", marker.member_key),
13650            "selection winner marker has no matching durable terminal event",
13651        ));
13652    };
13653    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
13654        return Err(invalid_recorded_history(
13655            "selection_resolution_event_mismatch",
13656            member.base_sequence,
13657            &format!("{event_type}:{event_id}"),
13658            &format!(
13659                "{}:{}",
13660                marker.resolution_event_type, marker.resolution_event_id
13661            ),
13662            "selection winner marker does not reference the event that made its member terminal",
13663        ));
13664    }
13665    Ok(*sequence)
13666}
13667
13668fn selection_member_recorded_command(
13669    state: &WorkflowState,
13670    authored_sequence: u64,
13671) -> Option<&RecordedCommand> {
13672    let original = state
13673        .recorded_commands
13674        .iter()
13675        .find(|command| command.sequence() == authored_sequence)?;
13676    let RecordedCommand::ConditionWait {
13677        occurrence_id,
13678        parallel_group_path: Some(_),
13679        ..
13680    } = original
13681    else {
13682        return Some(original);
13683    };
13684    // Decoding proves each physical reopen has the same authored identity and
13685    // group path after a satisfied predecessor. Only its latest wait can make
13686    // this logical member terminal.
13687    state
13688        .recorded_commands
13689        .iter()
13690        .filter(|command| {
13691            matches!(command, RecordedCommand::ConditionWait {
13692                occurrence_id: candidate, ..
13693            } if candidate == occurrence_id)
13694        })
13695        .max_by_key(|command| command.sequence())
13696}
13697
13698fn recorded_selection_member_outcome(
13699    state: &WorkflowState,
13700    handle: &DurableOperationHandle,
13701) -> Result<Option<ParallelResult>> {
13702    for event in state.history_events.iter() {
13703        let Some(sequence) = durable_event_sequence(event) else {
13704            continue;
13705        };
13706        if sequence < handle.base_sequence
13707            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
13708            || !matches!(
13709                event.event_type.as_str(),
13710                "ActivityFailed"
13711                    | "ActivityCancelled"
13712                    | "ActivityTimedOut"
13713                    | "ChildRunFailed"
13714                    | "ChildRunCancelled"
13715                    | "ChildRunTerminated"
13716            )
13717        {
13718            continue;
13719        }
13720        let Some(command) = state
13721            .recorded_commands
13722            .iter()
13723            .find(|command| command.sequence() == sequence)
13724        else {
13725            continue;
13726        };
13727        match command {
13728            RecordedCommand::Activity {
13729                outcome: Some(Err(failure)),
13730                ..
13731            } => return Err(Error::ActivityFailed(failure.clone())),
13732            RecordedCommand::ChildWorkflow {
13733                outcome: Some(Err(failure)),
13734                ..
13735            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
13736            _ => {}
13737        }
13738    }
13739
13740    let mut results = Vec::with_capacity(handle.size);
13741    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13742        let Some(command) = selection_member_recorded_command(state, sequence) else {
13743            return Ok(None);
13744        };
13745        let result = match command {
13746            RecordedCommand::Activity { outcome, .. } => match outcome {
13747                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
13748                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
13749                None => return Ok(None),
13750            },
13751            RecordedCommand::Timer { fired, .. } => {
13752                if !fired {
13753                    return Ok(None);
13754                }
13755                ParallelAvroResult::Timer
13756            }
13757            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13758                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13759                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13760                None => return Ok(None),
13761            },
13762            RecordedCommand::SignalWait { value, .. } => match value {
13763                Some(value) => ParallelAvroResult::Signal(value.clone()),
13764                None => return Ok(None),
13765            },
13766            RecordedCommand::ConditionWait { result, .. } => match result {
13767                Some(result) => ParallelAvroResult::Condition(*result),
13768                None => return Ok(None),
13769            },
13770            other => {
13771                return Err(command_mismatch(
13772                    other,
13773                    format!("selected {} member", handle.kind),
13774                ))
13775            }
13776        };
13777        results.push(result);
13778    }
13779    let mut results = results.into_iter();
13780    parallel_results_for_shape(&handle.shape, &mut results)
13781        .into_json_result()
13782        .map(Some)
13783}
13784
13785fn recorded_selection_member_is_terminal(
13786    state: &WorkflowState,
13787    handle: &DurableOperationHandle,
13788) -> bool {
13789    let mut completed = 0usize;
13790    let mut all_completed = true;
13791    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13792        let Some(command) = selection_member_recorded_command(state, sequence) else {
13793            all_completed = false;
13794            continue;
13795        };
13796        let terminal = match command {
13797            RecordedCommand::Activity {
13798                outcome: Some(Err(_)),
13799                ..
13800            }
13801            | RecordedCommand::ChildWorkflow {
13802                outcome: Some(Err(_)),
13803                ..
13804            } => return true,
13805            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13806            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13807            RecordedCommand::Timer { fired, .. } => *fired,
13808            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13809            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13810            RecordedCommand::SearchAttributes { .. }
13811            | RecordedCommand::CancellationScope { .. }
13812            | RecordedCommand::SideEffect { .. }
13813            | RecordedCommand::VersionMarker { .. }
13814            | RecordedCommand::Memo { .. }
13815            | RecordedCommand::CancellationBoundary { .. }
13816            | RecordedCommand::CancellationGroup { .. } => false,
13817        };
13818        if !terminal {
13819            all_completed = false;
13820            continue;
13821        }
13822        completed += 1;
13823    }
13824    all_completed && completed == handle.size
13825}
13826
13827fn selection_cancellation_for_handle(
13828    state: &WorkflowState,
13829    handle: &DurableOperationHandle,
13830) -> Result<bool> {
13831    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13832        recorded.selection_group_id == handle.selection_group_id
13833            && recorded.member_base_sequence == handle.base_sequence
13834    }) else {
13835        return Ok(false);
13836    };
13837    validate_selection_cancellation_marker(marker, handle)?;
13838    Ok(true)
13839}
13840
13841fn validate_selection_cancellations_for_handles(
13842    state: &WorkflowState,
13843    handles: &[DurableOperationHandle],
13844) -> Result<()> {
13845    let Some(group_id) = handles
13846        .first()
13847        .map(|handle| handle.selection_group_id.as_str())
13848    else {
13849        return Ok(());
13850    };
13851    for marker in state
13852        .cancelled_selection_members
13853        .iter()
13854        .filter(|marker| marker.selection_group_id == group_id)
13855    {
13856        let Some(handle) = handles
13857            .iter()
13858            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13859        else {
13860            return Err(invalid_recorded_history(
13861                "selection_cancellation_member_mismatch",
13862                marker.member_base_sequence,
13863                "SelectionOperationCancelled matching an authored selection handle",
13864                &format!("{marker:?}"),
13865                "selection cancellation member base does not name an authored member",
13866            ));
13867        };
13868        validate_selection_cancellation_marker(marker, handle)?;
13869    }
13870    Ok(())
13871}
13872
13873fn validate_selection_cancellation_marker(
13874    marker: &SelectionCancellation,
13875    handle: &DurableOperationHandle,
13876) -> Result<()> {
13877    if marker.selection_group_id != handle.selection_group_id
13878        || marker.member_key != handle.key
13879        || marker.member_index != handle.index
13880        || marker.member_base_sequence != handle.base_sequence
13881        || marker.member_size != handle.size
13882        || marker.operation_kind != handle.kind
13883        || marker.operation_identity != handle.identity
13884    {
13885        return Err(invalid_recorded_history(
13886            "selection_cancellation_member_mismatch",
13887            handle.base_sequence,
13888            "SelectionOperationCancelled matching the authored selection handle",
13889            &format!("{marker:?}"),
13890            "selection cancellation history targets different authored member metadata",
13891        ));
13892    }
13893    Ok(())
13894}
13895
13896/// Future returned by [`DurableOperationHandle::await_result`].
13897pub struct DurableOperationAwaitCall {
13898    handle: DurableOperationHandle,
13899}
13900
13901impl Future for DurableOperationAwaitCall {
13902    type Output = Result<ParallelResult>;
13903
13904    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13905        let mut state = match self.handle.ctx.state.lock() {
13906            Ok(state) => state,
13907            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13908        };
13909        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13910            return Poll::Ready(Err(error));
13911        }
13912        match state.prepare_selection_handle_cancellation(&self.handle) {
13913            Ok(true) => return Poll::Pending,
13914            Ok(false) => {}
13915            Err(error) => return Poll::Ready(Err(error)),
13916        }
13917        match selection_cancellation_for_handle(&state, &self.handle) {
13918            Err(error) => return Poll::Ready(Err(error)),
13919            Ok(false) => {}
13920            Ok(true) => {
13921                state.advance_cancellation_receipt(
13922                    &self.handle.selection_group_id,
13923                    self.handle.base_sequence,
13924                );
13925                return Poll::Ready(Err(Error::DurableOperationCancelled(
13926                    DurableOperationCancelled {
13927                        selection_group_id: self.handle.selection_group_id.clone(),
13928                        member_key: self.handle.key.clone(),
13929                        member_index: self.handle.index,
13930                        operation_kind: self.handle.kind.clone(),
13931                        operation_identity: self.handle.identity.clone(),
13932                    },
13933                )));
13934            }
13935        }
13936        match recorded_selection_member_outcome(&state, &self.handle) {
13937            Ok(Some(result)) => {
13938                state.advance_cancellation_handle(&self.handle, false);
13939                Poll::Ready(Ok(result))
13940            }
13941            Ok(None) => Poll::Pending,
13942            Err(error) => {
13943                if !workflow_task_integrity_error(&error) {
13944                    state.advance_cancellation_handle(&self.handle, true);
13945                }
13946                Poll::Ready(Err(error))
13947            }
13948        }
13949    }
13950}
13951
13952fn validate_selection_delivery_handle(
13953    state: &WorkflowState,
13954    handle: &DurableOperationHandle,
13955) -> Result<()> {
13956    let path = state
13957        .recorded_commands
13958        .iter()
13959        .find(|command| command.sequence() == handle.base_sequence)
13960        .and_then(|command| match command {
13961            RecordedCommand::Activity {
13962                parallel_group_path,
13963                ..
13964            }
13965            | RecordedCommand::ChildWorkflow {
13966                parallel_group_path,
13967                ..
13968            }
13969            | RecordedCommand::Timer {
13970                parallel_group_path,
13971                ..
13972            }
13973            | RecordedCommand::SignalWait {
13974                parallel_group_path,
13975                ..
13976            }
13977            | RecordedCommand::ConditionWait {
13978                parallel_group_path,
13979                ..
13980            } => parallel_group_path.as_ref(),
13981            _ => None,
13982        })
13983        .and_then(|path| path.first());
13984    let matches = path.is_some_and(|entry| {
13985        entry.parallel_group_mode.as_deref() == Some("select")
13986            && entry.parallel_group_id == handle.selection_group_id
13987            && entry.selection_member_key.as_ref() == Some(&handle.key)
13988            && entry.selection_member_index == Some(handle.index)
13989            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13990            && entry.selection_member_size == Some(handle.size)
13991            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13992    });
13993    if !matches
13994        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13995            != handle.identity
13996    {
13997        return Err(invalid_recorded_history(
13998            "cooperative_cancellation_call_mismatch",
13999            handle.base_sequence,
14000            "selection handle matching its authored durable identity",
14001            &format!("{handle:?}"),
14002            "selection handle identity or member metadata changed before cancellation replay",
14003        ));
14004    }
14005    Ok(())
14006}
14007
14008/// Future returned by [`DurableOperationHandle::cancel`].
14009pub struct CancelDurableOperationCall {
14010    handle: DurableOperationHandle,
14011    emitted: bool,
14012}
14013
14014impl Future for CancelDurableOperationCall {
14015    type Output = Result<()>;
14016
14017    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14018        let ctx = self.handle.ctx.clone();
14019        let mut state = match ctx.state.lock() {
14020            Ok(state) => state,
14021            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14022        };
14023        match selection_cancellation_for_handle(&state, &self.handle) {
14024            Err(error) => return Poll::Ready(Err(error)),
14025            Ok(true) => {
14026                state.advance_cancellation_receipt(
14027                    &self.handle.selection_group_id,
14028                    self.handle.base_sequence,
14029                );
14030                return Poll::Ready(Ok(()));
14031            }
14032            Ok(false) => {}
14033        }
14034        if recorded_selection_member_is_terminal(&state, &self.handle) {
14035            return Poll::Ready(Ok(()));
14036        }
14037        if !self.emitted {
14038            state.commands.push(json!({
14039                "type": "cancel_selection_operation",
14040                "selection_group_id": self.handle.selection_group_id,
14041                "member_key": self.handle.key,
14042                "member_index": self.handle.index,
14043                "member_base_sequence": self.handle.base_sequence,
14044                "member_size": self.handle.size,
14045                "operation_kind": self.handle.kind,
14046                "operation_identity": self.handle.identity,
14047            }));
14048            self.emitted = true;
14049        }
14050        // The cancellation command is only a request. Do not expose workflow
14051        // state after cancel until committed SelectionOperationCancelled
14052        // history proves that the request won the race with member completion.
14053        Poll::Pending
14054    }
14055}
14056
14057trait PollNestedResultExt<T> {
14058    fn flatten_result(self) -> Poll<Result<T>>;
14059}
14060
14061impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14062    fn flatten_result(self) -> Poll<Result<T>> {
14063        match self {
14064            Poll::Ready(Ok(result)) => Poll::Ready(result),
14065            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14066            Poll::Pending => Poll::Pending,
14067        }
14068    }
14069}
14070
14071struct SagaCompensation {
14072    activity_type: String,
14073    options: ActivityOptions,
14074    arguments: AvroValue,
14075    registration_order: usize,
14076}
14077
14078/// Workflow-local deterministic saga compensation helper.
14079///
14080/// Register each compensation only after its forward step succeeds. Passing
14081/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14082/// reverse registration order after any failure, including cooperative
14083/// cancellation. Each compensation is an ordinary durable activity, so replay,
14084/// duplicate delivery, and worker restart use existing history semantics.
14085pub struct Saga {
14086    ctx: WorkflowContext,
14087    compensations: Vec<SagaCompensation>,
14088}
14089
14090impl Saga {
14091    fn new(ctx: WorkflowContext) -> Self {
14092        Self {
14093            ctx,
14094            compensations: Vec::new(),
14095        }
14096    }
14097
14098    pub fn add_compensation<T: Serialize>(
14099        &mut self,
14100        activity_type: impl Into<String>,
14101        args: T,
14102    ) -> Result<&mut Self> {
14103        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14104    }
14105
14106    pub fn add_compensation_with_options<T: Serialize>(
14107        &mut self,
14108        activity_type: impl Into<String>,
14109        options: ActivityOptions,
14110        args: T,
14111    ) -> Result<&mut Self> {
14112        let activity_type = activity_type.into();
14113        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14114            return Err(Error::Codec(
14115                "saga compensation activity type must be non-empty without surrounding whitespace"
14116                    .to_string(),
14117            ));
14118        }
14119        options.validate().map_err(Error::InvalidActivityOptions)?;
14120        let arguments = AvroValue::from_serialize(&args)?;
14121        let registration_order = self.compensations.len() + 1;
14122        self.compensations.push(SagaCompensation {
14123            activity_type,
14124            options,
14125            arguments,
14126            registration_order,
14127        });
14128        Ok(self)
14129    }
14130
14131    /// Compensate `initiating_failure` and return the failure that must remain.
14132    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14133        let _shield = match self.ctx.cancellation_shield() {
14134            Ok(shield) => shield,
14135            Err(error) => return error,
14136        };
14137        while let Some(compensation) = self.compensations.pop() {
14138            if let Err(compensation_failure) = self
14139                .ctx
14140                .activity_with_options(
14141                    compensation.activity_type.clone(),
14142                    compensation.options,
14143                    compensation.arguments,
14144                )
14145                .await
14146            {
14147                if workflow_task_integrity_error(&compensation_failure) {
14148                    return compensation_failure;
14149                }
14150                return Error::SagaCompensationFailed(SagaCompensationFailure {
14151                    initiating_failure: Box::new(initiating_failure),
14152                    compensation_failure: Box::new(compensation_failure),
14153                    compensation_activity_type: compensation.activity_type,
14154                    compensation_registration_order: compensation.registration_order,
14155                });
14156            }
14157        }
14158        initiating_failure
14159    }
14160
14161    /// Return a successful forward value or compensate and preserve its failure.
14162    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14163        match outcome {
14164            Ok(value) => Ok(value),
14165            Err(error) => Err(self.compensate(error).await),
14166        }
14167    }
14168}
14169
14170pub struct ActivityCall {
14171    ctx: WorkflowContext,
14172    activity_type: String,
14173    options: ActivityOptions,
14174    worker_session: Option<WorkerSessionOptions>,
14175    args: Option<Result<AvroValue>>,
14176    scheduled: bool,
14177    local: bool,
14178    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
14179    parallel_group_path: Vec<ParallelGroupMetadata>,
14180}
14181
14182impl ActivityCall {
14183    fn poll_avro_value(
14184        mut self: Pin<&mut Self>,
14185        _cx: &mut TaskContext<'_>,
14186    ) -> Poll<Result<AvroValue>> {
14187        let ctx = self.ctx.clone();
14188        let mut state = match ctx.state.lock() {
14189            Ok(state) => state,
14190            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14191        };
14192
14193        if let Some(result) = &self.local_result {
14194            return match result.lock() {
14195                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
14196                    Poll::Ready(result.map_err(Error::ActivityFailed))
14197                }),
14198                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14199            };
14200        }
14201        if self.scheduled {
14202            return Poll::Pending;
14203        }
14204
14205        let options = match self.options.validate() {
14206            Ok(options) => options,
14207            Err(error) => {
14208                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
14209            }
14210        };
14211        if self.local {
14212            if self.worker_session.is_some() {
14213                return Poll::Ready(Err(Error::WorkerLoop(
14214                    "local activities cannot use worker-session routing".into(),
14215                )));
14216            }
14217            if let Err(error) = local_activity::validate(&options) {
14218                return Poll::Ready(Err(error));
14219            }
14220        }
14221        let session = match self
14222            .worker_session
14223            .as_ref()
14224            .map(WorkerSessionOptions::to_wire)
14225            .transpose()
14226        {
14227            Ok(value) => value,
14228            Err(error) => return Poll::Ready(Err(error)),
14229        };
14230        let session_queue = session
14231            .as_ref()
14232            .and_then(|session| session["queue"].as_str());
14233        let task_queue = options
14234            .task_queue
14235            .clone()
14236            .or_else(|| session_queue.map(str::to_owned))
14237            .unwrap_or_else(|| state.task_queue.clone());
14238        if session_queue.is_some_and(|queue| queue != task_queue) {
14239            return Poll::Ready(Err(Error::WorkerLoop(
14240                "worker-session queue must match the activity task queue".into(),
14241            )));
14242        }
14243        let current_recorded_options = RecordedActivityOptions {
14244            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
14245            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
14246            retry_policy: current_activity_retry_snapshot(&options),
14247            worker_session: session,
14248        };
14249
14250        let cursor = state.command_cursor;
14251        let call_kind = if self.local {
14252            CancellationCallKind::LocalActivity
14253        } else {
14254            CancellationCallKind::Activity
14255        };
14256        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14257            return Poll::Ready(Err(error));
14258        }
14259        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
14260            Ok(recorded) => recorded,
14261            Err(error) => return Poll::Ready(Err(error)),
14262        };
14263        if let Some(recorded) = recorded {
14264            let sequence = recorded.sequence();
14265            match recorded {
14266                RecordedCommand::Activity {
14267                    activity_type,
14268                    cancellation_policy,
14269                    options: recorded_options,
14270                    outcome,
14271                    parallel_group_path,
14272                    ..
14273                } => {
14274                    let current_policy = options
14275                        .cancellation_policy
14276                        .unwrap_or(CancellationPolicy::TryCancel)
14277                        .as_str();
14278                    if cancellation_policy != current_policy {
14279                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14280                            ReplayFailure::new(
14281                                "activity_cancellation_policy_changed",
14282                                Some(sequence),
14283                                Some(cancellation_policy),
14284                                Some(current_policy.to_string()),
14285                                "Activity cancellation policy changed during replay",
14286                            ),
14287                        )));
14288                    }
14289                    if let Err(error) = ensure_parallel_path_matches(
14290                        sequence,
14291                        parallel_group_path.as_deref(),
14292                        &self.parallel_group_path,
14293                    ) {
14294                        return Poll::Ready(Err(error));
14295                    }
14296                    if let Some(recorded_type) = activity_type {
14297                        if recorded_type != self.activity_type {
14298                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14299                                ReplayFailure::new(
14300                                    "recorded_command_detail_mismatch",
14301                                    Some(sequence),
14302                                    Some(format!("activity:{recorded_type}")),
14303                                    Some(format!("activity:{}", self.activity_type)),
14304                                    "recorded activity type differs from the current workflow command",
14305                                ),
14306                            )));
14307                        }
14308                    }
14309                    if let Some(recorded_options) = recorded_options {
14310                        if recorded_options.worker_session
14311                            != current_recorded_options.worker_session
14312                        {
14313                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14314                                "activity_worker_session_mismatch", Some(sequence),
14315                                Some(activity_options_description(&recorded_options)),
14316                                Some(activity_options_description(&current_recorded_options)),
14317                                "recorded worker-session routing differs from the current activity",
14318                            ))));
14319                        }
14320                        if !recorded_options
14321                            .task_queue
14322                            .matches_current(&current_recorded_options.task_queue)
14323                        {
14324                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14325                                ReplayFailure::new(
14326                                    "activity_task_queue_mismatch",
14327                                    Some(sequence),
14328                                    Some(activity_options_description(&recorded_options)),
14329                                    Some(activity_options_description(&current_recorded_options)),
14330                                    "recorded activity task queue differs from the current workflow command",
14331                                ),
14332                            )));
14333                        }
14334                        if (self.local
14335                            && matches!(
14336                                recorded_options.execution_mode,
14337                                RecordedSnapshotValue::Unknown
14338                            ))
14339                            || !recorded_options
14340                                .execution_mode
14341                                .matches_current(&current_recorded_options.execution_mode)
14342                        {
14343                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14344                                ReplayFailure::new(
14345                                    "activity_execution_mode_mismatch",
14346                                    Some(sequence),
14347                                    Some(activity_options_description(&recorded_options)),
14348                                    Some(activity_options_description(&current_recorded_options)),
14349                                    "recorded activity execution mode differs from the current workflow command",
14350                                ),
14351                            )));
14352                        }
14353                        if !recorded_options
14354                            .retry_policy
14355                            .matches_current(&current_recorded_options.retry_policy)
14356                        {
14357                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14358                                ReplayFailure::new(
14359                                    "activity_retry_policy_mismatch",
14360                                    Some(sequence),
14361                                    Some(activity_options_description(&recorded_options)),
14362                                    Some(activity_options_description(&current_recorded_options)),
14363                                    "recorded activity retry policy differs from the current workflow command",
14364                                ),
14365                            )));
14366                        }
14367                    }
14368                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
14369                        return Poll::Ready(Err(error));
14370                    }
14371                    match state.prepare_scalar_cancellation(
14372                        cursor,
14373                        call_kind,
14374                        &self.parallel_group_path,
14375                    ) {
14376                        Ok(true) => {
14377                            self.scheduled = 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::ActivityFailed));
14387                    }
14388                    state.matched_recorded_pending = true;
14389                    self.scheduled = true;
14390                    return Poll::Pending;
14391                }
14392                other => {
14393                    return Poll::Ready(Err(command_mismatch(
14394                        &other,
14395                        format!("activity:{}", self.activity_type),
14396                    )));
14397                }
14398            }
14399        }
14400
14401        if !self.scheduled {
14402            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14403                Ok(args) => args,
14404                Err(error) => return Poll::Ready(Err(error)),
14405            };
14406            let arguments = normalize_avro_arguments(args);
14407            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
14408                Ok(envelope) => envelope,
14409                Err(error) => return Poll::Ready(Err(error)),
14410            };
14411
14412            let mut command = serde_json::Map::from_iter([
14413                (
14414                    "type".to_string(),
14415                    json!(if self.local {
14416                        "record_local_activity"
14417                    } else {
14418                        "schedule_activity"
14419                    }),
14420                ),
14421                (
14422                    "activity_type".to_string(),
14423                    json!(self.activity_type.clone()),
14424                ),
14425                ("queue".to_string(), json!(task_queue)),
14426                ("arguments".to_string(), envelope),
14427            ]);
14428            for (field, value) in [
14429                ("start_to_close_timeout", options.start_to_close_timeout),
14430                (
14431                    "schedule_to_start_timeout",
14432                    options.schedule_to_start_timeout,
14433                ),
14434                (
14435                    "schedule_to_close_timeout",
14436                    options.schedule_to_close_timeout,
14437                ),
14438                ("heartbeat_timeout", options.heartbeat_timeout),
14439            ] {
14440                if let Some(value) = value {
14441                    command.insert(field.to_string(), json!(value));
14442                }
14443            }
14444            if let Some(retry_policy) = &options.retry_policy {
14445                command.insert("retry_policy".to_string(), retry_policy.clone());
14446            }
14447            if let Some(policy) = options.cancellation_policy {
14448                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
14449            }
14450            if let Some(session) = current_recorded_options.worker_session {
14451                command.insert("worker_session".into(), session);
14452            }
14453            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14454            ctx.apply_scope_membership(&mut command);
14455            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
14456                Ok(true) => {
14457                    self.scheduled = true;
14458                    return Poll::Pending;
14459                }
14460                Ok(false) => {}
14461                Err(error) => return Poll::Ready(Err(error)),
14462            }
14463            if self.local {
14464                command.remove("queue");
14465                command.insert("execution_mode".into(), json!("local"));
14466                let result = Arc::new(Mutex::new(None));
14467                let command_index = state.commands.len();
14468                state.local_activity_requests.push(local_activity::Request {
14469                    command_index,
14470                    options,
14471                    arguments,
14472                    result: result.clone(),
14473                });
14474                self.local_result = Some(result);
14475            }
14476            state.commands.push(Value::Object(command));
14477            self.scheduled = true;
14478        }
14479
14480        Poll::Pending
14481    }
14482}
14483
14484impl Future for ActivityCall {
14485    type Output = Result<Value>;
14486
14487    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14488        match self.poll_avro_value(cx) {
14489            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
14490            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14491            Poll::Pending => Poll::Pending,
14492        }
14493    }
14494}
14495
14496/// Future returned by [`WorkflowContext::sleep`].
14497pub struct TimerCall {
14498    ctx: WorkflowContext,
14499    delay_seconds: Option<u64>,
14500    scheduled: bool,
14501    matched_pending: bool,
14502    parallel_group_path: Vec<ParallelGroupMetadata>,
14503}
14504
14505impl Future for TimerCall {
14506    type Output = Result<()>;
14507
14508    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14509        if self.matched_pending {
14510            return Poll::Pending;
14511        }
14512
14513        let ctx = self.ctx.clone();
14514        let Some(requested_delay) = self.delay_seconds else {
14515            return Poll::Ready(Err(Error::TimerDurationOverflow));
14516        };
14517        let mut state = match ctx.state.lock() {
14518            Ok(state) => state,
14519            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14520        };
14521
14522        let cursor = state.command_cursor;
14523        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14524            return Poll::Ready(Err(error));
14525        }
14526        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
14527        {
14528            Ok(recorded) => recorded,
14529            Err(error) => return Poll::Ready(Err(error)),
14530        };
14531        if let Some(recorded) = recorded {
14532            match recorded {
14533                RecordedCommand::Timer {
14534                    sequence,
14535                    delay_seconds,
14536                    fired,
14537                    parallel_group_path,
14538                    ..
14539                } => {
14540                    if let Err(error) =
14541                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
14542                    {
14543                        return Poll::Ready(Err(error));
14544                    }
14545                    if let Err(error) = ensure_parallel_path_matches(
14546                        sequence,
14547                        parallel_group_path.as_deref(),
14548                        &self.parallel_group_path,
14549                    ) {
14550                        return Poll::Ready(Err(error));
14551                    }
14552                    if delay_seconds != requested_delay {
14553                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14554                            ReplayFailure::new(
14555                                "timer_delay_mismatch",
14556                                Some(sequence),
14557                                Some(format!("timer:{delay_seconds}s")),
14558                                Some(format!("timer:{requested_delay}s")),
14559                                "recorded timer delay differs from the current workflow command",
14560                            ),
14561                        )));
14562                    }
14563                    if let Err(error) =
14564                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
14565                    {
14566                        return Poll::Ready(Err(error));
14567                    }
14568                    match state.prepare_scalar_cancellation(
14569                        cursor,
14570                        CancellationCallKind::Timer,
14571                        &self.parallel_group_path,
14572                    ) {
14573                        Ok(true) => {
14574                            self.scheduled = true;
14575                            self.matched_pending = true;
14576                            return Poll::Pending;
14577                        }
14578                        Ok(false) => {}
14579                        Err(error) => return Poll::Ready(Err(error)),
14580                    }
14581                    state.command_cursor += 1;
14582                    if fired {
14583                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14584                        return Poll::Ready(Ok(()));
14585                    }
14586                    state.matched_recorded_pending = true;
14587                    self.scheduled = true;
14588                    self.matched_pending = true;
14589                    return Poll::Pending;
14590                }
14591                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
14592            }
14593        }
14594
14595        if !self.scheduled {
14596            let mut command = serde_json::Map::from_iter([
14597                ("type".to_string(), json!("start_timer")),
14598                ("delay_seconds".to_string(), json!(requested_delay)),
14599            ]);
14600            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
14601                Ok(Some(proof)) => {
14602                    command.insert("cancellation_cleanup".into(), proof);
14603                }
14604                Ok(None) => {}
14605                Err(error) => return Poll::Ready(Err(error)),
14606            }
14607            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14608            ctx.apply_scope_membership(&mut command);
14609            match state.prepare_scalar_cancellation(
14610                cursor,
14611                CancellationCallKind::Timer,
14612                &self.parallel_group_path,
14613            ) {
14614                Ok(true) => {
14615                    self.scheduled = true;
14616                    self.matched_pending = true;
14617                    return Poll::Pending;
14618                }
14619                Ok(false) => {}
14620                Err(error) => return Poll::Ready(Err(error)),
14621            }
14622            state.commands.push(Value::Object(command));
14623            self.scheduled = true;
14624        }
14625
14626        Poll::Pending
14627    }
14628}
14629
14630/// Future returned by [`WorkflowContext::wait_condition`].
14631pub struct ConditionWaitCall {
14632    ctx: WorkflowContext,
14633    options: ConditionWaitOptions,
14634    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
14635    occurrence_id: Option<String>,
14636    opened_wait: bool,
14637    parallel_group_path: Vec<ParallelGroupMetadata>,
14638}
14639
14640impl Future for ConditionWaitCall {
14641    type Output = Result<ConditionWaitResult>;
14642
14643    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14644        if self.opened_wait {
14645            return Poll::Pending;
14646        }
14647
14648        let options = match self.options.validate() {
14649            Ok(options) => options,
14650            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
14651        };
14652        let ctx = self.ctx.clone();
14653        let occurrence_id = match self.occurrence_id.as_ref() {
14654            Some(occurrence_id) => occurrence_id.clone(),
14655            None => {
14656                let mut state = match ctx.state.lock() {
14657                    Ok(state) => state,
14658                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14659                };
14660                let ordinal = state.condition_wait_occurrence_counter;
14661                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
14662                    Some(next) => next,
14663                    None => {
14664                        return Poll::Ready(Err(Error::WorkerLoop(
14665                            "condition wait occurrence counter overflowed".to_string(),
14666                        )))
14667                    }
14668                };
14669                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
14670                drop(state);
14671                self.occurrence_id = Some(occurrence_id.clone());
14672                occurrence_id
14673            }
14674        };
14675
14676        let recorded_result = {
14677            let mut state = match ctx.state.lock() {
14678                Ok(state) => state,
14679                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14680            };
14681            let initial_cursor = state.command_cursor;
14682            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
14683                return Poll::Ready(Err(error));
14684            }
14685            let recorded = match state
14686                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
14687            {
14688                Ok(recorded) => recorded,
14689                Err(error) => return Poll::Ready(Err(error)),
14690            };
14691            let Some(recorded) = recorded else {
14692                drop(state);
14693                return self.poll_new_condition(options);
14694            };
14695            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
14696                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
14697            }
14698
14699            let mut cursor = state.command_cursor;
14700            let mut result = None;
14701            let mut pending_delivery = false;
14702            loop {
14703                if cursor > initial_cursor
14704                    && matches!(
14705                        state.recorded_commands.get(cursor),
14706                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
14707                    )
14708                {
14709                    break;
14710                }
14711                let recorded = match state
14712                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
14713                {
14714                    Ok(recorded) => recorded,
14715                    Err(error) => return Poll::Ready(Err(error)),
14716                };
14717                let Some(RecordedCommand::ConditionWait {
14718                    sequence,
14719                    occurrence_id: ref recorded_occurrence_id,
14720                    ref condition_key,
14721                    ref predicate_identity,
14722                    timeout_seconds,
14723                    result: recorded_result,
14724                    ref parallel_group_path,
14725                    ..
14726                }) = recorded
14727                else {
14728                    break;
14729                };
14730
14731                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
14732                    break;
14733                }
14734                if let Err(error) = ensure_parallel_path_matches(
14735                    sequence,
14736                    parallel_group_path.as_deref(),
14737                    &self.parallel_group_path,
14738                ) {
14739                    return Poll::Ready(Err(error));
14740                }
14741                if let Err(error) = validate_recorded_condition_wait(
14742                    sequence,
14743                    recorded_occurrence_id,
14744                    condition_key.as_deref(),
14745                    predicate_identity,
14746                    timeout_seconds,
14747                    &occurrence_id,
14748                    &options,
14749                ) {
14750                    return Poll::Ready(Err(error));
14751                }
14752                if result == Some(ConditionWaitResult::TimedOut) {
14753                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14754                        "condition_wait_reopened_after_timeout",
14755                        Some(sequence),
14756                        Some("timed-out condition is terminal".to_string()),
14757                        Some("another physical wait-open".to_string()),
14758                        "condition history reopened one logical wait after its durable timeout",
14759                    ))));
14760                }
14761                if let Err(error) =
14762                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14763                {
14764                    return Poll::Ready(Err(error));
14765                }
14766                match state.prepare_scalar_cancellation(
14767                    cursor,
14768                    CancellationCallKind::Condition,
14769                    &self.parallel_group_path,
14770                ) {
14771                    Ok(pending) => pending_delivery |= pending,
14772                    Err(error) => return Poll::Ready(Err(error)),
14773                }
14774                result = recorded_result;
14775                if result.is_some() {
14776                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14777                }
14778                cursor += 1;
14779            }
14780            state.command_cursor = cursor;
14781            if pending_delivery {
14782                self.opened_wait = true;
14783                return Poll::Pending;
14784            }
14785            result
14786        };
14787
14788        if let Some(result) = recorded_result {
14789            return Poll::Ready(Ok(result));
14790        }
14791
14792        self.poll_open_condition(options, true)
14793    }
14794}
14795
14796impl ConditionWaitCall {
14797    fn poll_new_condition(
14798        self: Pin<&mut Self>,
14799        options: ValidatedConditionWaitOptions,
14800    ) -> Poll<Result<ConditionWaitResult>> {
14801        self.poll_open_condition(options, false)
14802    }
14803
14804    fn poll_open_condition(
14805        mut self: Pin<&mut Self>,
14806        options: ValidatedConditionWaitOptions,
14807        recorded_wait: bool,
14808    ) -> Poll<Result<ConditionWaitResult>> {
14809        {
14810            let ctx = self.ctx.clone();
14811            let mut state = match ctx.state.lock() {
14812                Ok(state) => state,
14813                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14814            };
14815            let cursor = state.command_cursor;
14816            match state.prepare_scalar_cancellation(
14817                cursor,
14818                CancellationCallKind::Condition,
14819                &self.parallel_group_path,
14820            ) {
14821                Ok(true) => {
14822                    self.opened_wait = true;
14823                    return Poll::Pending;
14824                }
14825                Ok(false) => {}
14826                Err(error) => return Poll::Ready(Err(error)),
14827            }
14828        }
14829        let selection_member = self
14830            .parallel_group_path
14831            .first()
14832            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14833        match (self.predicate)() {
14834            Ok(true) if !selection_member || recorded_wait => {
14835                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14836            }
14837            Ok(_) => {}
14838            Err(error) => return Poll::Ready(Err(error)),
14839        }
14840        if options.timeout_seconds == Some(0) && !selection_member {
14841            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14842        }
14843
14844        let ctx = self.ctx.clone();
14845        let mut state = match ctx.state.lock() {
14846            Ok(state) => state,
14847            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14848        };
14849        let mut command = serde_json::Map::from_iter([
14850            ("type".to_string(), json!("open_condition_wait")),
14851            (
14852                "condition_wait_occurrence_id".to_string(),
14853                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14854            ),
14855            ("condition_key".to_string(), json!(options.condition_key)),
14856            (
14857                "condition_definition_fingerprint".to_string(),
14858                json!(options.predicate_identity),
14859            ),
14860        ]);
14861        if let Some(timeout_seconds) = options.timeout_seconds {
14862            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14863        }
14864        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14865        ctx.apply_scope_membership(&mut command);
14866        state.commands.push(Value::Object(command));
14867        drop(state);
14868        self.opened_wait = true;
14869        Poll::Pending
14870    }
14871}
14872
14873fn validate_recorded_condition_wait(
14874    sequence: u64,
14875    recorded_occurrence_id: &str,
14876    recorded_key: Option<&str>,
14877    recorded_predicate_identity: &str,
14878    recorded_timeout_seconds: Option<u64>,
14879    current_occurrence_id: &str,
14880    current: &ValidatedConditionWaitOptions,
14881) -> Result<()> {
14882    if recorded_occurrence_id != current_occurrence_id {
14883        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14884            "condition_wait_occurrence_mismatch",
14885            Some(sequence),
14886            Some(recorded_occurrence_id.to_string()),
14887            Some(current_occurrence_id.to_string()),
14888            "recorded condition occurrence differs from the current authored wait position",
14889        )));
14890    }
14891    if recorded_key != Some(current.condition_key.as_str()) {
14892        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14893            "condition_wait_key_mismatch",
14894            Some(sequence),
14895            recorded_key.map(str::to_string),
14896            Some(current.condition_key.clone()),
14897            "recorded condition identity differs from the current workflow wait",
14898        )));
14899    }
14900    if recorded_predicate_identity != current.predicate_identity {
14901        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14902            "condition_wait_predicate_mismatch",
14903            Some(sequence),
14904            Some(recorded_predicate_identity.to_string()),
14905            Some(current.predicate_identity.clone()),
14906            "recorded condition predicate behavior differs from current workflow code",
14907        )));
14908    }
14909    if recorded_timeout_seconds != current.timeout_seconds {
14910        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14911            "condition_wait_timeout_mismatch",
14912            Some(sequence),
14913            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14914            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14915            "recorded condition timeout differs from the current workflow wait",
14916        )));
14917    }
14918    Ok(())
14919}
14920
14921/// Future returned by [`WorkflowContext::start_child_workflow`].
14922pub struct ChildWorkflowCall {
14923    ctx: WorkflowContext,
14924    workflow_type: String,
14925    options: ChildWorkflowOptions,
14926    args: Option<Result<AvroValue>>,
14927    scheduled: bool,
14928    matched_pending: bool,
14929    parallel_group_path: Vec<ParallelGroupMetadata>,
14930}
14931
14932impl ChildWorkflowCall {
14933    fn poll_avro_value(
14934        mut self: Pin<&mut Self>,
14935        _cx: &mut TaskContext<'_>,
14936    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14937        if self.matched_pending {
14938            return Poll::Pending;
14939        }
14940
14941        let ctx = self.ctx.clone();
14942        let mut state = match ctx.state.lock() {
14943            Ok(state) => state,
14944            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14945        };
14946
14947        let cursor = state.command_cursor;
14948        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14949            return Poll::Ready(Err(error));
14950        }
14951        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14952        {
14953            Ok(recorded) => recorded,
14954            Err(error) => return Poll::Ready(Err(error)),
14955        };
14956        if let Some(recorded) = recorded {
14957            let sequence = recorded.sequence();
14958            match recorded {
14959                RecordedCommand::ChildWorkflow {
14960                    workflow_type,
14961                    policies,
14962                    outcome,
14963                    parallel_group_path,
14964                    ..
14965                } => {
14966                    if let Err(error) = ensure_parallel_path_matches(
14967                        sequence,
14968                        parallel_group_path.as_deref(),
14969                        &self.parallel_group_path,
14970                    ) {
14971                        return Poll::Ready(Err(error));
14972                    }
14973                    if let Some(recorded_type) = workflow_type {
14974                        if recorded_type != self.workflow_type {
14975                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14976                                ReplayFailure::new(
14977                                    "recorded_command_detail_mismatch",
14978                                    Some(sequence),
14979                                    Some(format!("child workflow:{recorded_type}")),
14980                                    Some(format!("child workflow:{}", self.workflow_type)),
14981                                    "recorded child workflow type differs from the current workflow command",
14982                                ),
14983                            )));
14984                        }
14985                    }
14986                    if let Err(error) =
14987                        ensure_child_policies_match(sequence, &policies, &self.options)
14988                    {
14989                        return Poll::Ready(Err(error));
14990                    }
14991                    if let Err(error) =
14992                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14993                    {
14994                        return Poll::Ready(Err(error));
14995                    }
14996                    match state.prepare_scalar_cancellation(
14997                        cursor,
14998                        CancellationCallKind::Child,
14999                        &self.parallel_group_path,
15000                    ) {
15001                        Ok(true) => {
15002                            self.scheduled = true;
15003                            self.matched_pending = true;
15004                            return Poll::Pending;
15005                        }
15006                        Ok(false) => {}
15007                        Err(error) => return Poll::Ready(Err(error)),
15008                    }
15009                    state.command_cursor += 1;
15010                    if let Some(outcome) = outcome {
15011                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15012                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15013                    }
15014                    state.matched_recorded_pending = true;
15015                    self.scheduled = true;
15016                    self.matched_pending = true;
15017                    return Poll::Pending;
15018                }
15019                other => {
15020                    return Poll::Ready(Err(command_mismatch(
15021                        &other,
15022                        format!("child workflow:{}", self.workflow_type),
15023                    )));
15024                }
15025            }
15026        }
15027
15028        if !self.scheduled {
15029            if self.options.task_queue.trim().is_empty() {
15030                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15031                    "task_queue must not be empty".to_string(),
15032                )));
15033            }
15034            for (name, value) in [
15035                (
15036                    "execution_timeout_seconds",
15037                    self.options.execution_timeout_seconds,
15038                ),
15039                ("run_timeout_seconds", self.options.run_timeout_seconds),
15040            ] {
15041                if value == Some(0) {
15042                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15043                        "{name} must be at least 1"
15044                    ))));
15045                }
15046            }
15047
15048            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15049                Ok(args) => args,
15050                Err(error) => return Poll::Ready(Err(error)),
15051            };
15052            let arguments = match encode_typed_envelope(
15053                &normalize_avro_arguments(args),
15054                &state.payload_codec,
15055            ) {
15056                Ok(arguments) => arguments,
15057                Err(error) => return Poll::Ready(Err(error)),
15058            };
15059            let mut command = json!({
15060                "type": "start_child_workflow",
15061                "workflow_type": self.workflow_type,
15062                "queue": self.options.task_queue,
15063                "parent_close_policy": self.options.parent_close_policy.as_str(),
15064                "arguments": arguments,
15065            });
15066            let object = command
15067                .as_object_mut()
15068                .expect("child workflow command is always an object");
15069            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15070                object.insert(
15071                    "cancellation_policy".to_string(),
15072                    json!(self.options.cancellation_policy.as_str()),
15073                );
15074            }
15075            if let Some(policy) = &self.options.retry_policy {
15076                let mut retry_policy = serde_json::Map::new();
15077                if let Some(max_attempts) = policy.max_attempts {
15078                    if max_attempts == 0 {
15079                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15080                            "retry_policy.max_attempts must be at least 1".to_string(),
15081                        )));
15082                    }
15083                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15084                }
15085                if !policy.backoff_seconds.is_empty() {
15086                    retry_policy
15087                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15088                }
15089                if !policy.non_retryable_error_types.is_empty() {
15090                    retry_policy.insert(
15091                        "non_retryable_error_types".to_string(),
15092                        json!(policy.non_retryable_error_types),
15093                    );
15094                }
15095                if retry_policy.is_empty() {
15096                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15097                        "retry_policy must configure at least one field".to_string(),
15098                    )));
15099                }
15100                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15101            }
15102            if let Some(seconds) = self.options.execution_timeout_seconds {
15103                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15104            }
15105            if let Some(seconds) = self.options.run_timeout_seconds {
15106                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15107            }
15108            apply_parallel_group_path(object, &self.parallel_group_path);
15109            ctx.apply_scope_membership(object);
15110            match state.prepare_scalar_cancellation(
15111                cursor,
15112                CancellationCallKind::Child,
15113                &self.parallel_group_path,
15114            ) {
15115                Ok(true) => {
15116                    self.scheduled = true;
15117                    self.matched_pending = true;
15118                    return Poll::Pending;
15119                }
15120                Ok(false) => {}
15121                Err(error) => return Poll::Ready(Err(error)),
15122            }
15123            state.commands.push(command);
15124            self.scheduled = true;
15125        }
15126
15127        Poll::Pending
15128    }
15129}
15130
15131impl Future for ChildWorkflowCall {
15132    type Output = Result<ChildWorkflowResult>;
15133
15134    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15135        match self.poll_avro_value(cx) {
15136            Poll::Ready(Ok(result)) => match result.result.into_json() {
15137                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15138                    parent: result.parent,
15139                    child: result.child,
15140                    child_workflow_type: result.child_workflow_type,
15141                    result: projected,
15142                })),
15143                Err(error) => Poll::Ready(Err(error)),
15144            },
15145            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15146            Poll::Pending => Poll::Pending,
15147        }
15148    }
15149}
15150
15151fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15152    Error::NonDeterministicReplay(ReplayFailure::new(
15153        "recorded_command_mismatch",
15154        Some(recorded.sequence()),
15155        Some(recorded.shape().to_string()),
15156        Some(actual.into()),
15157        "current workflow command does not match the recorded durable command sequence",
15158    ))
15159}
15160
15161pub struct SignalCall {
15162    ctx: WorkflowContext,
15163    signal_name: String,
15164    runtime_reserved_allowed: bool,
15165    opened_wait: bool,
15166    matched_pending: bool,
15167    parallel_group_path: Vec<ParallelGroupMetadata>,
15168}
15169
15170impl SignalCall {
15171    fn poll_avro_value(
15172        mut self: Pin<&mut Self>,
15173        _cx: &mut TaskContext<'_>,
15174    ) -> Poll<Result<Vec<AvroValue>>> {
15175        if self.matched_pending {
15176            return Poll::Pending;
15177        }
15178        if !self.runtime_reserved_allowed {
15179            if let Err(error) = validate_user_signal_name(&self.signal_name) {
15180                return Poll::Ready(Err(error));
15181            }
15182        }
15183
15184        let ctx = self.ctx.clone();
15185        let mut state = match ctx.state.lock() {
15186            Ok(state) => state,
15187            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15188        };
15189
15190        let cursor = state.command_cursor;
15191        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15192            return Poll::Ready(Err(error));
15193        }
15194        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
15195        {
15196            Ok(recorded) => recorded,
15197            Err(error) => return Poll::Ready(Err(error)),
15198        };
15199        if let Some(recorded) = recorded {
15200            match recorded {
15201                RecordedCommand::SignalWait {
15202                    sequence,
15203                    signal_name,
15204                    value,
15205                    parallel_group_path,
15206                } => {
15207                    if let Err(error) = ensure_parallel_path_matches(
15208                        sequence,
15209                        parallel_group_path.as_deref(),
15210                        &self.parallel_group_path,
15211                    ) {
15212                        return Poll::Ready(Err(error));
15213                    }
15214                    if signal_name != self.signal_name {
15215                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15216                            ReplayFailure::new(
15217                                "recorded_command_detail_mismatch",
15218                                Some(sequence),
15219                                Some(format!("signal wait:{signal_name}")),
15220                                Some(format!("signal wait:{}", self.signal_name)),
15221                                "recorded signal name differs from the current workflow command",
15222                            ),
15223                        )));
15224                    }
15225
15226                    if let Err(error) =
15227                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
15228                    {
15229                        return Poll::Ready(Err(error));
15230                    }
15231                    match state.prepare_scalar_cancellation(
15232                        cursor,
15233                        CancellationCallKind::Signal,
15234                        &self.parallel_group_path,
15235                    ) {
15236                        Ok(true) => {
15237                            self.opened_wait = true;
15238                            self.matched_pending = true;
15239                            return Poll::Pending;
15240                        }
15241                        Ok(false) => {}
15242                        Err(error) => return Poll::Ready(Err(error)),
15243                    }
15244                    state.command_cursor += 1;
15245                    if let Some(value) = value {
15246                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15247                        return Poll::Ready(Ok(value));
15248                    }
15249                    if state
15250                        .resume_signal
15251                        .as_ref()
15252                        .is_some_and(|signal| signal.signal_name == self.signal_name)
15253                    {
15254                        let signal = state
15255                            .resume_signal
15256                            .take()
15257                            .expect("matching resume signal is present");
15258                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
15259                        return Poll::Ready(Ok(signal.arguments));
15260                    }
15261
15262                    state.matched_recorded_pending = true;
15263                    self.opened_wait = true;
15264                    self.matched_pending = true;
15265                    return Poll::Pending;
15266                }
15267                other => {
15268                    return Poll::Ready(Err(command_mismatch(
15269                        &other,
15270                        format!("signal wait:{}", self.signal_name),
15271                    )));
15272                }
15273            }
15274        }
15275
15276        match state.prepare_scalar_cancellation(
15277            cursor,
15278            CancellationCallKind::Signal,
15279            &self.parallel_group_path,
15280        ) {
15281            Ok(true) => {
15282                self.opened_wait = true;
15283                self.matched_pending = true;
15284                return Poll::Pending;
15285            }
15286            Ok(false) => {}
15287            Err(error) => return Poll::Ready(Err(error)),
15288        }
15289
15290        if state
15291            .resume_signal
15292            .as_ref()
15293            .is_some_and(|signal| signal.signal_name == self.signal_name)
15294        {
15295            let signal = state
15296                .resume_signal
15297                .take()
15298                .expect("matching resume signal is present");
15299            state.unavailable_cancellation_boundary(&self.parallel_group_path);
15300            return Poll::Ready(Ok(signal.arguments));
15301        }
15302
15303        if !self.opened_wait {
15304            let mut command = serde_json::Map::from_iter([
15305                ("type".to_string(), json!("open_signal_wait")),
15306                ("signal_name".to_string(), json!(self.signal_name)),
15307            ]);
15308            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15309            ctx.apply_scope_membership(&mut command);
15310            state.commands.push(Value::Object(command));
15311            self.opened_wait = true;
15312        }
15313
15314        Poll::Pending
15315    }
15316}
15317
15318impl Future for SignalCall {
15319    type Output = Result<Vec<Value>>;
15320
15321    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15322        match self.poll_avro_value(cx) {
15323            Poll::Ready(Ok(values)) => Poll::Ready(
15324                values
15325                    .into_iter()
15326                    .map(AvroValue::into_json)
15327                    .collect::<Result<Vec<_>>>(),
15328            ),
15329            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15330            Poll::Pending => Poll::Pending,
15331        }
15332    }
15333}
15334
15335#[derive(Clone, Debug)]
15336pub struct ActivityContext {
15337    client: Client,
15338    pub task_id: String,
15339    pub activity_attempt_id: String,
15340    pub lease_owner: String,
15341    pub activity_type: String,
15342    pub attempt_number: u64,
15343    pub task_queue: String,
15344    pub worker_id: String,
15345    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
15346    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
15347    worker_session: Option<WorkerSession>,
15348}
15349
15350impl ActivityContext {
15351    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
15352        if let Some(heartbeats) = &self.local_heartbeats {
15353            return heartbeats
15354                .lock()
15355                .map_err(|_| Error::WorkflowStatePoisoned)?
15356                .record(details);
15357        }
15358        if let Some(guard) = &self.claim_guard {
15359            return guard.heartbeat(self, details).await;
15360        }
15361        if let Some(session) = &self.worker_session {
15362            if !session.active() {
15363                return Err(Error::ActivityExecutionAbandoned(
15364                    "worker-session lease or TTL is no longer active".into(),
15365                ));
15366            }
15367            let result = self
15368                .client
15369                .heartbeat_activity_task_value(
15370                    &self.task_id,
15371                    &self.activity_attempt_id,
15372                    &self.lease_owner,
15373                    details,
15374                )
15375                .await;
15376            return worker_session::settle_activity_heartbeat(
15377                session,
15378                result,
15379                &self.task_id,
15380                &self.activity_attempt_id,
15381                &self.lease_owner,
15382            );
15383        }
15384        self.client
15385            .heartbeat_activity_task(
15386                &self.task_id,
15387                &self.activity_attempt_id,
15388                &self.lease_owner,
15389                details,
15390            )
15391            .await
15392    }
15393}
15394
15395fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
15396    validate_payload_codec(codec)?;
15397    match value {
15398        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
15399            value, codec,
15400        )?)),
15401        None => Ok(AvroValue::Array(Vec::new())),
15402    }
15403}
15404
15405fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
15406    let Some(signal_name) = task
15407        .signal_name
15408        .as_deref()
15409        .filter(|value| !value.is_empty())
15410    else {
15411        return Ok(None);
15412    };
15413    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
15414    let AvroValue::Array(arguments) = decoded else {
15415        unreachable!("normalize_avro_arguments always returns an array");
15416    };
15417
15418    Ok(Some(ResumeSignal {
15419        signal_name: signal_name.to_string(),
15420        arguments,
15421    }))
15422}
15423
15424fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
15425    validate_payload_codec(&task.payload_codec)?;
15426    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
15427    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
15428    for event in &task.history_events {
15429        validate_history_event_payloads(event, &task.payload_codec)?;
15430    }
15431    Ok(())
15432}
15433
15434fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
15435    validate_payload_codec(&task.payload_codec)?;
15436    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
15437}
15438
15439fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
15440    validate_payload_codec(&task.payload_codec)?;
15441    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
15442    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
15443    for event in &task.history_events {
15444        validate_history_event_payloads(event, &task.payload_codec)?;
15445    }
15446
15447    let Some(export) = task.history_export.as_ref() else {
15448        return Ok(());
15449    };
15450    let export_codec = match export.get("payloads") {
15451        Some(payloads) => declared_payload_codec(payloads, "codec")?,
15452        None => None,
15453    }
15454    .unwrap_or(&task.payload_codec);
15455    validate_payload_codec(export_codec)?;
15456
15457    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
15458        for event in events {
15459            let event_type = event
15460                .get("event_type")
15461                .or_else(|| event.get("type"))
15462                .and_then(Value::as_str)
15463                .unwrap_or_default();
15464            if let Some(payload) = event.get("payload") {
15465                validate_history_payloads(event_type, payload, export_codec)?;
15466            }
15467        }
15468    }
15469    for signal in export
15470        .get("signals")
15471        .and_then(Value::as_array)
15472        .into_iter()
15473        .flatten()
15474    {
15475        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
15476        validate_payload_codec(codec)?;
15477        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
15478    }
15479    for activity in export
15480        .get("activities")
15481        .and_then(Value::as_array)
15482        .into_iter()
15483        .flatten()
15484    {
15485        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
15486        validate_payload_codec(codec)?;
15487        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
15488        validate_optional_inbound_payload(activity.get("result"), codec)?;
15489    }
15490    Ok(())
15491}
15492
15493fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
15494    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
15495}
15496
15497fn validate_history_payloads(
15498    event_type: &str,
15499    payload: &Value,
15500    fallback_codec: &str,
15501) -> Result<()> {
15502    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
15503    validate_payload_codec(codec)?;
15504    for field in history_payload_fields(event_type) {
15505        validate_optional_inbound_payload(payload.get(*field), codec)?;
15506    }
15507    Ok(())
15508}
15509
15510const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
15511
15512fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
15513    match event_type {
15514        "ActivityCompleted" => &["result"],
15515        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
15516        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
15517        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
15518        "ChildRunCompleted" => &["result", "output"],
15519        "WorkflowCompleted" => &["output"],
15520        "ServiceCallStarted"
15521        | "ServiceCallCompleted"
15522        | "ServiceCallFailed"
15523        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
15524        _ => &[],
15525    }
15526}
15527
15528fn signal_history_payload(payload: &Value) -> Option<&Value> {
15529    SIGNAL_HISTORY_PAYLOAD_FIELDS
15530        .iter()
15531        .find_map(|field| payload.get(*field))
15532}
15533
15534fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
15535    match value.get(field) {
15536        None => Ok(None),
15537        Some(Value::String(codec)) => Ok(Some(codec)),
15538        Some(_) => Err(invalid_payload_envelope()),
15539    }
15540}
15541
15542fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
15543    validate_payload_codec(codec)?;
15544    if let Some(value) = value.filter(|value| !value.is_null()) {
15545        decode_wire_avro_value(value, codec)?;
15546    }
15547    Ok(())
15548}
15549
15550fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
15551    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
15552        invalid_recorded_history(
15553            "parallel_group_metadata_invalid",
15554            sequence,
15555            "non-empty parallel_group_id",
15556            &payload.to_string(),
15557            "parallel-group history is missing its stable identity",
15558        )
15559    })?;
15560    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
15561        invalid_recorded_history(
15562            "parallel_group_metadata_invalid",
15563            sequence,
15564            "activity, child, timer, signal, condition, or mixed group kind",
15565            &payload.to_string(),
15566            "parallel-group history is missing its group kind",
15567        )
15568    })?;
15569    if !matches!(
15570        kind.as_str(),
15571        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
15572    ) {
15573        return Err(invalid_recorded_history(
15574            "parallel_group_metadata_invalid",
15575            sequence,
15576            "activity, child, timer, signal, condition, or mixed group kind",
15577            &kind,
15578            "parallel-group history contains an unsupported group kind",
15579        ));
15580    }
15581    let base_sequence = payload
15582        .get("parallel_group_base_sequence")
15583        .and_then(value_as_u64)
15584        .filter(|value| *value > 0)
15585        .ok_or_else(|| {
15586            invalid_recorded_history(
15587                "parallel_group_metadata_invalid",
15588                sequence,
15589                "positive parallel_group_base_sequence",
15590                &payload.to_string(),
15591                "parallel-group history contains an invalid base sequence",
15592            )
15593        })?;
15594    let size = payload
15595        .get("parallel_group_size")
15596        .and_then(value_as_u64)
15597        .and_then(|value| usize::try_from(value).ok())
15598        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
15599        .ok_or_else(|| {
15600            invalid_recorded_history(
15601                "parallel_group_metadata_invalid",
15602                sequence,
15603                "bounded positive parallel_group_size",
15604                &payload.to_string(),
15605                "parallel-group history contains an invalid group size",
15606            )
15607        })?;
15608    let index = payload
15609        .get("parallel_group_index")
15610        .and_then(value_as_u64)
15611        .and_then(|value| usize::try_from(value).ok())
15612        .filter(|value| *value < size)
15613        .ok_or_else(|| {
15614            invalid_recorded_history(
15615                "parallel_group_metadata_invalid",
15616                sequence,
15617                "parallel_group_index within group bounds",
15618                &payload.to_string(),
15619                "parallel-group history contains an invalid member index",
15620            )
15621        })?;
15622    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
15623        return Err(invalid_recorded_history(
15624            "parallel_group_metadata_invalid",
15625            sequence,
15626            "base sequence plus member index equals workflow sequence",
15627            &payload.to_string(),
15628            "parallel-group path does not preserve durable workflow position",
15629        ));
15630    }
15631    let mode = payload
15632        .get("parallel_group_mode")
15633        .and_then(Value::as_str)
15634        .unwrap_or("all");
15635    if !matches!(mode, "all" | "select") {
15636        return Err(invalid_recorded_history(
15637            "parallel_group_metadata_invalid",
15638            sequence,
15639            "parallel group mode all or select",
15640            mode,
15641            "parallel-group history contains an unsupported group mode",
15642        ));
15643    }
15644    let expected_id = if mode == "select" {
15645        format!("select-calls:{base_sequence}:{size}")
15646    } else {
15647        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
15648    };
15649    if group_id != expected_id {
15650        return Err(invalid_recorded_history(
15651            "parallel_group_metadata_invalid",
15652            sequence,
15653            &expected_id,
15654            &group_id,
15655            "parallel-group history contains an incompatible stable group ID",
15656        ));
15657    }
15658    let selection_member_key = if mode == "select" {
15659        Some(selection_key_from_value(
15660            payload.get("selection_member_key"),
15661            sequence,
15662        )?)
15663    } else {
15664        None
15665    };
15666    let selection_member_index = if mode == "select" {
15667        Some(required_parallel_usize(
15668            payload,
15669            "selection_member_index",
15670            sequence,
15671        )?)
15672    } else {
15673        None
15674    };
15675    let selection_member_base_sequence = if mode == "select" {
15676        Some(
15677            payload
15678                .get("selection_member_base_sequence")
15679                .and_then(value_as_u64)
15680                .filter(|value| *value >= base_sequence)
15681                .ok_or_else(|| {
15682                    invalid_recorded_history(
15683                        "parallel_group_metadata_invalid",
15684                        sequence,
15685                        "selection member base within its group",
15686                        &payload.to_string(),
15687                        "selection history contains an invalid member base sequence",
15688                    )
15689                })?,
15690        )
15691    } else {
15692        None
15693    };
15694    let selection_member_size = if mode == "select" {
15695        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
15696        if member_size == 0 {
15697            return Err(invalid_recorded_history(
15698                "parallel_group_metadata_invalid",
15699                sequence,
15700                "positive selection member size",
15701                &payload.to_string(),
15702                "selection history contains an invalid member size",
15703            ));
15704        }
15705        Some(member_size)
15706    } else {
15707        None
15708    };
15709    let selection_member_kind = if mode == "select" {
15710        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
15711            invalid_recorded_history(
15712                "parallel_group_metadata_invalid",
15713                sequence,
15714                "selection member operation kind",
15715                &payload.to_string(),
15716                "selection history is missing its authored member kind",
15717            )
15718        })?;
15719        if !matches!(
15720            kind.as_str(),
15721            "activity" | "child" | "timer" | "signal" | "condition" | "group"
15722        ) {
15723            return Err(invalid_recorded_history(
15724                "parallel_group_metadata_invalid",
15725                sequence,
15726                "activity, child, timer, signal, condition, or group selection member kind",
15727                &kind,
15728                "selection history contains an unsupported member kind",
15729            ));
15730        }
15731        Some(kind)
15732    } else {
15733        None
15734    };
15735    if let (Some(member_base), Some(member_size)) =
15736        (selection_member_base_sequence, selection_member_size)
15737    {
15738        let member_end = member_base
15739            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
15740            .ok_or_else(|| {
15741                invalid_recorded_history(
15742                    "parallel_group_metadata_invalid",
15743                    sequence,
15744                    "bounded selection member range",
15745                    &payload.to_string(),
15746                    "selection member range overflowed",
15747                )
15748            })?;
15749        let group_end = base_sequence
15750            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
15751            .unwrap_or(u64::MAX);
15752        if sequence < member_base || sequence >= member_end || member_end > group_end {
15753            return Err(invalid_recorded_history(
15754                "parallel_group_metadata_invalid",
15755                sequence,
15756                "workflow sequence within one bounded selection member",
15757                &payload.to_string(),
15758                "selection member range does not contain its durable leaf",
15759            ));
15760        }
15761    }
15762    Ok(ParallelGroupMetadata {
15763        parallel_group_id: group_id,
15764        parallel_group_kind: kind,
15765        parallel_group_base_sequence: base_sequence,
15766        parallel_group_size: size,
15767        parallel_group_index: index,
15768        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15769        selection_member_key,
15770        selection_member_index,
15771        selection_member_base_sequence,
15772        selection_member_size,
15773        selection_member_kind,
15774    })
15775}
15776
15777fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15778    payload
15779        .get(field)
15780        .and_then(value_as_u64)
15781        .and_then(|value| usize::try_from(value).ok())
15782        .ok_or_else(|| {
15783            invalid_recorded_history(
15784                "parallel_group_metadata_invalid",
15785                sequence,
15786                &format!("non-negative integer {field}"),
15787                &payload.to_string(),
15788                "selection history contains invalid member metadata",
15789            )
15790        })
15791}
15792
15793fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15794    match value {
15795        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15796        Some(value) => value_as_u64(value)
15797            .and_then(|value| usize::try_from(value).ok())
15798            .map(SelectionKey::Index)
15799            .ok_or_else(|| {
15800                invalid_recorded_history(
15801                    "selection_member_key_invalid",
15802                    sequence,
15803                    "non-empty string or non-negative integer member key",
15804                    &value.to_string(),
15805                    "selection history contains an invalid member key",
15806                )
15807            }),
15808        None => Err(invalid_recorded_history(
15809            "selection_member_key_missing",
15810            sequence,
15811            "selection_member_key",
15812            "<missing>",
15813            "selection history is missing its stable member key",
15814        )),
15815    }
15816}
15817
15818fn recorded_parallel_group_path(
15819    events: &[&HistoryEvent],
15820    sequence: u64,
15821) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15822    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15823    for event in events {
15824        let payload = &event.payload;
15825        let has_metadata = payload.get("parallel_group_path").is_some()
15826            || payload.get("parallel_group_id").is_some()
15827            || payload.get("parallel_group_kind").is_some()
15828            || payload.get("parallel_group_base_sequence").is_some()
15829            || payload.get("parallel_group_size").is_some()
15830            || payload.get("parallel_group_index").is_some()
15831            || payload.get("parallel_group_mode").is_some()
15832            || payload.get("selection_member_key").is_some();
15833        if !has_metadata {
15834            continue;
15835        }
15836
15837        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15838        let path = match payload.get("parallel_group_path") {
15839            None => vec![top_level.clone()],
15840            Some(Value::Array(entries)) if !entries.is_empty() => entries
15841                .iter()
15842                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15843                .collect::<Result<Vec<_>>>()?,
15844            Some(value) => {
15845                return Err(invalid_recorded_history(
15846                    "parallel_group_metadata_invalid",
15847                    sequence,
15848                    "non-empty parallel_group_path list",
15849                    &value.to_string(),
15850                    "parallel-group history contains an invalid group path",
15851                ));
15852            }
15853        };
15854        if path.last() != Some(&top_level) {
15855            return Err(invalid_recorded_history(
15856                "parallel_group_metadata_invalid",
15857                sequence,
15858                &serde_json::to_string(&path.last()).unwrap_or_default(),
15859                &serde_json::to_string(&top_level).unwrap_or_default(),
15860                "parallel-group top-level fields do not match the innermost path entry",
15861            ));
15862        }
15863        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15864            return Err(invalid_recorded_history(
15865                "parallel_group_history_conflict",
15866                sequence,
15867                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15868                &serde_json::to_string(&path).unwrap_or_default(),
15869                "parallel-group metadata changed between scheduling and resolution history",
15870            ));
15871        }
15872        recorded = Some(path);
15873    }
15874    Ok(recorded)
15875}
15876
15877fn recorded_commands(
15878    events: &[HistoryEvent],
15879    fallback_codec: &str,
15880    parent: WorkflowIdentity,
15881) -> Result<Vec<RecordedCommand>> {
15882    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15883    let mut last_new_sequence = None;
15884
15885    for event in events {
15886        let is_activity = matches!(
15887            event.event_type.as_str(),
15888            "ActivityScheduled"
15889                | "ActivityStarted"
15890                | "ActivityHeartbeatRecorded"
15891                | "ActivityRetryScheduled"
15892                | "ActivityCompleted"
15893                | "ActivityFailed"
15894                | "ActivityCancelled"
15895                | "ActivityTimedOut"
15896        );
15897        let is_workflow_timer = matches!(
15898            event.event_type.as_str(),
15899            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15900        ) && !is_internal_timer_event(event);
15901        let is_child_workflow = matches!(
15902            event.event_type.as_str(),
15903            "ChildWorkflowScheduled"
15904                | "ChildRunStarted"
15905                | "ChildRunCompleted"
15906                | "ChildRunFailed"
15907                | "ChildRunCancelled"
15908                | "ChildRunTerminated"
15909        );
15910        let is_signal_wait = is_recorded_signal_wait_event(event);
15911        let is_condition_wait = is_recorded_condition_wait_event(event);
15912        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15913        let is_side_effect = event.event_type == "SideEffectRecorded";
15914        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15915        let is_memo = event.event_type == "MemoUpserted";
15916        if !is_activity
15917            && !is_workflow_timer
15918            && !is_child_workflow
15919            && !is_signal_wait
15920            && !is_condition_wait
15921            && !is_search_attributes
15922            && !is_side_effect
15923            && !is_version_marker
15924            && !is_memo
15925        {
15926            continue;
15927        }
15928
15929        let sequence = durable_event_sequence(event).ok_or_else(|| {
15930            Error::NonDeterministicReplay(ReplayFailure::new(
15931                "durable_command_sequence_missing",
15932                None,
15933                Some("positive workflow sequence".to_string()),
15934                Some(event.event_type.clone()),
15935                "durable command history event has no workflow sequence",
15936            ))
15937        })?;
15938        if sequence == 0 {
15939            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15940                "durable_command_sequence_invalid",
15941                Some(sequence),
15942                Some("positive workflow sequence".to_string()),
15943                Some(sequence.to_string()),
15944                "durable command history uses an invalid workflow sequence",
15945            )));
15946        }
15947        if !events_by_sequence.contains_key(&sequence) {
15948            if let Some(previous) = last_new_sequence {
15949                if sequence < previous {
15950                    return Err(invalid_recorded_history(
15951                        "durable_command_sequence_mismatch",
15952                        sequence,
15953                        &format!("workflow sequence greater than {previous}"),
15954                        &sequence.to_string(),
15955                        "durable commands are not strictly ordered by their recorded workflow sequence",
15956                    ));
15957                }
15958            }
15959            last_new_sequence = Some(sequence);
15960        }
15961        events_by_sequence.entry(sequence).or_default().push(event);
15962    }
15963
15964    let commands: Vec<RecordedCommand> = events_by_sequence
15965        .into_iter()
15966        .map(|(sequence, sequence_events)| {
15967            let activity_events: Vec<_> = sequence_events
15968                .iter()
15969                .copied()
15970                .filter(|event| event.event_type.starts_with("Activity"))
15971                .collect();
15972            let timer_events: Vec<_> = sequence_events
15973                .iter()
15974                .copied()
15975                .filter(|event| event.event_type.starts_with("Timer"))
15976                .collect();
15977            let child_events: Vec<_> = sequence_events
15978                .iter()
15979                .copied()
15980                .filter(|event| {
15981                    event.event_type == "ChildWorkflowScheduled"
15982                        || event.event_type.starts_with("ChildRun")
15983                })
15984                .collect();
15985            let signal_wait_events: Vec<_> = sequence_events
15986                .iter()
15987                .copied()
15988                .filter(|event| is_recorded_signal_wait_event(event))
15989                .collect();
15990            let condition_wait_events: Vec<_> = sequence_events
15991                .iter()
15992                .copied()
15993                .filter(|event| is_recorded_condition_wait_event(event))
15994                .collect();
15995            let search_attribute_events: Vec<_> = sequence_events
15996                .iter()
15997                .copied()
15998                .filter(|event| event.event_type == "SearchAttributesUpserted")
15999                .collect();
16000            let side_effect_events: Vec<_> = sequence_events
16001                .iter()
16002                .copied()
16003                .filter(|event| event.event_type == "SideEffectRecorded")
16004                .collect();
16005            let version_marker_events: Vec<_> = sequence_events
16006                .iter()
16007                .copied()
16008                .filter(|event| event.event_type == "VersionMarkerRecorded")
16009                .collect();
16010            let memo_events: Vec<_> = sequence_events
16011                .iter()
16012                .copied()
16013                .filter(|event| event.event_type == "MemoUpserted")
16014                .collect();
16015
16016            let command_kind_count = usize::from(!activity_events.is_empty())
16017                + usize::from(!timer_events.is_empty())
16018                + usize::from(!child_events.is_empty())
16019                + usize::from(!signal_wait_events.is_empty())
16020                + usize::from(!condition_wait_events.is_empty())
16021                + usize::from(!search_attribute_events.is_empty())
16022                + usize::from(!side_effect_events.is_empty())
16023                + usize::from(!version_marker_events.is_empty())
16024                + usize::from(!memo_events.is_empty());
16025            if command_kind_count > 1 {
16026                let actual = [
16027                    (!activity_events.is_empty()).then_some("activity"),
16028                    (!timer_events.is_empty()).then_some("timer"),
16029                    (!child_events.is_empty()).then_some("child workflow"),
16030                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16031                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16032                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16033                    (!side_effect_events.is_empty()).then_some("side effect"),
16034                    (!version_marker_events.is_empty()).then_some("version marker"),
16035                    (!memo_events.is_empty()).then_some("memo upsert"),
16036                ]
16037                .into_iter()
16038                .flatten()
16039                .collect::<Vec<_>>()
16040                .join(" and ");
16041                return Err(invalid_recorded_history(
16042                    "durable_command_sequence_collision",
16043                    sequence,
16044                    "one durable command kind",
16045                    &actual,
16046                    "one workflow sequence records more than one durable command kind",
16047                ));
16048            }
16049
16050            if !activity_events.is_empty() {
16051                let parallel_group_path =
16052                    recorded_parallel_group_path(&activity_events, sequence)?;
16053                let scheduled_count = activity_events
16054                    .iter()
16055                    .filter(|event| event.event_type == "ActivityScheduled")
16056                    .count();
16057                if scheduled_count > 1 {
16058                    return Err(invalid_recorded_history(
16059                        "duplicate_activity_schedule",
16060                        sequence,
16061                        "at most one ActivityScheduled event",
16062                        "multiple ActivityScheduled events",
16063                        "activity history schedules more than one command at one workflow sequence",
16064                    ));
16065                }
16066                let activity_type = activity_events.iter().find_map(|event| {
16067                    event
16068                        .payload
16069                        .get("activity_type")
16070                        .or_else(|| event.payload.get("activity_name"))
16071                        .and_then(Value::as_str)
16072                        .map(str::to_string)
16073                });
16074                if activity_events.iter().filter_map(|event| {
16075                    event
16076                        .payload
16077                        .get("activity_type")
16078                        .or_else(|| event.payload.get("activity_name"))
16079                        .and_then(Value::as_str)
16080                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16081                    return Err(invalid_recorded_history(
16082                        "activity_identity_mismatch",
16083                        sequence,
16084                        activity_type.as_deref().unwrap_or("one activity identity"),
16085                        "conflicting activity identities",
16086                        "activity lifecycle events at one workflow sequence disagree on identity",
16087                    ));
16088                }
16089                let terminal: Vec<_> = activity_events
16090                    .iter()
16091                    .copied()
16092                    .filter(|event| {
16093                        matches!(
16094                            event.event_type.as_str(),
16095                            "ActivityCompleted"
16096                                | "ActivityFailed"
16097                                | "ActivityCancelled"
16098                                | "ActivityTimedOut"
16099                        )
16100                    })
16101                    .collect();
16102                let duplicate_delivery = terminal.first().is_some_and(|first| {
16103                    terminal.iter().all(|event| {
16104                        event.event_type == first.event_type && event.payload == first.payload
16105                    })
16106                });
16107                if terminal.len() > 1 && !duplicate_delivery {
16108                    return Err(invalid_recorded_history(
16109                        "duplicate_activity_terminal_event",
16110                        sequence,
16111                        "at most one terminal activity event",
16112                        "multiple terminal activity events",
16113                        "activity history settles one command more than once",
16114                    ));
16115                }
16116                let outcome = terminal
16117                    .first()
16118                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16119                    .transpose()?;
16120                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16121                let activity_snapshot = activity_events
16122                    .iter()
16123                    .find(|event| event.event_type == "ActivityScheduled")
16124                    .and_then(|event| event.payload.get("activity"))
16125                    .and_then(Value::as_object);
16126                let options = Some(match activity_snapshot {
16127                    Some(activity) => RecordedActivityOptions {
16128                        task_queue: recorded_optional_string(activity, "queue"),
16129                        execution_mode,
16130                        retry_policy: recorded_activity_retry_snapshot(
16131                            activity.get("retry_policy"),
16132                        ),
16133                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16134                    },
16135                    None => RecordedActivityOptions {
16136                        task_queue: RecordedSnapshotValue::Unknown,
16137                        execution_mode,
16138                        retry_policy: recorded_activity_retry_snapshot(None),
16139                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16140                    },
16141                });
16142                return Ok(RecordedCommand::Activity {
16143                    sequence,
16144                    activity_type,
16145                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16146                    options,
16147                    outcome,
16148                    parallel_group_path,
16149                });
16150            }
16151
16152            if !child_events.is_empty() {
16153                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16154                let scheduled: Vec<_> = child_events
16155                    .iter()
16156                    .copied()
16157                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16158                    .collect();
16159                if scheduled.len() != 1 {
16160                    return Err(invalid_recorded_history(
16161                        "child_workflow_schedule_missing_or_duplicate",
16162                        sequence,
16163                        "one ChildWorkflowScheduled event",
16164                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
16165                        "child workflow replay requires exactly one recorded schedule event",
16166                    ));
16167                }
16168                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
16169                let workflow_type = child_events.iter().find_map(|event| {
16170                    event
16171                        .payload
16172                        .get("child_workflow_type")
16173                        .or_else(|| event.payload.get("workflow_type"))
16174                        .and_then(Value::as_str)
16175                        .filter(|value| !value.is_empty())
16176                        .map(str::to_string)
16177                });
16178                if child_events
16179                    .iter()
16180                    .filter_map(|event| {
16181                        event
16182                            .payload
16183                            .get("child_workflow_type")
16184                            .or_else(|| event.payload.get("workflow_type"))
16185                            .and_then(Value::as_str)
16186                    })
16187                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
16188                {
16189                    return Err(invalid_recorded_history(
16190                        "child_workflow_identity_mismatch",
16191                        sequence,
16192                        workflow_type
16193                            .as_deref()
16194                            .unwrap_or("one child workflow type"),
16195                        "conflicting child workflow types",
16196                        "child workflow lifecycle events at one sequence disagree on type",
16197                    ));
16198                }
16199                let mut outcomes = child_workflow_outcomes(
16200                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
16201                    fallback_codec,
16202                    parent.clone(),
16203                )?;
16204                let terminal_events = child_events
16205                    .iter()
16206                    .copied()
16207                    .filter(|event| event.event_type.starts_with("ChildRun"))
16208                    .collect::<Vec<_>>();
16209                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
16210                    terminal_events.iter().all(|event| {
16211                        event.event_type == first.event_type && event.payload == first.payload
16212                    })
16213                });
16214                if outcomes.len() > 1 && !duplicate_delivery {
16215                    return Err(invalid_recorded_history(
16216                        "duplicate_child_workflow_terminal_event",
16217                        sequence,
16218                        "at most one terminal child event",
16219                        "multiple terminal child events",
16220                        "child workflow history settles one command more than once",
16221                    ));
16222                }
16223                return Ok(RecordedCommand::ChildWorkflow {
16224                    sequence,
16225                    workflow_type,
16226                    policies,
16227                    outcome: outcomes.pop(),
16228                    parallel_group_path,
16229                });
16230            }
16231
16232            if !signal_wait_events.is_empty() {
16233                let opened: Vec<_> = signal_wait_events
16234                    .iter()
16235                    .copied()
16236                    .filter(|event| event.event_type == "SignalWaitOpened")
16237                    .collect();
16238                if opened.len() != 1 {
16239                    return Err(invalid_recorded_history(
16240                        "signal_wait_open_missing_or_duplicate",
16241                        sequence,
16242                        "one SignalWaitOpened event",
16243                        &format!("{} SignalWaitOpened events", opened.len()),
16244                        "signal replay requires exactly one canonical wait-open event",
16245                    ));
16246                }
16247
16248                let applied: Vec<_> = signal_wait_events
16249                    .iter()
16250                    .copied()
16251                    .filter(|event| event.event_type == "SignalApplied")
16252                    .collect();
16253                if applied.len() > 1 {
16254                    return Err(invalid_recorded_history(
16255                        "duplicate_signal_wait_apply",
16256                        sequence,
16257                        "at most one SignalApplied event",
16258                        "multiple SignalApplied events",
16259                        "signal history applies one durable wait more than once",
16260                    ));
16261                }
16262
16263                let signal_names = signal_wait_events
16264                    .iter()
16265                    .map(|event| required_signal_wait_name(event, sequence))
16266                    .collect::<Result<Vec<_>>>()?;
16267                let signal_name = signal_names
16268                    .first()
16269                    .expect("signal wait events are not empty")
16270                    .clone();
16271                if signal_names.iter().any(|candidate| candidate != &signal_name) {
16272                    return Err(invalid_recorded_history(
16273                        "signal_wait_identity_mismatch",
16274                        sequence,
16275                        &signal_name,
16276                        "conflicting signal names",
16277                        "signal wait lifecycle events at one workflow sequence disagree on identity",
16278                    ));
16279                }
16280                let value = applied
16281                    .first()
16282                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
16283                    .transpose()?;
16284                return Ok(RecordedCommand::SignalWait {
16285                    sequence,
16286                    signal_name,
16287                    value,
16288                    parallel_group_path: recorded_parallel_group_path(
16289                        &signal_wait_events,
16290                        sequence,
16291                    )?,
16292                });
16293            }
16294
16295            if !condition_wait_events.is_empty() {
16296                return recorded_condition_wait(
16297                    sequence,
16298                    &condition_wait_events,
16299                    events,
16300                );
16301            }
16302
16303            if !search_attribute_events.is_empty() {
16304                if search_attribute_events.len() != 1 {
16305                    return Err(invalid_recorded_history(
16306                        "duplicate_search_attribute_update",
16307                        sequence,
16308                        "one SearchAttributesUpserted event",
16309                        &format!(
16310                            "{} SearchAttributesUpserted events",
16311                            search_attribute_events.len()
16312                        ),
16313                        "search-attribute history records one workflow command more than once",
16314                    ));
16315                }
16316                let payload = &search_attribute_events[0].payload;
16317                let attributes = payload
16318                    .get("attributes")
16319                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
16320                    .cloned()
16321                    .ok_or_else(|| {
16322                        invalid_recorded_history(
16323                            "search_attribute_update_missing",
16324                            sequence,
16325                            "non-empty attributes object",
16326                            "missing or invalid attributes",
16327                            "search-attribute history is missing its recorded mutation",
16328                        )
16329                    })?;
16330                let attribute_types =
16331                    recorded_search_attribute_types(payload, &attributes, sequence)?;
16332                return Ok(RecordedCommand::SearchAttributes {
16333                    sequence,
16334                    attributes,
16335                    attribute_types,
16336                });
16337            }
16338
16339            if !side_effect_events.is_empty() {
16340                if side_effect_events.len() != 1 {
16341                    return Err(invalid_recorded_history(
16342                        "duplicate_side_effect_record",
16343                        sequence,
16344                        "one SideEffectRecorded event",
16345                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
16346                        "side-effect history records one workflow command more than once",
16347                    ));
16348                }
16349                let event = side_effect_events[0];
16350                let result = event.payload.get("result").ok_or_else(|| {
16351                    invalid_recorded_history(
16352                        "side_effect_result_missing",
16353                        sequence,
16354                        "recorded result payload",
16355                        "missing result",
16356                        "side-effect history is missing its recorded value",
16357                    )
16358                })?;
16359                let has_published_envelope = result.as_str().is_some()
16360                    || result.as_object().is_some_and(|envelope| {
16361                        envelope.get("codec").and_then(Value::as_str).is_some()
16362                            && envelope.get("blob").and_then(Value::as_str).is_some()
16363                    });
16364                if !has_published_envelope {
16365                    return Err(invalid_recorded_history(
16366                        "side_effect_payload_malformed",
16367                        sequence,
16368                        "payload blob or {codec, blob} envelope",
16369                        &result.to_string(),
16370                        "side-effect history result does not use a published payload envelope",
16371                    ));
16372                }
16373                let codec = event
16374                    .payload
16375                    .get("payload_codec")
16376                    .and_then(Value::as_str)
16377                    .unwrap_or(fallback_codec);
16378                let value = decode_wire_avro_value(result, codec).map_err(|error| {
16379                    if error.to_string().contains("unsupported_payload_codec") {
16380                        return error;
16381                    }
16382
16383                    invalid_recorded_history(
16384                        "side_effect_payload_incompatible",
16385                        sequence,
16386                        &format!("valid {codec} payload envelope"),
16387                        &error.to_string(),
16388                        "side-effect history payload cannot be decoded with its recorded codec",
16389                    )
16390                })?;
16391                return Ok(RecordedCommand::SideEffect { sequence, value });
16392            }
16393
16394            if !version_marker_events.is_empty() {
16395                if version_marker_events.len() != 1 {
16396                    return Err(invalid_recorded_history(
16397                        "duplicate_version_marker_record",
16398                        sequence,
16399                        "one VersionMarkerRecorded event",
16400                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
16401                        "version-marker history records one workflow command more than once",
16402                    ));
16403                }
16404                let payload = &version_marker_events[0].payload;
16405                let change_id = payload
16406                    .get("change_id")
16407                    .and_then(Value::as_str)
16408                    .filter(|value| !value.is_empty())
16409                    .map(str::to_string)
16410                    .ok_or_else(|| {
16411                        invalid_recorded_history(
16412                            "version_marker_field_missing",
16413                            sequence,
16414                            "non-empty change_id",
16415                            "missing or invalid change_id",
16416                            "version-marker history is missing its stable change ID",
16417                        )
16418                    })?;
16419                let version = required_version_i32(payload, "version", sequence)?;
16420                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
16421                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
16422                if min_supported > max_supported || version < min_supported || version > max_supported {
16423                    return Err(invalid_recorded_history(
16424                        "version_marker_history_range_invalid",
16425                        sequence,
16426                        "min_supported <= version <= max_supported",
16427                        &format!("{min_supported} <= {version} <= {max_supported}"),
16428                        "recorded version marker contains an internally incompatible range",
16429                    ));
16430                }
16431                return Ok(RecordedCommand::VersionMarker {
16432                    sequence,
16433                    change_id,
16434                    version,
16435                });
16436            }
16437
16438            if !memo_events.is_empty() {
16439                if memo_events.len() != 1 {
16440                    return Err(invalid_recorded_history(
16441                        "duplicate_memo_upsert_record",
16442                        sequence,
16443                        "one MemoUpserted event",
16444                        &format!("{} MemoUpserted events", memo_events.len()),
16445                        "memo history records one workflow update more than once",
16446                    ));
16447                }
16448                let payload = &memo_events[0].payload;
16449                let entries = payload.get("entries").cloned().ok_or_else(|| {
16450                    invalid_recorded_history(
16451                        "memo_entries_missing",
16452                        sequence,
16453                        "memo entries object",
16454                        "missing entries",
16455                        "MemoUpserted history is missing replay identity entries",
16456                    )
16457                })?;
16458                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
16459                    invalid_recorded_history(
16460                        "memo_entries_invalid",
16461                        sequence,
16462                        "valid canonical memo entries",
16463                        &error.to_string(),
16464                        "MemoUpserted history contains invalid replay identity entries",
16465                    )
16466                })?;
16467                let merged = payload.get("merged").cloned().ok_or_else(|| {
16468                    invalid_recorded_history(
16469                        "memo_merged_projection_missing",
16470                        sequence,
16471                        "merged memo projection",
16472                        "missing merged",
16473                        "MemoUpserted history is missing its merged projection",
16474                    )
16475                })?;
16476                decode_memo_history_map(&merged, false).map_err(|error| {
16477                    invalid_recorded_history(
16478                        "memo_merged_projection_invalid",
16479                        sequence,
16480                        "valid merged memo projection",
16481                        &error.to_string(),
16482                        "MemoUpserted history contains an invalid merged projection",
16483                    )
16484                })?;
16485
16486                return Ok(RecordedCommand::Memo { sequence, entries });
16487            }
16488            let scheduled: Vec<_> = timer_events
16489                .iter()
16490                .copied()
16491                .filter(|event| event.event_type == "TimerScheduled")
16492                .collect();
16493            let fired: Vec<_> = timer_events
16494                .iter()
16495                .copied()
16496                .filter(|event| event.event_type == "TimerFired")
16497                .collect();
16498            if scheduled.len() != 1 {
16499                return Err(invalid_recorded_history(
16500                    "timer_schedule_missing_or_duplicate",
16501                    sequence,
16502                    "one TimerScheduled event",
16503                    &format!("{} TimerScheduled events", scheduled.len()),
16504                    "timer replay requires exactly one recorded schedule event",
16505                ));
16506            }
16507            if fired.len() > 1 {
16508                return Err(invalid_recorded_history(
16509                    "duplicate_timer_fire",
16510                    sequence,
16511                    "at most one TimerFired event",
16512                    "multiple TimerFired events",
16513                    "timer history contains more than one fire event for a workflow sequence",
16514                ));
16515            }
16516
16517            let scheduled = scheduled[0];
16518            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16519            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16520            if let Some(fired) = fired.first() {
16521                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16522                if fired_timer_id != timer_id {
16523                    return Err(invalid_recorded_history(
16524                        "timer_identity_mismatch",
16525                        sequence,
16526                        &timer_id,
16527                        &fired_timer_id,
16528                        "TimerFired does not correspond to the recorded TimerScheduled event",
16529                    ));
16530                }
16531                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16532                if fired_delay != delay_seconds {
16533                    return Err(invalid_recorded_history(
16534                        "timer_history_delay_mismatch",
16535                        sequence,
16536                        &delay_seconds.to_string(),
16537                        &fired_delay.to_string(),
16538                        "TimerScheduled and TimerFired record different delays",
16539                    ));
16540                }
16541            }
16542
16543            Ok(RecordedCommand::Timer {
16544                sequence,
16545                delay_seconds,
16546                fired: !fired.is_empty(),
16547                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
16548            })
16549        })
16550        .collect::<Result<_>>()?;
16551
16552    let mut marker_decisions = HashMap::new();
16553    for command in &commands {
16554        if let RecordedCommand::VersionMarker {
16555            sequence,
16556            change_id,
16557            version,
16558        } = command
16559        {
16560            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
16561                if version != first_version {
16562                    return Err(invalid_recorded_history(
16563                        "version_marker_conflict",
16564                        *sequence,
16565                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
16566                        &format!("version {version} at sequence {sequence}"),
16567                        "workflow history contains conflicting decisions for one stable change ID",
16568                    ));
16569                }
16570            } else {
16571                marker_decisions.insert(change_id.clone(), (*version, *sequence));
16572            }
16573        }
16574    }
16575
16576    Ok(commands)
16577}
16578
16579fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
16580    payload
16581        .get(field)
16582        .and_then(Value::as_i64)
16583        .and_then(|value| i32::try_from(value).ok())
16584        .ok_or_else(|| {
16585            invalid_recorded_history(
16586                "version_marker_field_missing",
16587                sequence,
16588                &format!("integer {field}"),
16589                "missing or out-of-range integer",
16590                "version-marker history is missing a required integer field",
16591            )
16592        })
16593}
16594
16595fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
16596    event
16597        .payload
16598        .get("sequence")
16599        .or_else(|| event.payload.get("workflow_sequence"))
16600        .or_else(|| event.raw.get("sequence"))
16601        .or_else(|| event.raw.get("workflow_sequence"))
16602        .and_then(value_as_u64)
16603}
16604
16605fn is_internal_timer_event(event: &HistoryEvent) -> bool {
16606    matches!(
16607        event
16608            .payload
16609            .get("timer_kind")
16610            .or_else(|| event.raw.get("timer_kind"))
16611            .and_then(Value::as_str),
16612        Some("condition_timeout" | "signal_timeout")
16613    )
16614}
16615
16616fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
16617    matches!(
16618        event.event_type.as_str(),
16619        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16620    )
16621}
16622
16623fn recorded_condition_wait(
16624    sequence: u64,
16625    condition_events: &[&HistoryEvent],
16626    all_events: &[HistoryEvent],
16627) -> Result<RecordedCommand> {
16628    let opened = condition_events
16629        .iter()
16630        .copied()
16631        .filter(|event| event.event_type == "ConditionWaitOpened")
16632        .collect::<Vec<_>>();
16633    if opened.len() != 1 {
16634        return Err(invalid_recorded_history(
16635            "condition_wait_open_missing_or_duplicate",
16636            sequence,
16637            "one ConditionWaitOpened event",
16638            &format!("{} ConditionWaitOpened events", opened.len()),
16639            "condition replay requires exactly one canonical wait-open event",
16640        ));
16641    }
16642    let terminal = condition_events
16643        .iter()
16644        .copied()
16645        .filter(|event| {
16646            matches!(
16647                event.event_type.as_str(),
16648                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16649            )
16650        })
16651        .collect::<Vec<_>>();
16652    if terminal.len() > 1 {
16653        return Err(invalid_recorded_history(
16654            "duplicate_condition_wait_terminal_event",
16655            sequence,
16656            "at most one condition terminal event",
16657            "multiple condition terminal events",
16658            "condition history settles one durable wait more than once",
16659        ));
16660    }
16661
16662    let opened = opened[0];
16663    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
16664    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
16665    for event in condition_events
16666        .iter()
16667        .copied()
16668        .filter(|event| !std::ptr::eq(*event, opened))
16669    {
16670        let event_wait_id = required_condition_wait_id(event, sequence)?;
16671        if event_wait_id != condition_wait_id {
16672            return Err(invalid_recorded_history(
16673                "condition_wait_id_mismatch",
16674                sequence,
16675                &condition_wait_id,
16676                &event_wait_id,
16677                "condition lifecycle events at one sequence disagree on wait identity",
16678            ));
16679        }
16680        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
16681        if event_occurrence_id != occurrence_id {
16682            return Err(invalid_recorded_history(
16683                "condition_wait_occurrence_history_mismatch",
16684                sequence,
16685                &occurrence_id,
16686                &event_occurrence_id,
16687                "condition lifecycle events at one sequence disagree on authored occurrence identity",
16688            ));
16689        }
16690    }
16691
16692    let condition_key = optional_non_empty_history_string(opened, "condition_key");
16693    let predicate_identity = opened
16694        .payload
16695        .get("condition_definition_fingerprint")
16696        .and_then(Value::as_str)
16697        .filter(|value| !value.is_empty())
16698        .map(str::to_string)
16699        .ok_or_else(|| {
16700            invalid_recorded_history(
16701                "condition_wait_predicate_fingerprint_missing",
16702                sequence,
16703                "non-empty condition_definition_fingerprint",
16704                &opened.event_type,
16705                "canonical condition history is missing its predicate identity",
16706            )
16707        })?;
16708    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
16709    for event in condition_events
16710        .iter()
16711        .copied()
16712        .filter(|event| !std::ptr::eq(*event, opened))
16713    {
16714        for (field, opened_value) in [
16715            ("condition_key", condition_key.as_deref()),
16716            (
16717                "condition_definition_fingerprint",
16718                Some(predicate_identity.as_str()),
16719            ),
16720        ] {
16721            if let Some(value) = optional_non_empty_history_string(event, field) {
16722                if opened_value.is_some_and(|opened_value| opened_value != value) {
16723                    return Err(invalid_recorded_history(
16724                        "condition_wait_definition_history_mismatch",
16725                        sequence,
16726                        opened_value.unwrap_or_default(),
16727                        &value,
16728                        "condition lifecycle events disagree on the recorded definition",
16729                    ));
16730                }
16731            }
16732        }
16733        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
16734            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
16735                return Err(invalid_recorded_history(
16736                    "condition_wait_definition_history_mismatch",
16737                    sequence,
16738                    &format!("{}s", timeout_seconds.unwrap_or_default()),
16739                    &format!("{event_timeout}s"),
16740                    "condition lifecycle events disagree on the recorded timeout",
16741                ));
16742            }
16743        }
16744    }
16745
16746    let timeout_timer_events = all_events
16747        .iter()
16748        .filter(|event| {
16749            matches!(
16750                event.event_type.as_str(),
16751                "TimerScheduled" | "TimerCancelled" | "TimerFired"
16752            ) && event.payload.get("timer_kind").and_then(Value::as_str)
16753                == Some("condition_timeout")
16754                && event
16755                    .payload
16756                    .get("condition_wait_id")
16757                    .and_then(Value::as_str)
16758                    == Some(condition_wait_id.as_str())
16759        })
16760        .collect::<Vec<_>>();
16761    let scheduled = timeout_timer_events
16762        .iter()
16763        .copied()
16764        .filter(|event| event.event_type == "TimerScheduled")
16765        .collect::<Vec<_>>();
16766    let fired = timeout_timer_events
16767        .iter()
16768        .copied()
16769        .filter(|event| event.event_type == "TimerFired")
16770        .collect::<Vec<_>>();
16771    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16772        return Err(invalid_recorded_history(
16773            "condition_wait_timeout_history_invalid",
16774            sequence,
16775            "one timeout schedule and at most one fire",
16776            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16777            "condition timeout history has a missing or duplicate lifecycle event",
16778        ));
16779    }
16780    if let Some(scheduled) = scheduled.first() {
16781        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16782        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16783        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16784            return Err(invalid_recorded_history(
16785                "condition_wait_timeout_delay_mismatch",
16786                sequence,
16787                &format!("{}s", timeout_seconds.unwrap_or_default()),
16788                &format!("{delay_seconds}s"),
16789                "condition timeout timer differs from the wait definition",
16790            ));
16791        }
16792        if let Some(fired) = fired.first() {
16793            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16794            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16795            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16796                return Err(invalid_recorded_history(
16797                    "condition_wait_timeout_identity_mismatch",
16798                    sequence,
16799                    &format!("{timer_id}:{delay_seconds}s"),
16800                    &format!("{fired_timer_id}:{fired_delay}s"),
16801                    "condition timeout fire does not match its durable schedule",
16802                ));
16803            }
16804        }
16805    }
16806
16807    let result = terminal.first().map(|event| {
16808        if event.event_type == "ConditionWaitTimedOut" {
16809            ConditionWaitResult::TimedOut
16810        } else {
16811            ConditionWaitResult::Satisfied
16812        }
16813    });
16814    let result = if !fired.is_empty() {
16815        if result == Some(ConditionWaitResult::Satisfied) {
16816            return Err(invalid_recorded_history(
16817                "condition_wait_terminal_conflict",
16818                sequence,
16819                "one satisfied or timed-out outcome",
16820                "satisfied event and fired timeout",
16821                "condition history records conflicting terminal outcomes",
16822            ));
16823        }
16824        Some(ConditionWaitResult::TimedOut)
16825    } else {
16826        result
16827    };
16828
16829    Ok(RecordedCommand::ConditionWait {
16830        sequence,
16831        occurrence_id,
16832        condition_key,
16833        predicate_identity,
16834        timeout_seconds,
16835        result,
16836        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16837    })
16838}
16839
16840fn recorded_condition_group_path(
16841    condition_events: &[&HistoryEvent],
16842    all_events: &[HistoryEvent],
16843    sequence: u64,
16844) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16845    let opened = condition_events
16846        .iter()
16847        .copied()
16848        .find(|event| event.event_type == "ConditionWaitOpened")
16849        .expect("canonical condition opener is validated first");
16850    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16851    let previous_events = all_events
16852        .iter()
16853        .take_while(|event| !std::ptr::eq(*event, opened))
16854        .collect::<Vec<_>>();
16855    let originals = previous_events
16856        .iter()
16857        .copied()
16858        .filter(|event| event.event_type == "ConditionWaitOpened")
16859        .filter(|event| {
16860            event
16861                .payload
16862                .get("condition_wait_occurrence_id")
16863                .and_then(Value::as_str)
16864                == Some(occurrence.as_str())
16865        })
16866        .collect::<Vec<_>>();
16867    let Some(original) = originals.first().copied() else {
16868        return recorded_parallel_group_path(condition_events, sequence);
16869    };
16870    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16871    if authored_sequence == sequence {
16872        return recorded_parallel_group_path(condition_events, sequence);
16873    }
16874    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16875    if original_path.is_none() {
16876        return recorded_parallel_group_path(condition_events, sequence);
16877    }
16878    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16879    let identity_matches = [
16880        "condition_key",
16881        "condition_definition_fingerprint",
16882        "timeout_seconds",
16883    ]
16884    .iter()
16885    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16886    let previous = originals
16887        .iter()
16888        .copied()
16889        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16890        .max_by_key(|event| durable_event_sequence(event));
16891    let previously_satisfied = previous.is_some_and(|previous| {
16892        previous_events.iter().any(|event| {
16893            event.event_type == "ConditionWaitSatisfied"
16894                && event.payload.get("condition_wait_id")
16895                    == previous.payload.get("condition_wait_id")
16896                && event.payload.get("condition_wait_occurrence_id")
16897                    == previous.payload.get("condition_wait_occurrence_id")
16898                && durable_event_sequence(event) == durable_event_sequence(previous)
16899        })
16900    });
16901    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16902        return Err(invalid_recorded_history(
16903            "condition_wait_group_reopen_mismatch",
16904            sequence,
16905            "same authored condition and group path after a satisfied physical wait",
16906            &opened.payload.to_string(),
16907            "grouped condition reopen has no matching recorded predecessor",
16908        ));
16909    }
16910    Ok(reopened_path)
16911}
16912
16913fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16914    event
16915        .payload
16916        .get("condition_wait_occurrence_id")
16917        .and_then(Value::as_str)
16918        .filter(|value| !value.is_empty())
16919        .map(str::to_string)
16920        .ok_or_else(|| {
16921            invalid_recorded_history(
16922                "condition_wait_occurrence_id_missing",
16923                sequence,
16924                "non-empty condition_wait_occurrence_id",
16925                &event.event_type,
16926                "condition history is missing authored occurrence identity",
16927            )
16928        })
16929}
16930
16931fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16932    event
16933        .payload
16934        .get("condition_wait_id")
16935        .and_then(Value::as_str)
16936        .filter(|value| !value.is_empty())
16937        .map(str::to_string)
16938        .ok_or_else(|| {
16939            invalid_recorded_history(
16940                "condition_wait_id_missing",
16941                sequence,
16942                "non-empty condition_wait_id",
16943                &event.event_type,
16944                "canonical condition history is missing its durable wait identity",
16945            )
16946        })
16947}
16948
16949fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16950    event
16951        .payload
16952        .get(field)
16953        .and_then(Value::as_str)
16954        .filter(|value| !value.is_empty())
16955        .map(str::to_string)
16956}
16957
16958fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16959    match event.payload.get(field) {
16960        None | Some(Value::Null) => Ok(None),
16961        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16962            invalid_recorded_history(
16963                "condition_wait_definition_invalid",
16964                sequence,
16965                &format!("non-negative integer {field}"),
16966                &value.to_string(),
16967                "condition history contains an invalid numeric definition field",
16968            )
16969        }),
16970    }
16971}
16972
16973fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16974    event
16975        .payload
16976        .get("signal_name")
16977        .or_else(|| event.raw.get("signal_name"))
16978        .and_then(Value::as_str)
16979        .filter(|value| !value.is_empty())
16980        .map(str::to_string)
16981        .ok_or_else(|| {
16982            invalid_recorded_history(
16983                "signal_wait_name_missing",
16984                sequence,
16985                "non-empty signal_name",
16986                &event.event_type,
16987                "canonical signal-wait history is missing its signal identity",
16988            )
16989        })
16990}
16991
16992fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16993    // Applying a buffered control-plane signal has no authored call sequence.
16994    // Its outer sequence orders history events and must not become a wait.
16995    if event.event_type == "SignalApplied"
16996        && event
16997            .payload
16998            .get("signal_wait_id")
16999            .and_then(Value::as_str)
17000            .is_some_and(|id| id.starts_with("signal-command:"))
17001        && event.payload.get("sequence").is_none()
17002        && event.payload.get("workflow_sequence").is_none()
17003    {
17004        return false;
17005    }
17006    matches!(
17007        event.event_type.as_str(),
17008        "SignalWaitOpened" | "SignalApplied"
17009    )
17010}
17011
17012fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17013    event
17014        .payload
17015        .get(field)
17016        .and_then(Value::as_str)
17017        .filter(|value| !value.is_empty())
17018        .map(str::to_string)
17019        .ok_or_else(|| {
17020            invalid_recorded_history(
17021                "timer_history_field_missing",
17022                sequence,
17023                field,
17024                &event.event_type,
17025                "timer history is missing a required identity field",
17026            )
17027        })
17028}
17029
17030fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17031    event
17032        .payload
17033        .get(field)
17034        .and_then(value_as_u64)
17035        .ok_or_else(|| {
17036            invalid_recorded_history(
17037                "timer_history_field_missing",
17038                sequence,
17039                field,
17040                &event.event_type,
17041                "timer history is missing a required numeric field",
17042            )
17043        })
17044}
17045
17046fn recorded_search_attribute_types(
17047    payload: &Value,
17048    attributes: &Value,
17049    sequence: u64,
17050) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17051    let Some(raw_types) = payload.get("attribute_types") else {
17052        // This is the explicit compatibility rule for histories recorded
17053        // before typed identity was persisted. Values still constrain replay;
17054        // the unknown type snapshot does not assert a typed match.
17055        return Ok(RecordedSnapshotValue::Unknown);
17056    };
17057    let Some(raw_types) = raw_types.as_object() else {
17058        return Err(invalid_recorded_history(
17059            "search_attribute_types_malformed",
17060            sequence,
17061            "canonical attribute type map",
17062            &raw_types.to_string(),
17063            "search-attribute history contains malformed type identity",
17064        ));
17065    };
17066    let attribute_keys = attributes
17067        .as_object()
17068        .expect("recorded search attributes were validated as an object");
17069    let mut types = BTreeMap::new();
17070    for (key, value) in raw_types {
17071        let Some(attribute_type) = value.as_str() else {
17072            return Err(invalid_recorded_history(
17073                "search_attribute_types_malformed",
17074                sequence,
17075                "canonical string type name",
17076                &value.to_string(),
17077                "search-attribute history contains a non-string type identity",
17078            ));
17079        };
17080        if !attribute_keys.contains_key(key)
17081            || !matches!(
17082                attribute_type,
17083                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17084            )
17085        {
17086            return Err(invalid_recorded_history(
17087                "search_attribute_types_malformed",
17088                sequence,
17089                "canonical types for keys present in attributes",
17090                &format!("{key}:{attribute_type}"),
17091                "search-attribute history contains unsupported or orphaned type identity",
17092            ));
17093        }
17094        types.insert(key.clone(), attribute_type.to_string());
17095    }
17096    Ok(RecordedSnapshotValue::Known(types))
17097}
17098
17099fn invalid_recorded_history(
17100    reason: &str,
17101    sequence: u64,
17102    expected: &str,
17103    actual: &str,
17104    message: &str,
17105) -> Error {
17106    Error::NonDeterministicReplay(ReplayFailure::new(
17107        reason,
17108        Some(sequence),
17109        Some(expected.to_string()),
17110        Some(actual.to_string()),
17111        message,
17112    ))
17113}
17114
17115type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17116
17117fn activity_outcome(
17118    event: &HistoryEvent,
17119    fallback_codec: &str,
17120    recorded_activity_type: Option<String>,
17121) -> Result<ActivityOutcome> {
17122    if event.event_type == "ActivityCompleted" {
17123        let codec = event
17124            .payload
17125            .get("payload_codec")
17126            .and_then(Value::as_str)
17127            .unwrap_or(fallback_codec);
17128        return Ok(Ok(decode_wire_avro_value(
17129            event.payload.get("result").unwrap_or(&Value::Null),
17130            codec,
17131        )?));
17132    }
17133
17134    let payload = &event.payload;
17135    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17136        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17137        "ActivityCancelled" => (
17138            ActivityFailureKind::Cancelled,
17139            "cancelled",
17140            "activity was cancelled",
17141        ),
17142        "ActivityTimedOut" => (
17143            ActivityFailureKind::TimedOut,
17144            "timeout",
17145            "activity timed out",
17146        ),
17147        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17148    };
17149    let exception = payload
17150        .get("exception")
17151        .filter(|value| !value.is_null())
17152        .cloned();
17153    let failure_category = payload_string(payload, "failure_category");
17154    let timeout_kind = payload_string(payload, "timeout_kind");
17155    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17156        ActivityFailureKind::Failed => failure_category
17157            .clone()
17158            .unwrap_or_else(|| fallback_reason.to_string()),
17159        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
17160        ActivityFailureKind::TimedOut => timeout_kind
17161            .clone()
17162            .unwrap_or_else(|| fallback_reason.to_string()),
17163    });
17164    let message = payload_string(payload, "message")
17165        .or_else(|| {
17166            exception
17167                .as_ref()
17168                .and_then(|value| payload_string(value, "message"))
17169        })
17170        .unwrap_or_else(|| fallback_message.to_string());
17171
17172    Ok(Err(ActivityFailure {
17173        kind,
17174        reason,
17175        message,
17176        activity_execution_id: payload_string(payload, "activity_execution_id"),
17177        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
17178        activity_type: payload_string(payload, "activity_type")
17179            .or_else(|| payload_string(payload, "activity_name"))
17180            .or(recorded_activity_type),
17181        activity_class: payload_string(payload, "activity_class"),
17182        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
17183        failure_id: payload_string(payload, "failure_id"),
17184        failure_category,
17185        timeout_kind,
17186        non_retryable: payload
17187            .get("non_retryable")
17188            .and_then(Value::as_bool)
17189            .unwrap_or(false),
17190        exception_type: payload_string(payload, "exception_type").or_else(|| {
17191            exception
17192                .as_ref()
17193                .and_then(|value| payload_string(value, "type"))
17194        }),
17195        exception_class: payload_string(payload, "exception_class").or_else(|| {
17196            exception
17197                .as_ref()
17198                .and_then(|value| payload_string(value, "class"))
17199        }),
17200        code: payload
17201            .get("code")
17202            .filter(|value| !value.is_null())
17203            .cloned(),
17204        exception,
17205    }))
17206}
17207
17208type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
17209
17210fn child_workflow_outcomes(
17211    events: &[HistoryEvent],
17212    fallback_codec: &str,
17213    parent: WorkflowIdentity,
17214) -> Result<Vec<ChildWorkflowOutcome>> {
17215    let mut outcomes = Vec::new();
17216
17217    for event in events {
17218        let kind = match event.event_type.as_str() {
17219            "ChildRunCompleted" => None,
17220            "ChildRunFailed" => Some((
17221                ChildWorkflowFailureKind::Failed,
17222                "child_workflow",
17223                "child workflow failed",
17224            )),
17225            "ChildRunCancelled" => Some((
17226                ChildWorkflowFailureKind::Cancelled,
17227                "cancelled",
17228                "child workflow was cancelled",
17229            )),
17230            "ChildRunTerminated" => Some((
17231                ChildWorkflowFailureKind::Terminated,
17232                "terminated",
17233                "child workflow was terminated",
17234            )),
17235            _ => continue,
17236        };
17237        let payload = &event.payload;
17238        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
17239        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
17240        let child_workflow_type = payload_string(payload, "child_workflow_type");
17241
17242        if let Some((kind, reason, fallback_message)) = kind {
17243            let exception = payload
17244                .get("exception")
17245                .filter(|value| !value.is_null())
17246                .cloned();
17247            let message = payload_string(payload, "message")
17248                .or_else(|| {
17249                    exception
17250                        .as_ref()
17251                        .and_then(|value| payload_string(value, "message"))
17252                })
17253                .unwrap_or_else(|| fallback_message.to_string());
17254            let exception_type = payload_string(payload, "exception_type").or_else(|| {
17255                exception
17256                    .as_ref()
17257                    .and_then(|value| payload_string(value, "type"))
17258            });
17259            let exception_class = payload_string(payload, "exception_class").or_else(|| {
17260                exception
17261                    .as_ref()
17262                    .and_then(|value| payload_string(value, "class"))
17263            });
17264            outcomes.push(Err(ChildWorkflowFailure {
17265                kind,
17266                reason: reason.to_string(),
17267                message,
17268                parent_workflow_id: parent.workflow_id.clone(),
17269                parent_workflow_run_id: parent.run_id.clone(),
17270                child_workflow_id,
17271                child_workflow_run_id,
17272                child_workflow_type,
17273                failure_id: payload_string(payload, "failure_id"),
17274                failure_category: payload_string(payload, "failure_category"),
17275                exception_type,
17276                exception_class,
17277                non_retryable: payload
17278                    .get("non_retryable")
17279                    .and_then(Value::as_bool)
17280                    .unwrap_or(false),
17281                code: payload
17282                    .get("code")
17283                    .filter(|value| !value.is_null())
17284                    .cloned(),
17285                exception,
17286            }));
17287            continue;
17288        }
17289
17290        let codec = payload
17291            .get("payload_codec")
17292            .and_then(Value::as_str)
17293            .unwrap_or(fallback_codec);
17294        let result = payload
17295            .get("result")
17296            .or_else(|| payload.get("output"))
17297            .unwrap_or(&Value::Null);
17298        outcomes.push(Ok(ChildWorkflowAvroResult {
17299            parent: parent.clone(),
17300            child: WorkflowIdentity {
17301                workflow_id: child_workflow_id,
17302                run_id: child_workflow_run_id,
17303            },
17304            child_workflow_type,
17305            result: decode_wire_avro_value(result, codec)?,
17306        }));
17307    }
17308
17309    Ok(outcomes)
17310}
17311
17312fn payload_string(payload: &Value, key: &str) -> Option<String> {
17313    payload
17314        .get(key)
17315        .and_then(Value::as_str)
17316        .filter(|value| !value.is_empty())
17317        .map(str::to_string)
17318}
17319
17320fn recorded_activity_failure_boundary(
17321    ctx: &WorkflowContext,
17322    error: &Error,
17323) -> Option<(u64, String)> {
17324    let Error::ActivityFailed(failure) = error else {
17325        return None;
17326    };
17327    if failure.kind != ActivityFailureKind::Failed {
17328        return None;
17329    }
17330    let activity_execution_id = failure
17331        .activity_execution_id
17332        .as_deref()
17333        .filter(|value| !value.is_empty())?;
17334    let state = ctx.state.lock().ok()?;
17335    let mut matches = state.recorded_commands.iter().filter_map(|command| {
17336        let RecordedCommand::Activity {
17337            sequence,
17338            outcome: Some(Err(recorded_failure)),
17339            ..
17340        } = command
17341        else {
17342            return None;
17343        };
17344        (*sequence > 0 && recorded_failure == failure)
17345            .then_some((*sequence, activity_execution_id.to_string()))
17346    });
17347    let boundary = matches.next()?;
17348    matches.next().is_none().then_some(boundary)
17349}
17350
17351fn workflow_failure_command(
17352    error: &Error,
17353    failed_activity_boundary: Option<(u64, String)>,
17354) -> Value {
17355    let (exception_type, exception_class, properties) = match error {
17356        Error::ActivityFailed(failure) => (
17357            match failure.kind {
17358                ActivityFailureKind::Failed => "ActivityFailed",
17359                ActivityFailureKind::Cancelled => "ActivityCancelled",
17360                ActivityFailureKind::TimedOut => "ActivityTimedOut",
17361            },
17362            "durable_workflow::ActivityFailure",
17363            json!({
17364                "reason": failure.reason,
17365                "activity_execution_id": failure.activity_execution_id,
17366                "activity_attempt_id": failure.activity_attempt_id,
17367                "activity_type": failure.activity_type,
17368                "activity_class": failure.activity_class,
17369                "attempt_number": failure.attempt_number,
17370                "failure_id": failure.failure_id,
17371                "failure_category": failure.failure_category,
17372                "timeout_kind": failure.timeout_kind,
17373                "activity_non_retryable": failure.non_retryable,
17374                "activity_exception_type": failure.exception_type,
17375                "activity_exception_class": failure.exception_class,
17376                "activity_code": failure.code,
17377                "activity_exception": failure.exception,
17378            }),
17379        ),
17380        Error::ChildWorkflowFailed(failure) => (
17381            match failure.kind {
17382                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17383                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17384                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17385            },
17386            "durable_workflow::ChildWorkflowFailure",
17387            json!({
17388                "reason": failure.reason,
17389                "parent_workflow_id": failure.parent_workflow_id,
17390                "parent_workflow_run_id": failure.parent_workflow_run_id,
17391                "child_workflow_id": failure.child_workflow_id,
17392                "child_workflow_run_id": failure.child_workflow_run_id,
17393                "child_workflow_type": failure.child_workflow_type,
17394                "failure_id": failure.failure_id,
17395                "failure_category": failure.failure_category,
17396                "child_exception_type": failure.exception_type,
17397                "child_exception_class": failure.exception_class,
17398                "child_non_retryable": failure.non_retryable,
17399                "child_code": failure.code,
17400                "child_exception": failure.exception,
17401            }),
17402        ),
17403        Error::ParallelFailed(failure) => (
17404            "ParallelFailed",
17405            "durable_workflow::ParallelFailure",
17406            json!({
17407                "parallel_group_id": failure.group_id,
17408                "parallel_member_path": failure.member_path,
17409                "parallel_group_path": failure.group_path,
17410                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
17411                "cause_type": workflow_error_type(&failure.cause),
17412                "cause_message": failure.cause.to_string(),
17413            }),
17414        ),
17415        Error::SagaCompensationFailed(failure) => (
17416            "SagaCompensationFailed",
17417            "durable_workflow::SagaCompensationFailure",
17418            json!({
17419                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
17420                "initiating_failure_message": failure.initiating_failure.to_string(),
17421                "compensation_activity_type": failure.compensation_activity_type,
17422                "compensation_registration_order": failure.compensation_registration_order,
17423                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
17424                "compensation_failure_message": failure.compensation_failure.to_string(),
17425            }),
17426        ),
17427        Error::WorkflowCancellationRequested(_) => (
17428            "WorkflowCancellationRequested",
17429            "durable_workflow::WorkflowCancellationRequested",
17430            json!({"reason": "cancelled"}),
17431        ),
17432        Error::CooperativeCancellationRequested(cancellation) => (
17433            "WorkflowCancellationRequested",
17434            "durable_workflow::CooperativeCancellationRequested",
17435            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
17436                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
17437        ),
17438        Error::CancellationScopeRequested(cancellation) => (
17439            "WorkflowCancellationRequested",
17440            "durable_workflow::CancellationScopeRequested",
17441            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
17442                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
17443                "cancellation":cancellation.context.to_value()}),
17444        ),
17445        Error::NonDeterministicReplay(_) => (
17446            "NonDeterministicReplay",
17447            "durable_workflow::Error",
17448            Value::Null,
17449        ),
17450        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
17451    };
17452    let non_retryable = match error {
17453        Error::ActivityFailed(failure) => failure.non_retryable,
17454        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17455        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17456        Error::SagaCompensationFailed(failure) => {
17457            workflow_error_non_retryable(&failure.compensation_failure)
17458        }
17459        Error::WorkflowCancellationRequested(_)
17460        | Error::CooperativeCancellationRequested(_)
17461        | Error::CancellationScopeRequested(_) => true,
17462        Error::NonDeterministicReplay(_) => true,
17463        _ => false,
17464    };
17465
17466    let mut command = json!({
17467        "type": "fail_workflow",
17468        "message": error.to_string(),
17469        "exception_type": exception_type,
17470        "exception_class": exception_class,
17471        "non_retryable": non_retryable,
17472        "exception": {
17473            "type": exception_type,
17474            "class": exception_class,
17475            "message": error.to_string(),
17476            "properties": properties,
17477        }
17478    });
17479
17480    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
17481        command["failed_step_sequence"] = json!(sequence);
17482        command["failed_activity_execution_id"] = json!(activity_execution_id);
17483    }
17484
17485    command
17486}
17487
17488fn workflow_error_type(error: &Error) -> &'static str {
17489    match error {
17490        Error::ActivityFailed(failure) => match failure.kind {
17491            ActivityFailureKind::Failed => "ActivityFailed",
17492            ActivityFailureKind::Cancelled => "ActivityCancelled",
17493            ActivityFailureKind::TimedOut => "ActivityTimedOut",
17494        },
17495        Error::ChildWorkflowFailed(failure) => match failure.kind {
17496            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17497            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17498            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17499        },
17500        Error::ParallelFailed(_) => "ParallelFailed",
17501        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
17502        Error::WorkflowCancellationRequested(_)
17503        | Error::CooperativeCancellationRequested(_)
17504        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
17505        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
17506        _ => "RustWorkflowError",
17507    }
17508}
17509
17510fn workflow_error_non_retryable(error: &Error) -> bool {
17511    match error {
17512        Error::ActivityFailed(failure) => failure.non_retryable,
17513        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17514        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17515        Error::SagaCompensationFailed(failure) => {
17516            workflow_error_non_retryable(&failure.compensation_failure)
17517        }
17518        Error::WorkflowCancellationRequested(_)
17519        | Error::CooperativeCancellationRequested(_)
17520        | Error::CancellationScopeRequested(_)
17521        | Error::NonDeterministicReplay(_) => true,
17522        _ => false,
17523    }
17524}
17525
17526fn workflow_task_integrity_error(error: &Error) -> bool {
17527    matches!(
17528        error,
17529        Error::NonDeterministicReplay(_)
17530            | Error::Protocol(_)
17531            | Error::CancellationScopeExecutionUnavailable
17532            | Error::MissingWorkflowCommandIdentity
17533            | Error::WorkflowStatePoisoned
17534    )
17535}
17536
17537fn decode_signal_event_arguments(
17538    event: &HistoryEvent,
17539    fallback_codec: &str,
17540) -> Result<Vec<AvroValue>> {
17541    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17542    validate_payload_codec(codec)?;
17543    let raw = signal_history_payload(&event.payload);
17544    let decoded = match raw.filter(|value| !value.is_null()) {
17545        Some(value) => decode_wire_avro_value(value, codec)?,
17546        None => AvroValue::Array(Vec::new()),
17547    };
17548    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17549        unreachable!("normalize_avro_arguments always returns an array");
17550    };
17551    Ok(arguments)
17552}
17553
17554fn decode_update_event_arguments(
17555    event: &HistoryEvent,
17556    fallback_codec: &str,
17557) -> Result<Vec<AvroValue>> {
17558    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17559    validate_payload_codec(codec)?;
17560    let decoded = match event
17561        .payload
17562        .get("arguments")
17563        .filter(|value| !value.is_null())
17564    {
17565        Some(value) => decode_wire_avro_value(value, codec)?,
17566        None => AvroValue::Array(Vec::new()),
17567    };
17568    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17569        unreachable!("normalize_avro_arguments always returns an array");
17570    };
17571    Ok(arguments)
17572}
17573
17574fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17575    let Some(export_events) = task
17576        .history_export
17577        .as_ref()
17578        .and_then(|export| export.get("history_events"))
17579        .and_then(Value::as_array)
17580    else {
17581        return Ok(());
17582    };
17583
17584    if export_events.len() > task.history_events.len() {
17585        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
17586    }
17587
17588    Ok(())
17589}
17590
17591fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17592    let Some(export) = task.history_export.as_ref() else {
17593        return Ok(());
17594    };
17595    let signals = export
17596        .get("signals")
17597        .and_then(Value::as_array)
17598        .cloned()
17599        .unwrap_or_default();
17600    let activities = export
17601        .get("activities")
17602        .and_then(Value::as_array)
17603        .cloned()
17604        .unwrap_or_default();
17605    let export_codec = export
17606        .get("payloads")
17607        .and_then(|payloads| payloads.get("codec"))
17608        .and_then(Value::as_str)
17609        .unwrap_or(&task.payload_codec)
17610        .to_string();
17611    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
17612
17613    for event in &mut task.history_events {
17614        if event.event_type == "ActivityCompleted" {
17615            let sequence = event
17616                .payload
17617                .get("sequence")
17618                .or_else(|| event.payload.get("workflow_sequence"))
17619                .and_then(value_as_u64);
17620            let Some(activity) = sequence.and_then(|sequence| {
17621                activities.iter().find(|activity| {
17622                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
17623                })
17624            }) else {
17625                continue;
17626            };
17627            let Some(payload) = event.payload.as_object_mut() else {
17628                continue;
17629            };
17630            if missing_payload(payload.get("result")) {
17631                if let Some(result) = activity
17632                    .get("result")
17633                    .filter(|value| !missing_payload(Some(value)))
17634                {
17635                    payload.insert("result".to_string(), result.clone());
17636                }
17637            }
17638            for field in ["payload_codec", "activity_type"] {
17639                if payload
17640                    .get(field)
17641                    .and_then(Value::as_str)
17642                    .unwrap_or_default()
17643                    .is_empty()
17644                {
17645                    if let Some(value) = activity.get(field) {
17646                        payload.insert(field.to_string(), value.clone());
17647                    }
17648                }
17649            }
17650            continue;
17651        }
17652
17653        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
17654            continue;
17655        }
17656        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17657        let command_id = event
17658            .payload
17659            .get("workflow_command_id")
17660            .or_else(|| event.raw.get("workflow_command_id"))
17661            .and_then(Value::as_str);
17662        let signal_name = event
17663            .payload
17664            .get("signal_name")
17665            .and_then(Value::as_str)
17666            .unwrap_or_default()
17667            .to_string();
17668        let matched = signals
17669            .iter()
17670            .find(|signal| {
17671                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
17672            })
17673            .or_else(|| {
17674                signals.iter().find(|signal| {
17675                    command_id.is_some()
17676                        && signal.get("command_id").and_then(Value::as_str) == command_id
17677                })
17678            })
17679            .or_else(|| {
17680                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
17681                let signal = signals
17682                    .iter()
17683                    .filter(|signal| {
17684                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
17685                    })
17686                    .nth(*offset);
17687                if signal.is_some() {
17688                    *offset += 1;
17689                }
17690                signal
17691            });
17692        let Some(signal) = matched else {
17693            continue;
17694        };
17695        let signal_codec = signal
17696            .get("payload_codec")
17697            .and_then(Value::as_str)
17698            .unwrap_or(&export_codec);
17699        let Some(payload) = event.payload.as_object_mut() else {
17700            continue;
17701        };
17702        if missing_payload(payload.get("arguments")) {
17703            if let Some(arguments) = signal
17704                .get("arguments")
17705                .filter(|value| !missing_payload(Some(value)))
17706            {
17707                let envelope = match arguments {
17708                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
17709                    other => other.clone(),
17710                };
17711                payload.insert("arguments".to_string(), envelope);
17712            }
17713        }
17714        if payload
17715            .get("payload_codec")
17716            .and_then(Value::as_str)
17717            .unwrap_or_default()
17718            .is_empty()
17719        {
17720            payload.insert("payload_codec".to_string(), json!(signal_codec));
17721        }
17722    }
17723
17724    Ok(())
17725}
17726
17727fn missing_payload(value: Option<&Value>) -> bool {
17728    match value {
17729        None | Some(Value::Null) => true,
17730        Some(Value::String(value)) => value.is_empty(),
17731        Some(_) => false,
17732    }
17733}
17734
17735fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
17736    history_signal_events(
17737        &task.history_events,
17738        task.history_export.as_ref(),
17739        &task.payload_codec,
17740    )
17741}
17742
17743fn history_signal_events(
17744    history_events: &[HistoryEvent],
17745    history_export: Option<&Value>,
17746    payload_codec: &str,
17747) -> Result<Vec<QuerySignal>> {
17748    let export_signals = history_export
17749        .and_then(|export| export.get("signals"))
17750        .and_then(Value::as_array)
17751        .cloned()
17752        .unwrap_or_default();
17753    let export_codec = history_export
17754        .and_then(|export| export.get("payloads"))
17755        .and_then(|payloads| payloads.get("codec"))
17756        .and_then(Value::as_str)
17757        .unwrap_or(payload_codec);
17758    let mut name_offsets: HashMap<String, usize> = HashMap::new();
17759    let mut signals: Vec<QuerySignal> = Vec::new();
17760    let mut signal_indices = HashMap::new();
17761    let mut command_indices = HashMap::new();
17762
17763    for event in history_events {
17764        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
17765            continue;
17766        }
17767
17768        let name = event
17769            .payload
17770            .get("signal_name")
17771            .and_then(Value::as_str)
17772            .unwrap_or_default();
17773        if name.is_empty() {
17774            continue;
17775        }
17776        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17777        let command_id = event
17778            .payload
17779            .get("workflow_command_id")
17780            .or_else(|| event.raw.get("workflow_command_id"))
17781            .and_then(Value::as_str);
17782        let matched_export = export_signals
17783            .iter()
17784            .find(|candidate| {
17785                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17786            })
17787            .or_else(|| {
17788                export_signals.iter().find(|candidate| {
17789                    command_id.is_some()
17790                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17791                })
17792            })
17793            .or_else(|| {
17794                let offset = name_offsets.entry(name.to_string()).or_default();
17795                let candidate = export_signals
17796                    .iter()
17797                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17798                    .nth(*offset);
17799                if candidate.is_some() {
17800                    *offset += 1;
17801                }
17802                candidate
17803            });
17804        let codec = event
17805            .payload
17806            .get("payload_codec")
17807            .and_then(Value::as_str)
17808            .or_else(|| {
17809                matched_export
17810                    .and_then(|signal| signal.get("payload_codec"))
17811                    .and_then(Value::as_str)
17812            })
17813            .unwrap_or(export_codec);
17814        let raw_arguments = signal_history_payload(&event.payload)
17815            .filter(|value| !value.is_null())
17816            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17817        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
17818        let workflow_sequence = event
17819            .payload
17820            .get("workflow_sequence")
17821            .and_then(value_as_u64)
17822            .or_else(|| {
17823                matched_export
17824                    .and_then(|signal| signal.get("workflow_sequence"))
17825                    .and_then(value_as_u64)
17826            });
17827
17828        let id = signal_id.or_else(|| {
17829            matched_export
17830                .and_then(|signal| signal.get("id"))
17831                .and_then(Value::as_str)
17832        });
17833        let command_id = command_id.or_else(|| {
17834            matched_export
17835                .and_then(|signal| signal.get("command_id"))
17836                .and_then(Value::as_str)
17837        });
17838        let duplicate = id
17839            .and_then(|id| signal_indices.get(id))
17840            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
17841            .copied();
17842        let index = duplicate.unwrap_or(signals.len());
17843        if let Some(index) = duplicate {
17844            let original = &mut signals[index];
17845            let same_arguments = if event.event_type == "SignalApplied" {
17846                if let Some(value) = event.payload.get("value") {
17847                    let expected = match original.avro_arguments.as_slice() {
17848                        [] => AvroValue::Boolean(true),
17849                        [value] => value.clone(),
17850                        values => AvroValue::Array(values.to_vec()),
17851                    };
17852                    let applied = decode_wire_avro_value(value, codec)?;
17853                    applied == expected
17854                        || applied == AvroValue::Array(original.avro_arguments.clone())
17855                } else {
17856                    original.avro_arguments == avro_arguments
17857                }
17858            } else {
17859                original.avro_arguments == avro_arguments
17860            };
17861            if original.name != name
17862                || !same_arguments
17863                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
17864            {
17865                return Err(Error::Codec("conflicting committed signal identity".into()));
17866            }
17867            if original.id.is_none() {
17868                original.id = id.map(str::to_string);
17869            }
17870            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
17871        } else {
17872            signals.push(QuerySignal {
17873                id: id.map(str::to_string),
17874                name: name.to_string(),
17875                arguments,
17876                avro_arguments,
17877                workflow_sequence,
17878            });
17879        }
17880        if let Some(id) = id {
17881            signal_indices.insert(id.to_string(), index);
17882        }
17883        if let Some(id) = command_id {
17884            command_indices.insert(id.to_string(), index);
17885        }
17886    }
17887
17888    if signals.is_empty() {
17889        for signal in export_signals {
17890            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17891                continue;
17892            }
17893            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17894                continue;
17895            };
17896            let codec = signal
17897                .get("payload_codec")
17898                .and_then(Value::as_str)
17899                .unwrap_or(export_codec);
17900            let (arguments, avro_arguments) =
17901                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17902            signals.push(QuerySignal {
17903                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17904                name: name.to_string(),
17905                arguments,
17906                avro_arguments,
17907                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17908            });
17909        }
17910        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17911    }
17912
17913    Ok(signals)
17914}
17915
17916fn decode_query_signal_arguments(
17917    raw: Option<&Value>,
17918    codec: &str,
17919) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17920    validate_payload_codec(codec)?;
17921    let decoded = match raw.filter(|value| !value.is_null()) {
17922        Some(value) => decode_wire_avro_value(value, codec)?,
17923        None => AvroValue::Array(Vec::new()),
17924    };
17925    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17926        unreachable!("normalize_avro_arguments always returns an array");
17927    };
17928    let arguments = avro_arguments
17929        .iter()
17930        .cloned()
17931        .map(AvroValue::into_json)
17932        .collect::<Result<Vec<_>>>()?;
17933    Ok((arguments, avro_arguments))
17934}
17935
17936fn value_as_u64(value: &Value) -> Option<u64> {
17937    value
17938        .as_u64()
17939        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17940}
17941
17942#[cfg(test)]
17943mod tests {
17944    use super::*;
17945    mod activity_cancellation_policies;
17946    mod cancellation_scope_admission;
17947    mod cancellation_scope_authoring;
17948    mod cancellation_scope_history;
17949    mod cancellation_scope_opening;
17950    mod cancellation_scope_replay;
17951    mod child_workflow_policies;
17952    mod cooperative_cancellation;
17953    mod local_activity;
17954    mod runtime_payloads;
17955    mod runtime_uploads;
17956    mod version_marker_contract;
17957    mod worker_session;
17958    use std::{
17959        fs,
17960        io::{Read, Write},
17961        net::{SocketAddr, TcpListener, TcpStream},
17962        process::Command as ProcessCommand,
17963        sync::atomic::AtomicUsize,
17964        thread,
17965    };
17966
17967    #[derive(Clone, Copy, Debug)]
17968    enum InvalidTaskPayloadCodec {
17969        Missing,
17970        Null,
17971        NonString,
17972    }
17973
17974    impl InvalidTaskPayloadCodec {
17975        fn label(self) -> &'static str {
17976            match self {
17977                Self::Missing => "missing",
17978                Self::Null => "null",
17979                Self::NonString => "non-string",
17980            }
17981        }
17982
17983        fn apply(self, task: &mut Value) {
17984            let task = task.as_object_mut().expect("task fixture object");
17985            match self {
17986                Self::Missing => {
17987                    task.remove("payload_codec");
17988                }
17989                Self::Null => {
17990                    task.insert("payload_codec".to_string(), Value::Null);
17991                }
17992                Self::NonString => {
17993                    task.insert("payload_codec".to_string(), json!(42));
17994                }
17995            }
17996        }
17997    }
17998
17999    fn fixture_envelope(value: Value) -> Value {
18000        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18001    }
18002
18003    fn fixture_blob(value: Value) -> String {
18004        encode_payload(&value, DEFAULT_CODEC)
18005            .expect("encode Avro test fixture")
18006            .blob
18007    }
18008
18009    #[test]
18010    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18011        for base_url in [
18012            "http://127.0.0.1:8080/api",
18013            "http://localhost:8080/api/",
18014            "https://runtime.example.test/namespaces/orders/api",
18015        ] {
18016            let error = Client::builder(base_url)
18017                .build()
18018                .expect_err("SDK-owned /api suffix must be rejected during build");
18019
18020            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18021            assert!(
18022                error.to_string().contains("SDK appends /api automatically"),
18023                "the validation error must explain how to fix the endpoint"
18024            );
18025        }
18026    }
18027
18028    #[test]
18029    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18030        for (base_url, expected) in [
18031            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18032            (
18033                "http://localhost:8080/durable-workflow/",
18034                "http://localhost:8080/durable-workflow",
18035            ),
18036            (
18037                "https://runtime.example.test/namespaces/orders",
18038                "https://runtime.example.test/namespaces/orders",
18039            ),
18040            (
18041                "https://runtime.example.test/gateway/api/namespaces/orders",
18042                "https://runtime.example.test/gateway/api/namespaces/orders",
18043            ),
18044            (
18045                "https://api.example.test/runtime/orders/",
18046                "https://api.example.test/runtime/orders",
18047            ),
18048        ] {
18049            let client = Client::builder(base_url)
18050                .build()
18051                .expect("Server and Cloud runtime base URL must remain valid");
18052
18053            assert_eq!(client.base_url, expected);
18054        }
18055    }
18056
18057    #[test]
18058    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18059        assert_eq!(
18060            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18061            MINIMUM_WORKER_PROTOCOL_VERSION
18062        );
18063        assert_eq!(
18064            workflow_completion_protocol_version(&[json!({
18065                "type": "upsert_search_attributes",
18066                "attributes": {"OrderStatus": "waiting"},
18067            })]),
18068            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18069        );
18070        assert_eq!(
18071            workflow_completion_protocol_version(&[json!({
18072                "type": "upsert_search_attributes",
18073                "attributes": {"OrderStatus": "waiting"},
18074                "attribute_types": {"OrderStatus": "keyword"},
18075            })]),
18076            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18077        );
18078        assert_eq!(
18079            workflow_completion_protocol_version(&[
18080                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18081                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18082            ]),
18083            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18084        );
18085        assert_eq!(
18086            workflow_completion_protocol_version(&[
18087                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18088                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18089            ]),
18090            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18091        );
18092        assert_eq!(
18093            workflow_completion_protocol_version(&[json!({
18094                "type": "open_condition_wait",
18095                "condition_wait_occurrence_id": "rust:condition-wait:0",
18096                "condition_key": "ready",
18097            })]),
18098            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18099        );
18100        assert_eq!(
18101            workflow_completion_protocol_version_with_message_streams(
18102                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18103                true,
18104            ),
18105            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18106        );
18107        assert_eq!(
18108            workflow_completion_protocol_version_with_message_streams(
18109                &[json!({
18110                    "type": "open_condition_wait",
18111                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18112                    "condition_key": "ready",
18113                })],
18114                true,
18115            ),
18116            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18117        );
18118    }
18119
18120    #[test]
18121    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
18122        let manifest = portable_worker_affinity_capability_manifest();
18123
18124        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
18125            assert_eq!(manifest[capability]["supported"], json!(false));
18126            assert_eq!(
18127                manifest[capability]["minimum_protocol_version"],
18128                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18129            );
18130            assert!(manifest[capability]["reason"]
18131                .as_str()
18132                .is_some_and(|reason| !reason.is_empty()));
18133        }
18134    }
18135
18136    fn typed_fidelity_probe() -> AvroValue {
18137        AvroValue::Map(BTreeMap::from([
18138            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18139            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18140            (
18141                "numeric".to_string(),
18142                AvroValue::Map(BTreeMap::from([
18143                    ("0".to_string(), AvroValue::String("zero".to_string())),
18144                    ("1".to_string(), AvroValue::String("one".to_string())),
18145                ])),
18146            ),
18147            (
18148                "nested".to_string(),
18149                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
18150                    "enabled".to_string(),
18151                    AvroValue::Boolean(true),
18152                )]))]),
18153            ),
18154            (
18155                "projection_collisions".to_string(),
18156                AvroValue::Array(projection_collision_probe()),
18157            ),
18158        ]))
18159    }
18160
18161    fn projection_collision_probe() -> Vec<AvroValue> {
18162        vec![
18163            AvroValue::Map(BTreeMap::from([
18164                ("$type".to_string(), AvroValue::String("bytes".to_string())),
18165                (
18166                    "base64".to_string(),
18167                    AvroValue::String("ordinary user text".to_string()),
18168                ),
18169            ])),
18170            AvroValue::Map(BTreeMap::from([
18171                ("$type".to_string(), AvroValue::String("map".to_string())),
18172                (
18173                    "entries".to_string(),
18174                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
18175                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
18176                        (
18177                            "value".to_string(),
18178                            AvroValue::String("user map".to_string()),
18179                        ),
18180                    ]))]),
18181                ),
18182            ])),
18183        ]
18184    }
18185
18186    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18187    struct TypedContract {
18188        nested: TypedNested,
18189        mode: TypedMode,
18190        optional: Option<String>,
18191        absent: Option<String>,
18192        items: Vec<i64>,
18193        labels: BTreeMap<String, String>,
18194        bytes: serde_bytes::ByteBuf,
18195        signed: i64,
18196        finite: f64,
18197    }
18198
18199    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18200    struct TypedNested {
18201        enabled: bool,
18202    }
18203
18204    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18205    enum TypedMode {
18206        Detailed { label: String },
18207    }
18208
18209    fn typed_contract() -> TypedContract {
18210        TypedContract {
18211            nested: TypedNested { enabled: true },
18212            mode: TypedMode::Detailed {
18213                label: "compiler-checked".to_string(),
18214            },
18215            optional: Some("present".to_string()),
18216            absent: None,
18217            items: vec![i64::MIN, 0, i64::MAX],
18218            labels: BTreeMap::from([
18219                ("language".to_string(), "rust".to_string()),
18220                ("wire".to_string(), "avro".to_string()),
18221            ]),
18222            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
18223            signed: -9_223_372_036_854_775_000,
18224            finite: 12.5,
18225        }
18226    }
18227
18228    #[derive(Clone, Debug, Default, PartialEq)]
18229    struct ReplayCounterState {
18230        loaded: Option<String>,
18231        count: i64,
18232        finished: bool,
18233    }
18234
18235    fn replay_counter_worker() -> Worker {
18236        let client = Client::new("http://127.0.0.1:8080").expect("client");
18237        let mut worker = Worker::new(client, "rust-workers");
18238        worker.register_replayed_workflow(
18239            "replay-counter",
18240            ReplayCounterState::default,
18241            |ctx, _input, state| async move {
18242                let loaded = ctx.activity("load-counter", json!([])).await?;
18243                state.update(|current| {
18244                    current.loaded = loaded.as_str().map(str::to_string);
18245                })?;
18246                for _ in 0..2 {
18247                    let signal = ctx.wait_signal("increment").await?;
18248                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
18249                    state.update(|current| current.count += amount)?;
18250                }
18251                state.update(|current| current.finished = true)?;
18252                state.read(|current| Ok(json!(current.count)))?
18253            },
18254        );
18255        worker.register_replayed_query::<ReplayCounterState, _, _>(
18256            "replay-counter",
18257            "current",
18258            |_ctx, state, _args| async move {
18259                Ok(json!({
18260                    "loaded": state.loaded,
18261                    "count": state.count,
18262                    "finished": state.finished,
18263                }))
18264            },
18265        );
18266        worker.register_replayed_query::<ReplayCounterState, _, _>(
18267            "replay-counter",
18268            "detached-mutation",
18269            |_ctx, state, _args| async move {
18270                let mut detached = (*state).clone();
18271                detached.count = 999;
18272                Ok(json!(detached.count))
18273            },
18274        );
18275        worker.register_replayed_query::<ReplayCounterState, _, _>(
18276            "replay-counter",
18277            "failed-mutation",
18278            |_ctx, state, _args| async move {
18279                let mut detached = (*state).clone();
18280                detached.count = 999;
18281                Err(Error::WorkerLoop("query refused".to_string()))
18282            },
18283        );
18284        worker
18285    }
18286
18287    fn replay_counter_query(
18288        query_name: &str,
18289        history_events: Value,
18290        run_status: &str,
18291    ) -> QueryTask {
18292        let arguments = fixture_envelope(json!([]));
18293        serde_json::from_value(json!({
18294            "query_task_id": format!("query-{query_name}"),
18295            "workflow_type": "replay-counter",
18296            "query_name": query_name,
18297            "payload_codec": DEFAULT_CODEC,
18298            "workflow_arguments": arguments.clone(),
18299            "query_arguments": arguments,
18300            "history_events": history_events,
18301            "run_status": run_status,
18302        }))
18303        .expect("query task")
18304    }
18305
18306    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
18307        workflow_context_with_codec(history, DEFAULT_CODEC)
18308    }
18309
18310    fn workflow_context_with_codec(
18311        history: Vec<HistoryEvent>,
18312        payload_codec: &str,
18313    ) -> WorkflowContext {
18314        WorkflowContext {
18315            cancellation_scope_id: "root".into(),
18316            state: Arc::new(Mutex::new(
18317                WorkflowState::new_with_identity(
18318                    history,
18319                    None,
18320                    None,
18321                    "rust-workers".to_string(),
18322                    payload_codec.to_string(),
18323                    None,
18324                )
18325                .expect("valid workflow history"),
18326            )),
18327        }
18328    }
18329
18330    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
18331        HistoryEvent {
18332            event_type: event_type.to_string(),
18333            payload,
18334            raw: HashMap::new(),
18335        }
18336    }
18337
18338    fn parallel_path_entry(
18339        kind: &str,
18340        base: u64,
18341        size: usize,
18342        index: usize,
18343    ) -> ParallelGroupMetadata {
18344        parallel_group_entry(base, size, index, kind)
18345    }
18346
18347    fn parallel_history_event(
18348        event_type: &str,
18349        sequence: u64,
18350        identity_field: &str,
18351        identity: &str,
18352        path: Vec<ParallelGroupMetadata>,
18353        result: Option<Value>,
18354    ) -> HistoryEvent {
18355        let mut payload = serde_json::Map::from_iter([
18356            ("sequence".to_string(), json!(sequence)),
18357            (identity_field.to_string(), json!(identity)),
18358        ]);
18359        let inner = path.last().expect("parallel history path");
18360        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
18361        payload.insert("parallel_group_path".to_string(), json!(path));
18362        if let Some(result) = result {
18363            let field = if event_type == "ChildRunCompleted" {
18364                "result"
18365            } else {
18366                "result"
18367            };
18368            payload.insert(field.to_string(), fixture_envelope(result));
18369            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
18370        }
18371        history_event(event_type, Value::Object(payload))
18372    }
18373
18374    fn nested_parallel_operations() -> Vec<ParallelOperation> {
18375        vec![
18376            ParallelOperation::activity("first", json!([])),
18377            ParallelOperation::group(vec![
18378                ParallelOperation::child_workflow(
18379                    "second",
18380                    ChildWorkflowOptions::new("child-workers"),
18381                    json!([]),
18382                ),
18383                ParallelOperation::activity("third", json!([])),
18384            ]),
18385        ]
18386    }
18387
18388    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
18389        let outer = [
18390            parallel_path_entry("mixed", 1, 3, 0),
18391            parallel_path_entry("mixed", 1, 3, 1),
18392            parallel_path_entry("mixed", 1, 3, 2),
18393        ];
18394        [
18395            vec![outer[0].clone()],
18396            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
18397            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
18398        ]
18399    }
18400
18401    #[test]
18402    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
18403        let ctx = workflow_context(Vec::new());
18404        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18405        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18406
18407        assert!(matches!(
18408            call.as_mut().poll(&mut task_context),
18409            Poll::Pending
18410        ));
18411        let commands = ctx.take_commands().expect("parallel commands");
18412        assert_eq!(
18413            commands
18414                .iter()
18415                .map(|command| command["type"].as_str().unwrap_or_default())
18416                .collect::<Vec<_>>(),
18417            [
18418                "schedule_activity",
18419                "start_child_workflow",
18420                "schedule_activity"
18421            ]
18422        );
18423        let paths = nested_parallel_paths();
18424        for (command, path) in commands.iter().zip(paths) {
18425            assert_eq!(command["parallel_group_path"], json!(path));
18426            assert_eq!(
18427                command["parallel_group_id"],
18428                json!(path.last().expect("inner group").parallel_group_id)
18429            );
18430        }
18431    }
18432
18433    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
18434        let paths = nested_parallel_paths();
18435        let third = parallel_history_event(
18436            "ActivityCompleted",
18437            3,
18438            "activity_type",
18439            "third",
18440            paths[2].clone(),
18441            Some(json!("three")),
18442        );
18443        vec![
18444            parallel_history_event(
18445                "ActivityCompleted",
18446                1,
18447                "activity_type",
18448                "first",
18449                paths[0].clone(),
18450                Some(json!("one")),
18451            ),
18452            parallel_history_event(
18453                "ChildWorkflowScheduled",
18454                2,
18455                "child_workflow_type",
18456                "second",
18457                paths[1].clone(),
18458                None,
18459            ),
18460            parallel_history_event(
18461                "ChildRunCompleted",
18462                2,
18463                "child_workflow_type",
18464                "second",
18465                paths[1].clone(),
18466                Some(json!("two")),
18467            ),
18468            third.clone(),
18469            third,
18470        ]
18471    }
18472
18473    #[test]
18474    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
18475        for _restart_or_completed_replay in 0..2 {
18476            let ctx = workflow_context(completed_nested_parallel_history());
18477            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18478            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18479            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
18480                panic!("completed nested parallel history must replay");
18481            };
18482            assert_eq!(
18483                results,
18484                vec![
18485                    ParallelResult::Activity(json!("one")),
18486                    ParallelResult::Group(vec![
18487                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
18488                            parent: WorkflowIdentity {
18489                                workflow_id: None,
18490                                run_id: None,
18491                            },
18492                            child: WorkflowIdentity {
18493                                workflow_id: None,
18494                                run_id: None,
18495                            },
18496                            child_workflow_type: Some("second".to_string()),
18497                            result: json!("two"),
18498                        }),
18499                        ParallelResult::Activity(json!("three")),
18500                    ]),
18501                ]
18502            );
18503            assert!(ctx.take_commands().expect("commands").is_empty());
18504            ctx.ensure_history_consumed().expect("history consumed");
18505        }
18506    }
18507
18508    #[test]
18509    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
18510        let paths = nested_parallel_paths();
18511        let history = vec![
18512            parallel_history_event(
18513                "ActivityCompleted",
18514                1,
18515                "activity_type",
18516                "first",
18517                paths[0].clone(),
18518                Some(json!("one")),
18519            ),
18520            parallel_history_event(
18521                "ChildWorkflowScheduled",
18522                2,
18523                "child_workflow_type",
18524                "second",
18525                paths[1].clone(),
18526                None,
18527            ),
18528            parallel_history_event(
18529                "ChildRunFailed",
18530                2,
18531                "child_workflow_type",
18532                "second",
18533                paths[1].clone(),
18534                None,
18535            ),
18536            parallel_history_event(
18537                "ActivityCompleted",
18538                3,
18539                "activity_type",
18540                "third",
18541                paths[2].clone(),
18542                Some(json!("late")),
18543            ),
18544        ];
18545        let ctx = workflow_context(history);
18546        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18547        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18548        let outcome = call.as_mut().poll(&mut task_context);
18549        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
18550            panic!("one failed child must return a typed partial failure: {outcome:?}");
18551        };
18552        assert_eq!(failure.member_path, [1, 0]);
18553        assert_eq!(failure.group_id, "parallel-calls:1:3");
18554        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
18555        assert_eq!(
18556            failure
18557                .completed
18558                .iter()
18559                .map(|completion| completion.member_path.clone())
18560                .collect::<Vec<_>>(),
18561            [vec![0], vec![1, 1]]
18562        );
18563    }
18564
18565    #[test]
18566    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
18567        let paths = nested_parallel_paths();
18568        let history = vec![
18569            parallel_history_event(
18570                "ActivityScheduled",
18571                1,
18572                "activity_type",
18573                "first",
18574                paths[0].clone(),
18575                None,
18576            ),
18577            parallel_history_event(
18578                "ChildWorkflowScheduled",
18579                2,
18580                "child_workflow_type",
18581                "second",
18582                paths[1].clone(),
18583                None,
18584            ),
18585            parallel_history_event(
18586                "ActivityScheduled",
18587                3,
18588                "activity_type",
18589                "third",
18590                paths[2].clone(),
18591                None,
18592            ),
18593        ];
18594        for _restart in 0..2 {
18595            let ctx = workflow_context(history.clone());
18596            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18597            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18598            let outcome = call.as_mut().poll(&mut task_context);
18599            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
18600            assert!(ctx.take_commands().expect("commands").is_empty());
18601        }
18602    }
18603
18604    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
18605        vec![selection_group_entry(
18606            1,
18607            2,
18608            index,
18609            "activity",
18610            &SelectionMemberMetadata {
18611                key: SelectionKey::Name(key.to_string()),
18612                index,
18613                base_sequence: index as u64 + 1,
18614                size: 1,
18615                kind: "activity".to_string(),
18616            },
18617        )]
18618    }
18619
18620    fn selection_activity_event(
18621        event_type: &str,
18622        index: usize,
18623        key: &str,
18624        result: Option<Value>,
18625    ) -> HistoryEvent {
18626        let sequence = index as u64 + 1;
18627        let mut event = parallel_history_event(
18628            event_type,
18629            sequence,
18630            "activity_type",
18631            &format!("{key}-activity"),
18632            selection_path(index, key),
18633            result,
18634        );
18635        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
18636        event.raw.insert(
18637            "id".to_string(),
18638            json!(if event_type == "ActivityCompleted" {
18639                format!("event-{key}")
18640            } else {
18641                format!("{event_type}-{key}")
18642            }),
18643        );
18644        event
18645    }
18646
18647    fn selection_winner_marker() -> HistoryEvent {
18648        history_event(
18649            "SelectionResolved",
18650            json!({
18651                "selection_group_id": "select-calls:1:2",
18652                "selection_group_base_sequence": 1,
18653                "selection_group_size": 2,
18654                "member_key": "fast",
18655                "member_index": 1,
18656                "member_base_sequence": 2,
18657                "member_size": 1,
18658                "operation_kind": "activity",
18659                "operation_identity": "activity-fast",
18660                "outcome": "completed",
18661                "resolution_event_id": "event-fast",
18662                "resolution_event_type": "ActivityCompleted",
18663            }),
18664        )
18665    }
18666
18667    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
18668        ctx.select_keyed(vec![
18669            (
18670                "slow",
18671                ParallelOperation::activity_with_options(
18672                    "slow-activity",
18673                    ActivityOptions::new().task_queue("default"),
18674                    json!([]),
18675                ),
18676            ),
18677            (
18678                "fast",
18679                ParallelOperation::activity_with_options(
18680                    "fast-activity",
18681                    ActivityOptions::new().task_queue("default"),
18682                    json!([]),
18683                ),
18684            ),
18685        ])
18686    }
18687
18688    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
18689        let ctx = workflow_context(history);
18690        let mut call = Box::pin(keyed_activity_selection(&ctx));
18691        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18692        let selected = match call.as_mut().poll(&mut task_context) {
18693            Poll::Ready(Ok(selected)) => selected,
18694            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
18695            Poll::Pending => panic!("persisted selection winner must replay without pending"),
18696        };
18697        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
18698        assert_eq!(
18699            selected.value,
18700            Some(ParallelResult::Activity(json!("winner-value")))
18701        );
18702        let slow = selected
18703            .handle(&SelectionKey::Name("slow".to_string()))
18704            .expect("slow handle")
18705            .clone();
18706        let mut await_slow = Box::pin(slow.await_result());
18707        assert!(matches!(
18708            await_slow.as_mut().poll(&mut task_context),
18709            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
18710        ));
18711        assert!(ctx.take_commands().expect("commands").is_empty());
18712    }
18713
18714    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
18715
18716    fn canonical_selection_history() -> Vec<HistoryEvent> {
18717        const FIXTURE: &[u8] =
18718            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
18719        assert_eq!(
18720            format!("{:x}", Sha256::digest(FIXTURE)),
18721            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18722        );
18723        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
18724
18725        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
18726    }
18727
18728    #[test]
18729    fn selection_fresh_process_entrypoint() {
18730        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
18731            return;
18732        };
18733        let persisted = fs::read(path).expect("persisted selection history");
18734        assert_eq!(
18735            format!("{:x}", Sha256::digest(&persisted)),
18736            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18737        );
18738        let fixture: Value =
18739            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
18740        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
18741            .expect("valid persisted selection history");
18742
18743        assert_persisted_selection_replay(history);
18744    }
18745
18746    #[test]
18747    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
18748        let ctx = workflow_context(Vec::new());
18749        let mut call = Box::pin(keyed_activity_selection(&ctx));
18750        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18751
18752        assert!(matches!(
18753            call.as_mut().poll(&mut task_context),
18754            Poll::Pending
18755        ));
18756        let commands = ctx.take_commands().expect("selection commands");
18757        assert_eq!(commands.len(), 2);
18758        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
18759        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
18760        assert!(commands.iter().all(|command| {
18761            command["parallel_group_id"] == json!("select-calls:1:2")
18762                && command["parallel_group_mode"] == json!("select")
18763        }));
18764    }
18765
18766    #[test]
18767    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
18768        let ctx = workflow_context(Vec::new());
18769        let mut invalid = Box::pin(ctx.select_keyed(vec![(
18770            "",
18771            ParallelOperation::activity("invalid", json!([])),
18772        )]));
18773        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18774        assert!(matches!(
18775            invalid.as_mut().poll(&mut task_context),
18776            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
18777                reason: "selection_key_invalid",
18778                ..
18779            })))
18780        ));
18781
18782        for invalid_key in [json!(""), json!(-1)] {
18783            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
18784            event.payload["selection_member_key"] = invalid_key.clone();
18785            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
18786            assert!(matches!(
18787                WorkflowState::new_with_identity(
18788                    vec![event],
18789                    None,
18790                    None,
18791                    "rust-workers".to_string(),
18792                    DEFAULT_CODEC.to_string(),
18793                    None,
18794                ),
18795                Err(Error::NonDeterministicReplay(_))
18796            ));
18797        }
18798    }
18799
18800    #[test]
18801    fn selection_preserves_valid_named_and_numeric_keys() {
18802        let ctx = workflow_context(Vec::new());
18803        let mut selection = Box::pin(ctx.select_keyed(vec![
18804            (
18805                SelectionKey::Index(0),
18806                ParallelOperation::activity("numeric", json!([])),
18807            ),
18808            (
18809                SelectionKey::Name("named".to_string()),
18810                ParallelOperation::timer(Duration::from_secs(1)),
18811            ),
18812        ]));
18813        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18814
18815        assert!(matches!(
18816            selection.as_mut().poll(&mut task_context),
18817            Poll::Pending
18818        ));
18819        let commands = ctx.take_commands().expect("selection commands");
18820        assert_eq!(commands[0]["selection_member_key"], json!(0));
18821        assert_eq!(commands[1]["selection_member_key"], json!("named"));
18822    }
18823
18824    #[test]
18825    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
18826        let history = canonical_selection_history();
18827        assert_persisted_selection_replay(history.clone());
18828
18829        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18830            .join("tests/fixtures/durable_selection_runtime_history.json");
18831        let output =
18832            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
18833                .args([
18834                    "--exact",
18835                    "tests::selection_fresh_process_entrypoint",
18836                    "--nocapture",
18837                ])
18838                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
18839                .output()
18840                .expect("run fresh selection replay process");
18841
18842        assert!(
18843            output.status.success(),
18844            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
18845            String::from_utf8_lossy(&output.stdout),
18846            String::from_utf8_lossy(&output.stderr),
18847        );
18848    }
18849
18850    #[test]
18851    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
18852        let mut history = canonical_selection_history();
18853        history.retain(|event| event.event_type != "SelectionResolved");
18854        let ctx = workflow_context(history);
18855        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18856        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18857
18858        assert!(matches!(
18859            selection.as_mut().poll(&mut task_context),
18860            Poll::Pending
18861        ));
18862        assert!(ctx.take_commands().expect("commands").is_empty());
18863        assert!(
18864            ctx.matched_recorded_pending()
18865                .expect("selection pending state"),
18866            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
18867        );
18868    }
18869
18870    #[test]
18871    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18872        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18873            ("ConditionWaitSatisfied", true, None),
18874            ("ConditionWaitTimedOut", false, Some(0)),
18875        ] {
18876            let member = SelectionMemberMetadata {
18877                key: SelectionKey::Name("condition".to_string()),
18878                index: 0,
18879                base_sequence: 1,
18880                size: 1,
18881                kind: "condition".to_string(),
18882            };
18883            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18884            let mut payload = json!({
18885                "sequence": 1,
18886                "condition_wait_id": "condition-1",
18887                "condition_wait_occurrence_id": "rust:condition-wait:0",
18888                "condition_key": "ready",
18889                "condition_definition_fingerprint": "sha256:ready-v1",
18890                "parallel_group_path": path,
18891            });
18892            payload
18893                .as_object_mut()
18894                .expect("condition history payload")
18895                .extend(
18896                    serde_json::to_value(&path[0])
18897                        .expect("condition selection metadata")
18898                        .as_object()
18899                        .expect("condition selection metadata object")
18900                        .clone(),
18901                );
18902            if let Some(timeout_seconds) = timeout_seconds {
18903                payload["timeout_seconds"] = json!(timeout_seconds);
18904            }
18905            let history = vec![
18906                history_event("ConditionWaitOpened", payload.clone()),
18907                history_event(terminal_event, payload),
18908            ];
18909            let ctx = workflow_context(history);
18910            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18911            if timeout_seconds.is_some() {
18912                options = options.timeout(Duration::ZERO);
18913            }
18914            let mut selection = Box::pin(ctx.select_keyed(vec![(
18915                "condition",
18916                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18917            )]));
18918            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18919
18920            assert!(matches!(
18921                selection.as_mut().poll(&mut task_context),
18922                Poll::Pending
18923            ));
18924            assert!(ctx.take_commands().expect("commands").is_empty());
18925            assert!(
18926                ctx.matched_recorded_pending()
18927                    .expect("condition selection pending state"),
18928                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18929            );
18930        }
18931    }
18932
18933    #[test]
18934    fn selection_immediate_condition_members_open_a_durable_wait() {
18935        for predicate_satisfied in [true, false] {
18936            let ctx = workflow_context(Vec::new());
18937            let mut selection = Box::pin(ctx.select_keyed(vec![(
18938                "condition",
18939                ParallelOperation::condition(
18940                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18941                    move || Ok(predicate_satisfied),
18942                ),
18943            )]));
18944            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18945
18946            assert!(matches!(
18947                selection.as_mut().poll(&mut task_context),
18948                Poll::Pending
18949            ));
18950            let commands = ctx.take_commands().expect("condition selection command");
18951            assert_eq!(commands.len(), 1);
18952            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18953            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18954            assert_eq!(
18955                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18956                json!("select")
18957            );
18958        }
18959    }
18960
18961    #[test]
18962    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18963        let history = vec![
18964            selection_activity_event("ActivityScheduled", 0, "slow", None),
18965            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18966            selection_winner_marker(),
18967        ];
18968        let ctx = workflow_context(history.clone());
18969        let mut call = Box::pin(keyed_activity_selection(&ctx));
18970        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18971        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18972            panic!("winner must replay");
18973        };
18974        let slow = selected
18975            .handle(&SelectionKey::Name("slow".to_string()))
18976            .expect("slow handle")
18977            .clone();
18978        let mut cancel = Box::pin(slow.cancel());
18979        assert!(matches!(
18980            cancel.as_mut().poll(&mut task_context),
18981            Poll::Pending
18982        ));
18983        assert!(matches!(
18984            cancel.as_mut().poll(&mut task_context),
18985            Poll::Pending
18986        ));
18987        let commands = ctx.take_commands().expect("cancel command");
18988        assert_eq!(commands.len(), 1);
18989        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18990        assert_eq!(commands[0]["member_key"], json!("slow"));
18991
18992        let mut cancelled_history = history;
18993        cancelled_history.push(history_event(
18994            "SelectionOperationCancelled",
18995            json!({
18996                "selection_group_id": "select-calls:1:2",
18997                "member_key": "slow",
18998                "member_index": 0,
18999                "member_base_sequence": 1,
19000                "member_size": 1,
19001                "operation_kind": "activity",
19002                "operation_identity": "activity-slow",
19003                "cancelled_at": "2026-08-27T00:00:00Z",
19004            }),
19005        ));
19006        let replayed = workflow_context(cancelled_history);
19007        let mut call = Box::pin(keyed_activity_selection(&replayed));
19008        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19009            panic!("winner must replay after cancellation");
19010        };
19011        let slow = selected
19012            .handle(&SelectionKey::Name("slow".to_string()))
19013            .expect("slow handle")
19014            .clone();
19015        let mut cancel = Box::pin(slow.cancel());
19016        assert!(matches!(
19017            cancel.as_mut().poll(&mut task_context),
19018            Poll::Ready(Ok(()))
19019        ));
19020        assert!(replayed.take_commands().expect("commands").is_empty());
19021    }
19022
19023    #[test]
19024    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19025        let base_history = vec![
19026            selection_activity_event("ActivityScheduled", 0, "slow", None),
19027            selection_activity_event("ActivityScheduled", 1, "fast", None),
19028            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19029            selection_winner_marker(),
19030        ];
19031        for (field, corrupt) in [
19032            ("member_key", json!("fast")),
19033            ("member_index", json!(1)),
19034            ("member_base_sequence", json!(3)),
19035            ("member_size", json!(2)),
19036            ("operation_kind", json!("timer")),
19037            ("operation_identity", json!("forged")),
19038        ] {
19039            let mut cancellation = json!({
19040                "selection_group_id": "select-calls:1:2",
19041                "member_key": "slow",
19042                "member_index": 0,
19043                "member_base_sequence": 1,
19044                "member_size": 1,
19045                "operation_kind": "activity",
19046                "operation_identity": "activity-slow",
19047            });
19048            cancellation[field] = corrupt;
19049            let mut history = base_history.clone();
19050            history.push(history_event("SelectionOperationCancelled", cancellation));
19051            let ctx = workflow_context(history);
19052            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19053            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19054
19055            assert!(matches!(
19056                selection.as_mut().poll(&mut task_context),
19057                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19058            ));
19059        }
19060    }
19061
19062    #[test]
19063    fn selection_child_identity_prefers_the_durable_run_id() {
19064        let ctx = workflow_context(vec![history_event(
19065            "ChildWorkflowScheduled",
19066            json!({
19067                "sequence": 1,
19068                "child_workflow_type": "child",
19069                "child_workflow_instance_id": "child-instance",
19070                "child_workflow_run_id": "child-run",
19071            }),
19072        )]);
19073        let state = ctx.state.lock().expect("workflow state");
19074
19075        assert_eq!(
19076            selection_operation_identity(&state, "child", 1, 1),
19077            "child-run"
19078        );
19079    }
19080
19081    #[test]
19082    fn selection_activity_identity_requires_canonical_execution_id() {
19083        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19084        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19085        let mut fast_completed =
19086            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19087        for event in [&mut fast_open, &mut fast_completed] {
19088            event
19089                .payload
19090                .as_object_mut()
19091                .expect("activity payload")
19092                .remove("activity_execution_id");
19093            event.payload["activity_id"] = json!("forged-activity-id");
19094        }
19095        let mut marker = selection_winner_marker();
19096        marker.payload["operation_identity"] = json!("forged-activity-id");
19097        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19098        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19099        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19100
19101        assert!(matches!(
19102            selection.as_mut().poll(&mut task_context),
19103            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19104        ));
19105    }
19106
19107    #[test]
19108    fn selection_completion_before_cancellation_remains_awaitable() {
19109        let history = vec![
19110            selection_activity_event("ActivityScheduled", 0, "slow", None),
19111            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19112            selection_winner_marker(),
19113            selection_activity_event(
19114                "ActivityCompleted",
19115                0,
19116                "slow",
19117                Some(json!("completed-first")),
19118            ),
19119        ];
19120        let ctx = workflow_context(history);
19121        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19122        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19123        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19124            panic!("winner must replay");
19125        };
19126        let slow = selected
19127            .handle(&SelectionKey::Name("slow".to_string()))
19128            .expect("slow handle")
19129            .clone();
19130        let mut cancel = Box::pin(slow.cancel());
19131        assert!(matches!(
19132            cancel.as_mut().poll(&mut task_context),
19133            Poll::Ready(Ok(()))
19134        ));
19135        let mut await_slow = Box::pin(slow.await_result());
19136        assert!(matches!(
19137            await_slow.as_mut().poll(&mut task_context),
19138            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19139        ));
19140        let commands = ctx.take_commands().expect("commands");
19141        assert!(commands.is_empty());
19142    }
19143
19144    #[test]
19145    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
19146        let nested_member = SelectionMemberMetadata {
19147            key: SelectionKey::Name("nested".to_string()),
19148            index: 0,
19149            base_sequence: 1,
19150            size: 2,
19151            kind: "group".to_string(),
19152        };
19153        let deadline_member = SelectionMemberMetadata {
19154            key: SelectionKey::Name("deadline".to_string()),
19155            index: 1,
19156            base_sequence: 3,
19157            size: 1,
19158            kind: "timer".to_string(),
19159        };
19160        let nested_paths = [
19161            vec![
19162                selection_group_entry(1, 3, 0, "mixed", &nested_member),
19163                parallel_group_entry(1, 2, 0, "activity"),
19164            ],
19165            vec![
19166                selection_group_entry(1, 3, 1, "mixed", &nested_member),
19167                parallel_group_entry(1, 2, 1, "activity"),
19168            ],
19169        ];
19170        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
19171        let mut timer_fired = parallel_history_event(
19172            "TimerFired",
19173            3,
19174            "timer_id",
19175            "timer-3",
19176            deadline_path.clone(),
19177            None,
19178        );
19179        timer_fired.payload["delay_seconds"] = json!(0);
19180        timer_fired
19181            .raw
19182            .insert("id".to_string(), json!("timer-fired"));
19183        let mut timer_scheduled = parallel_history_event(
19184            "TimerScheduled",
19185            3,
19186            "timer_id",
19187            "timer-3",
19188            deadline_path,
19189            None,
19190        );
19191        timer_scheduled.payload["delay_seconds"] = json!(0);
19192        let history = vec![
19193            parallel_history_event(
19194                "ActivityScheduled",
19195                1,
19196                "activity_type",
19197                "nested-first",
19198                nested_paths[0].clone(),
19199                None,
19200            ),
19201            parallel_history_event(
19202                "ActivityScheduled",
19203                2,
19204                "activity_type",
19205                "nested-second",
19206                nested_paths[1].clone(),
19207                None,
19208            ),
19209            timer_scheduled,
19210            timer_fired,
19211            history_event(
19212                "SelectionResolved",
19213                json!({
19214                    "selection_group_id": "select-calls:1:3",
19215                    "selection_group_base_sequence": 1,
19216                    "selection_group_size": 3,
19217                    "member_key": "deadline",
19218                    "member_index": 1,
19219                    "member_base_sequence": 3,
19220                    "member_size": 1,
19221                    "operation_kind": "timer",
19222                    "operation_identity": "timer-3",
19223                    "outcome": "completed",
19224                    "resolution_event_id": "timer-fired",
19225                    "resolution_event_type": "TimerFired",
19226                }),
19227            ),
19228            parallel_history_event(
19229                "ActivityFailed",
19230                2,
19231                "activity_type",
19232                "nested-second",
19233                nested_paths[1].clone(),
19234                None,
19235            ),
19236        ];
19237        let ctx = workflow_context(history);
19238        let mut selection = Box::pin(ctx.select_keyed(vec![
19239            (
19240                "nested",
19241                ParallelOperation::group(vec![
19242                    ParallelOperation::activity("nested-first", json!([])),
19243                    ParallelOperation::activity("nested-second", json!([])),
19244                ]),
19245            ),
19246            ("deadline", ParallelOperation::timer(Duration::ZERO)),
19247        ]));
19248        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19249        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19250            panic!("deadline winner must replay");
19251        };
19252        let nested = selected
19253            .handle(&SelectionKey::Name("nested".to_string()))
19254            .expect("nested handle")
19255            .clone();
19256        let mut cancel = Box::pin(nested.cancel());
19257        assert!(matches!(
19258            cancel.as_mut().poll(&mut task_context),
19259            Poll::Ready(Ok(()))
19260        ));
19261        let mut await_nested = Box::pin(nested.await_result());
19262
19263        assert!(matches!(
19264            await_nested.as_mut().poll(&mut task_context),
19265            Poll::Ready(Err(Error::ActivityFailed(_)))
19266        ));
19267        assert!(ctx.take_commands().expect("commands").is_empty());
19268    }
19269
19270    #[test]
19271    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
19272        let ctx = workflow_context(Vec::new());
19273        let mut call = Box::pin(ctx.select(vec![
19274            ParallelOperation::child_workflow(
19275                "child",
19276                ChildWorkflowOptions::new("children"),
19277                json!([]),
19278            ),
19279            ParallelOperation::timer(Duration::from_secs(30)),
19280            ParallelOperation::signal("approval"),
19281            ParallelOperation::condition(
19282                ConditionWaitOptions::new("ready", "sha256:ready"),
19283                || Ok(false),
19284            ),
19285            ParallelOperation::group(vec![
19286                ParallelOperation::activity("nested-one", json!([])),
19287                ParallelOperation::activity("nested-two", json!([])),
19288            ]),
19289        ]));
19290        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19291        assert!(matches!(
19292            call.as_mut().poll(&mut task_context),
19293            Poll::Pending
19294        ));
19295        let commands = ctx.take_commands().expect("selection commands");
19296        assert_eq!(
19297            commands
19298                .iter()
19299                .map(|command| command["type"].as_str().unwrap_or_default())
19300                .collect::<Vec<_>>(),
19301            [
19302                "start_child_workflow",
19303                "start_timer",
19304                "open_signal_wait",
19305                "open_condition_wait",
19306                "schedule_activity",
19307                "schedule_activity",
19308            ]
19309        );
19310        assert!(commands.iter().all(|command| {
19311            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
19312        }));
19313        assert_eq!(
19314            commands[4]["parallel_group_path"].as_array().map(Vec::len),
19315            Some(2)
19316        );
19317        assert_eq!(
19318            commands[4]["parallel_group_path"][0]["selection_member_kind"],
19319            json!("group")
19320        );
19321        assert_eq!(
19322            commands[5]["parallel_group_path"][0]["selection_member_kind"],
19323            json!("group")
19324        );
19325
19326        let one_leaf_ctx = workflow_context(Vec::new());
19327        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
19328            ParallelOperation::activity("nested-only", json!([])),
19329        ])]));
19330        assert!(matches!(
19331            one_leaf.as_mut().poll(&mut task_context),
19332            Poll::Pending
19333        ));
19334        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
19335        assert_eq!(one_leaf_commands.len(), 1);
19336        assert_eq!(
19337            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
19338            json!("group")
19339        );
19340        assert_eq!(
19341            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
19342            json!(1)
19343        );
19344    }
19345
19346    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
19347        let mut saga = ctx.saga();
19348        let outcome = async {
19349            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19350            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19351            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
19352            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
19353            ctx.activity("trip.charge", json!([])).await?;
19354            Ok(json!({"status": "booked"}))
19355        }
19356        .await;
19357        saga.finish(outcome).await
19358    }
19359
19360    fn saga_activity(
19361        event_type: &str,
19362        sequence: u64,
19363        activity_type: &str,
19364        result: Option<Value>,
19365    ) -> HistoryEvent {
19366        let mut payload = json!({
19367            "sequence": sequence,
19368            "activity_type": activity_type,
19369            "message": format!("{activity_type} failed"),
19370            "exception_type": "PlannedFailure",
19371            "non_retryable": true,
19372        });
19373        if let Some(result) = result {
19374            payload["result"] = fixture_envelope(result);
19375        }
19376        history_event(event_type, payload)
19377    }
19378
19379    #[test]
19380    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
19381        let completed_hotel_compensation = saga_activity(
19382            "ActivityCompleted",
19383            4,
19384            "trip.cancel-hotel",
19385            Some(Value::Null),
19386        );
19387        let history = vec![
19388            saga_activity(
19389                "ActivityCompleted",
19390                1,
19391                "trip.reserve-flight",
19392                Some(json!("flight-1")),
19393            ),
19394            saga_activity(
19395                "ActivityCompleted",
19396                2,
19397                "trip.reserve-hotel",
19398                Some(json!("hotel-1")),
19399            ),
19400            saga_activity("ActivityFailed", 3, "trip.charge", None),
19401            completed_hotel_compensation.clone(),
19402            completed_hotel_compensation,
19403        ];
19404
19405        for _restart in 0..2 {
19406            let ctx = workflow_context(history.clone());
19407            let mut future = Box::pin(trip_saga(ctx.clone()));
19408            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19409            assert!(matches!(
19410                future.as_mut().poll(&mut task_context),
19411                Poll::Pending
19412            ));
19413            let commands = ctx.take_commands().expect("compensation command");
19414            assert_eq!(commands.len(), 1);
19415            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19416        }
19417    }
19418
19419    #[test]
19420    fn saga_compensation_failure_preserves_both_typed_failures() {
19421        let history = vec![
19422            saga_activity(
19423                "ActivityCompleted",
19424                1,
19425                "trip.reserve-flight",
19426                Some(json!("flight-1")),
19427            ),
19428            saga_activity(
19429                "ActivityCompleted",
19430                2,
19431                "trip.reserve-hotel",
19432                Some(json!("hotel-1")),
19433            ),
19434            saga_activity("ActivityFailed", 3, "trip.charge", None),
19435            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
19436        ];
19437        let ctx = workflow_context(history);
19438        let mut future = Box::pin(trip_saga(ctx));
19439        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19440        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
19441            future.as_mut().poll(&mut task_context)
19442        else {
19443            panic!("compensation failure must remain structured");
19444        };
19445        assert!(matches!(
19446            *failure.initiating_failure,
19447            Error::ActivityFailed(_)
19448        ));
19449        assert!(matches!(
19450            *failure.compensation_failure,
19451            Error::ActivityFailed(_)
19452        ));
19453        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
19454        assert_eq!(failure.compensation_registration_order, 2);
19455    }
19456
19457    #[test]
19458    fn saga_compensates_cooperative_cancellation() {
19459        let ctx = workflow_context(vec![saga_activity(
19460            "ActivityCompleted",
19461            1,
19462            "trip.reserve-flight",
19463            Some(json!("flight-1")),
19464        )]);
19465        ctx.state.lock().expect("state").cancel_requested = true;
19466        let run = {
19467            let ctx = ctx.clone();
19468            async move {
19469                let mut saga = ctx.saga();
19470                let outcome = async {
19471                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19472                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19473                    ctx.throw_if_cancellation_requested()?;
19474                    Ok(json!("unexpected"))
19475                }
19476                .await;
19477                saga.finish(outcome).await
19478            }
19479        };
19480        let mut future = Box::pin(run);
19481        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19482        assert!(matches!(
19483            future.as_mut().poll(&mut task_context),
19484            Poll::Pending
19485        ));
19486        let commands = ctx.take_commands().expect("cancellation compensation");
19487        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19488    }
19489
19490    fn workflow_task(
19491        workflow_type: &str,
19492        history_events: Vec<HistoryEvent>,
19493        payload_codec: &str,
19494    ) -> WorkflowTask {
19495        WorkflowTask {
19496            task_id: format!("wft-{workflow_type}"),
19497            workflow_command_id: None,
19498            workflow_id: Some(format!("wf-{workflow_type}")),
19499            run_id: Some(format!("run-{workflow_type}")),
19500            workflow_type: workflow_type.to_string(),
19501            cancel_requested: false,
19502            payload_codec: payload_codec.to_string(),
19503            arguments: Some(
19504                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
19505            ),
19506            total_history_events: Some(history_events.len() as u64),
19507            history_size_bytes: None,
19508            continue_as_new_recommended: None,
19509            history_budget_pressure: None,
19510            history_events,
19511            next_history_page_token: None,
19512            workflow_task_attempt: 1,
19513            workflow_signal_id: None,
19514            signal_name: None,
19515            signal_arguments: None,
19516            workflow_update_id: None,
19517            update_name: None,
19518            lease_owner: Some("rust-worker".to_string()),
19519        }
19520    }
19521
19522    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19523    struct SideEffectProbe {
19524        request_id: String,
19525        attempt: u32,
19526    }
19527
19528    #[test]
19529    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
19530        let calls = AtomicUsize::new(0);
19531        let ctx = workflow_context(Vec::new());
19532        let value = ctx
19533            .side_effect(|| {
19534                calls.fetch_add(1, Ordering::SeqCst);
19535                SideEffectProbe {
19536                    request_id: "request-42".to_string(),
19537                    attempt: 3,
19538                }
19539            })
19540            .expect("first side effect");
19541        assert_eq!(value.attempt, 3);
19542        assert_eq!(calls.load(Ordering::SeqCst), 1);
19543        let commands = ctx.take_commands().expect("commands");
19544        assert_eq!(commands.len(), 1);
19545        assert_eq!(commands[0]["type"], "record_side_effect");
19546        assert_eq!(
19547            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19548            serde_json::to_value(&value).expect("value")
19549        );
19550
19551        let replay = workflow_context(vec![history_event(
19552            "SideEffectRecorded",
19553            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19554        )]);
19555        let replayed: SideEffectProbe = replay
19556            .side_effect(|| {
19557                calls.fetch_add(1, Ordering::SeqCst);
19558                panic!("committed side-effect callbacks must not run during replay")
19559            })
19560            .expect("replayed side effect");
19561        assert_eq!(replayed, value);
19562        assert_eq!(calls.load(Ordering::SeqCst), 1);
19563        assert!(replay.take_commands().expect("commands").is_empty());
19564        replay.ensure_history_consumed().expect("history consumed");
19565    }
19566
19567    #[test]
19568    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
19569        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19570        let value = ctx
19571            .side_effect(|| SideEffectProbe {
19572                request_id: "avro-request".to_string(),
19573                attempt: 1,
19574            })
19575            .expect("Avro side effect");
19576        let uuid = ctx.uuid_v4().expect("deterministic UUID");
19577        let commands = ctx.take_commands().expect("commands");
19578        assert_eq!(commands.len(), 2);
19579        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
19580        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
19581        assert_eq!(
19582            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19583            serde_json::to_value(&value).expect("value")
19584        );
19585
19586        let replay = workflow_context_with_codec(
19587            vec![
19588                history_event(
19589                    "SideEffectRecorded",
19590                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19591                ),
19592                history_event(
19593                    "SideEffectRecorded",
19594                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
19595                ),
19596            ],
19597            DEFAULT_CODEC,
19598        );
19599        let replayed: SideEffectProbe = replay
19600            .side_effect(|| panic!("Avro callback must not run"))
19601            .expect("replayed Avro value");
19602        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
19603        assert_eq!(replayed, value);
19604        assert_eq!(replayed_uuid, uuid);
19605        assert!(replay.take_commands().expect("commands").is_empty());
19606    }
19607
19608    #[test]
19609    fn typed_side_effect_replay_preserves_bytes_and_maps() {
19610        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19611        let value = ctx
19612            .side_effect_avro_value(typed_fidelity_probe)
19613            .expect("typed side effect");
19614        let commands = ctx.take_commands().expect("side-effect command");
19615        assert_eq!(
19616            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19617                .expect("recorded side effect"),
19618            value
19619        );
19620
19621        let replay = workflow_context_with_codec(
19622            vec![history_event(
19623                "SideEffectRecorded",
19624                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19625            )],
19626            DEFAULT_CODEC,
19627        );
19628        assert_eq!(
19629            replay
19630                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
19631                .expect("replayed typed side effect"),
19632            value
19633        );
19634    }
19635
19636    #[test]
19637    fn ordered_side_effects_share_the_durable_command_stream() {
19638        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
19639        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
19640        let ctx = workflow_context(vec![
19641            history_event(
19642                "SideEffectRecorded",
19643                json!({"sequence": 1, "result": first}),
19644            ),
19645            history_event(
19646                "SideEffectRecorded",
19647                json!({"sequence": 2, "result": second}),
19648            ),
19649        ]);
19650        let first: String = ctx
19651            .side_effect(|| panic!("first callback must not run"))
19652            .expect("first replay");
19653        let second: i32 = ctx
19654            .side_effect(|| panic!("second callback must not run"))
19655            .expect("second replay");
19656        assert_eq!(first, "first");
19657        assert_eq!(second, 29);
19658        ctx.ensure_history_consumed().expect("ordered history");
19659
19660        let reordered = workflow_context(vec![history_event(
19661            "VersionMarkerRecorded",
19662            json!({
19663                "sequence": 1,
19664                "change_id": "before-side-effect",
19665                "version": 1,
19666                "min_supported": 1,
19667                "max_supported": 1,
19668            }),
19669        )]);
19670        let error = reordered
19671            .side_effect(|| "new".to_string())
19672            .expect_err("command reordering must fail");
19673        assert!(matches!(
19674            error,
19675            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19676                if reason == "recorded_command_mismatch"
19677        ));
19678    }
19679
19680    #[test]
19681    fn legacy_patch_preserves_pending_and_completed_activity_history() {
19682        for completed in [false, true] {
19683            let mut history = vec![history_event(
19684                "ActivityScheduled",
19685                json!({"sequence": 1, "activity_type": "old"}),
19686            )];
19687            if completed {
19688                history.push(history_event(
19689                    "ActivityCompleted",
19690                    json!({
19691                        "sequence": 1,
19692                        "activity_type": "old",
19693                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
19694                    }),
19695                ));
19696            }
19697            for _cold_replay in 0..2 {
19698                let ctx = workflow_context(history.clone());
19699                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
19700                assert!(!ctx.patched("added-step").expect("same frozen decision"));
19701                ctx.deprecate_patch("added-step")
19702                    .expect("retained boundary");
19703                let mut activity = Box::pin(ctx.activity("old", json!([])));
19704                let mut context = TaskContext::from_waker(noop_waker_ref());
19705                match activity.as_mut().poll(&mut context) {
19706                    Poll::Ready(result) => {
19707                        assert!(completed);
19708                        assert_eq!(result.expect("recorded result"), json!(41));
19709                        ctx.ensure_history_consumed().expect("old command retained");
19710                    }
19711                    Poll::Pending => assert!(!completed),
19712                }
19713                assert!(ctx.take_commands().expect("commands").is_empty());
19714            }
19715        }
19716    }
19717
19718    #[test]
19719    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
19720        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
19721        assert!(!ctx.patched("added-step").expect("legacy completed run"));
19722        ctx.deprecate_patch("added-step")
19723            .expect("same legacy decision");
19724        assert!(ctx.take_commands().expect("commands").is_empty());
19725        ctx.ensure_history_consumed().expect("completed history");
19726    }
19727
19728    #[test]
19729    fn legacy_patch_rejects_a_range_without_the_original_branch() {
19730        let ctx = workflow_context(vec![history_event(
19731            "ActivityScheduled",
19732            json!({"sequence": 1, "activity_type": "old"}),
19733        )]);
19734        let error = ctx
19735            .get_version("added-step", 0, 1)
19736            .expect_err("legacy is unsupported");
19737        assert!(matches!(
19738            error,
19739            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19740                if reason == "version_marker_incompatible_range"
19741        ));
19742        assert!(!ctx
19743            .patched("supported-step")
19744            .expect("failed check did not consume history"));
19745        assert!(ctx.take_commands().expect("commands").is_empty());
19746    }
19747
19748    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
19749        let mut event = history_event(
19750            "VersionMarkerRecorded",
19751            json!({
19752                "sequence": sequence,
19753                "change_id": "retained-patch",
19754                "version": version,
19755                "min_supported": -1,
19756                "max_supported": 1,
19757            }),
19758        );
19759        event.raw.insert("timestamp".into(), json!(time));
19760        event
19761    }
19762
19763    #[test]
19764    fn retained_patch_markers_preserve_each_original_boundary() {
19765        for completed in [false, true] {
19766            let mut history = vec![
19767                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19768                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19769                history_event(
19770                    "ActivityScheduled",
19771                    json!({"sequence": 3, "activity_type": "old"}),
19772                ),
19773            ];
19774            if completed {
19775                history.push(history_event(
19776                    "ActivityCompleted",
19777                    json!({
19778                        "sequence": 3,
19779                        "activity_type": "old",
19780                        "result": fixture_envelope(json!(41)),
19781                    }),
19782                ));
19783            }
19784            for _cold_replay in 0..2 {
19785                let ctx = workflow_context(history.clone());
19786                assert!(ctx.patched("retained-patch").unwrap());
19787                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19788                assert!(ctx.patched("retained-patch").unwrap());
19789                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19790                ctx.deprecate_patch("retained-patch").unwrap();
19791                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19792                let mut activity = Box::pin(ctx.activity("old", json!([])));
19793                let mut context = TaskContext::from_waker(noop_waker_ref());
19794                match activity.as_mut().poll(&mut context) {
19795                    Poll::Ready(result) => {
19796                        assert!(completed);
19797                        assert_eq!(result.unwrap(), json!(41));
19798                        ctx.ensure_history_consumed().unwrap();
19799                    }
19800                    Poll::Pending => assert!(!completed),
19801                }
19802                assert!(ctx.take_commands().unwrap().is_empty());
19803                let state = ctx.state.lock().unwrap();
19804                for (actual, original) in state.history_events.iter().zip(&history) {
19805                    assert_eq!(actual.payload, original.payload);
19806                    assert_eq!(actual.raw, original.raw);
19807                }
19808            }
19809        }
19810    }
19811
19812    #[test]
19813    fn retained_patch_aliases_do_not_skip_intervening_operations() {
19814        let ctx = workflow_context(vec![
19815            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19816            history_event(
19817                "SideEffectRecorded",
19818                json!({
19819                    "sequence": 2, "result": fixture_envelope(json!("between")),
19820                }),
19821            ),
19822            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
19823            history_event(
19824                "VersionMarkerRecorded",
19825                json!({
19826                    "sequence": 4, "change_id": "other-patch", "version": 1,
19827                    "min_supported": -1, "max_supported": 1,
19828                }),
19829            ),
19830        ]);
19831        assert!(ctx.patched("retained-patch").unwrap());
19832        assert!(ctx.patched("retained-patch").unwrap());
19833        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19834        assert_eq!(
19835            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19836            "between"
19837        );
19838        ctx.deprecate_patch("retained-patch").unwrap();
19839        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19840        ctx.deprecate_patch("retained-patch").unwrap();
19841        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19842        assert!(ctx.patched("other-patch").unwrap());
19843        ctx.ensure_history_consumed().unwrap();
19844        assert!(ctx.take_commands().unwrap().is_empty());
19845    }
19846
19847    #[test]
19848    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
19849        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19850        alias.payload["max_supported"] = json!(3);
19851        let ctx = workflow_context(vec![
19852            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19853            alias,
19854        ]);
19855        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
19856        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
19857        assert!(matches!(error,
19858            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19859                if reason == "version_marker_incompatible_range"));
19860        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19861        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
19862        ctx.ensure_history_consumed().unwrap();
19863        assert!(ctx.take_commands().unwrap().is_empty());
19864    }
19865
19866    #[test]
19867    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
19868        let ctx = workflow_context(Vec::new());
19869        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
19870        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
19871        assert!(ctx.patched("new-search").expect("patch"));
19872        ctx.deprecate_patch("new-search").expect("deprecate patch");
19873        let commands = ctx.take_commands().expect("commands");
19874        assert_eq!(commands.len(), 2);
19875        assert_eq!(commands[0]["type"], "record_version_marker");
19876        assert_eq!(commands[0]["version"], 2);
19877        assert_eq!(commands[1]["change_id"], "new-search");
19878
19879        let replay = workflow_context(vec![history_event(
19880            "VersionMarkerRecorded",
19881            json!({
19882                "sequence": 1,
19883                "change_id": "checkout-v2",
19884                "version": 2,
19885                "min_supported": 1,
19886                "max_supported": 2,
19887            }),
19888        )]);
19889        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
19890        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
19891        assert!(replay.take_commands().expect("commands").is_empty());
19892        replay.ensure_history_consumed().expect("history consumed");
19893    }
19894
19895    #[test]
19896    fn version_markers_reject_incompatible_or_malformed_history() {
19897        let incompatible = workflow_context(vec![history_event(
19898            "VersionMarkerRecorded",
19899            json!({
19900                "sequence": 1,
19901                "change_id": "checkout-v2",
19902                "version": 1,
19903                "min_supported": 1,
19904                "max_supported": 2,
19905            }),
19906        )]);
19907        let error = incompatible
19908            .get_version("checkout-v2", 2, 3)
19909            .expect_err("old version is unsupported");
19910        assert!(matches!(
19911            error,
19912            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19913                if reason == "version_marker_incompatible_range"
19914        ));
19915
19916        for (history, reason) in [
19917            (
19918                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
19919                "side_effect_result_missing",
19920            ),
19921            (
19922                vec![history_event(
19923                    "SideEffectRecorded",
19924                    json!({
19925                        "sequence": 1,
19926                        "result": {"codec": "avro", "blob": "not-base64"},
19927                    }),
19928                )],
19929                "side_effect_payload_incompatible",
19930            ),
19931            (
19932                vec![history_event(
19933                    "SideEffectRecorded",
19934                    json!({"sequence": 1, "result": {"unwrapped": true}}),
19935                )],
19936                "side_effect_payload_malformed",
19937            ),
19938            (
19939                vec![history_event(
19940                    "VersionMarkerRecorded",
19941                    json!({
19942                        "sequence": 1,
19943                        "change_id": "change",
19944                        "version": 1,
19945                        "min_supported": 2,
19946                        "max_supported": 1,
19947                    }),
19948                )],
19949                "version_marker_history_range_invalid",
19950            ),
19951        ] {
19952            let error = WorkflowState::new(
19953                history,
19954                "rust-workers".to_string(),
19955                DEFAULT_CODEC.to_string(),
19956                None,
19957            )
19958            .expect_err("malformed history must fail");
19959            assert!(matches!(
19960                error,
19961                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
19962                    if actual == reason
19963            ));
19964        }
19965    }
19966
19967    #[test]
19968    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
19969        let history = vec![history_event(
19970            "SearchAttributesUpserted",
19971            json!({
19972                "sequence": 1,
19973                "attributes": {"customer_tier": "gold"},
19974                "attribute_types": {"customer_tier": "keyword"},
19975                "merged": {"customer_tier": "gold"}
19976            }),
19977        )];
19978
19979        let matching = workflow_context(history.clone());
19980        matching
19981            .upsert_search_attributes(
19982                SearchAttributeUpdate::new()
19983                    .keyword("customer_tier", "gold")
19984                    .expect("keyword update"),
19985            )
19986            .expect("matching typed update must replay");
19987        matching
19988            .ensure_history_consumed()
19989            .expect("history consumed");
19990
19991        let changed_type = workflow_context(history.clone());
19992        let error = changed_type
19993            .upsert_search_attributes(
19994                SearchAttributeUpdate::new()
19995                    .string("customer_tier", "gold")
19996                    .expect("string update"),
19997            )
19998            .expect_err("same JSON value with a different declaration must be nondeterministic");
19999        let Error::NonDeterministicReplay(failure) = error else {
20000            panic!("typed identity drift must be a replay failure");
20001        };
20002        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20003        assert_eq!(failure.sequence, Some(1));
20004
20005        let changed_value = workflow_context(history);
20006        let error = changed_value
20007            .upsert_search_attributes(
20008                SearchAttributeUpdate::new()
20009                    .keyword("customer_tier", "platinum")
20010                    .expect("keyword update"),
20011            )
20012            .expect_err("changed values must be nondeterministic");
20013        let Error::NonDeterministicReplay(failure) = error else {
20014            panic!("value drift must be a replay failure");
20015        };
20016        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20017    }
20018
20019    #[test]
20020    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20021        let history = vec![history_event(
20022            "SearchAttributesUpserted",
20023            json!({
20024                "sequence": 1,
20025                "attributes": {"customer_tier": "gold"},
20026                "merged": {"customer_tier": "gold"}
20027            }),
20028        )];
20029
20030        for update in [
20031            SearchAttributeUpdate::new()
20032                .keyword("customer_tier", "gold")
20033                .expect("keyword update"),
20034            SearchAttributeUpdate::new()
20035                .string("customer_tier", "gold")
20036                .expect("string update"),
20037        ] {
20038            let restarted = workflow_context(history.clone());
20039            restarted
20040                .upsert_search_attributes(update)
20041                .expect("legacy history constrains values but has unknown type identity");
20042            restarted
20043                .ensure_history_consumed()
20044                .expect("history consumed");
20045        }
20046    }
20047
20048    #[test]
20049    fn search_attribute_command_emits_canonical_types() {
20050        let ctx = workflow_context(Vec::new());
20051        ctx.upsert_search_attributes(
20052            SearchAttributeUpdate::new()
20053                .keyword("customer_tier", "gold")
20054                .expect("keyword update")
20055                .int("attempts", 3)
20056                .expect("int update")
20057                .delete("obsolete")
20058                .expect("delete update"),
20059        )
20060        .expect("valid search attributes");
20061
20062        assert_eq!(
20063            ctx.take_commands().expect("commands"),
20064            vec![json!({
20065                "type": "upsert_search_attributes",
20066                "attributes": {
20067                    "attempts": 3,
20068                    "customer_tier": "gold",
20069                    "obsolete": null
20070                },
20071                "attribute_types": {
20072                    "attempts": "int",
20073                    "customer_tier": "keyword"
20074                }
20075            })]
20076        );
20077    }
20078
20079    #[test]
20080    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
20081        let duplicate_side_effect = WorkflowState::new(
20082            vec![
20083                history_event(
20084                    "SideEffectRecorded",
20085                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
20086                ),
20087                history_event(
20088                    "SideEffectRecorded",
20089                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
20090                ),
20091            ],
20092            "rust-workers".to_string(),
20093            DEFAULT_CODEC.to_string(),
20094            None,
20095        )
20096        .expect_err("duplicate side effect");
20097        assert!(matches!(
20098            duplicate_side_effect,
20099            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20100                if reason == "duplicate_side_effect_record"
20101        ));
20102
20103        let marker = |sequence, version| {
20104            history_event(
20105                "VersionMarkerRecorded",
20106                json!({
20107                    "sequence": sequence,
20108                    "change_id": "same-change",
20109                    "version": version,
20110                    "min_supported": -1,
20111                    "max_supported": 1,
20112                }),
20113            )
20114        };
20115        let duplicate_marker = WorkflowState::new(
20116            vec![marker(1, 1), marker(3, -1)],
20117            "rust-workers".to_string(),
20118            DEFAULT_CODEC.to_string(),
20119            None,
20120        )
20121        .expect_err("conflicting marker");
20122        assert!(matches!(
20123            duplicate_marker,
20124            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20125                if reason == "version_marker_conflict"
20126        ));
20127    }
20128
20129    #[test]
20130    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
20131        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
20132        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20133        invalid_alias.payload["max_supported"] = json!(0);
20134        for (history, expected_reason) in [
20135            (
20136                vec![marker.clone(), marker.clone()],
20137                "duplicate_version_marker_record",
20138            ),
20139            (
20140                vec![marker, invalid_alias],
20141                "version_marker_history_range_invalid",
20142            ),
20143        ] {
20144            let error =
20145                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
20146                    .expect_err("invalid historical alias");
20147            assert!(matches!(error,
20148                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
20149                    if reason == expected_reason));
20150        }
20151    }
20152
20153    #[test]
20154    fn retained_patch_aliases_require_the_original_call_boundary() {
20155        let ctx = workflow_context(vec![
20156            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20157            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20158        ]);
20159        assert!(ctx.patched("retained-patch").unwrap());
20160        assert!(ctx.ensure_history_consumed().is_err());
20161        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20162        ctx.deprecate_patch("retained-patch").unwrap();
20163        ctx.ensure_history_consumed().unwrap();
20164        assert!(ctx.take_commands().unwrap().is_empty());
20165    }
20166
20167    #[test]
20168    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
20169        let ctx = workflow_context(vec![
20170            history_event(
20171                "SideEffectRecorded",
20172                json!({
20173                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
20174                }),
20175            ),
20176            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20177        ]);
20178        assert!(!ctx.patched("retained-patch").unwrap());
20179        assert_eq!(
20180            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20181            "old-operation"
20182        );
20183        let error = ctx.patched("retained-patch").unwrap_err();
20184        assert!(matches!(error,
20185            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20186                if reason == "version_marker_conflict"));
20187        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20188        assert!(ctx.take_commands().unwrap().is_empty());
20189    }
20190
20191    #[test]
20192    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
20193        let mut state = WorkflowState::new(
20194            Vec::new(),
20195            "rust-workers".to_string(),
20196            DEFAULT_CODEC.to_string(),
20197            None,
20198        )
20199        .expect("workflow state");
20200        state.workflow_command_identity = "command-7".to_string();
20201        let context = WorkflowContext {
20202            state: Arc::new(Mutex::new(state)),
20203            cancellation_scope_id: "root".into(),
20204        };
20205        let item =
20206            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
20207
20208        context
20209            .append_workflow_stream("output", &[item], Some(10))
20210            .expect("append command");
20211        context
20212            .error_workflow_stream("output", "producer failed", None)
20213            .expect("error command");
20214        let commands = context.take_commands().expect("commands");
20215
20216        assert_eq!(commands[0]["type"], "record_side_effect");
20217        assert_eq!(
20218            commands[0]["workflow_stream"]["command_identity"],
20219            "command-7"
20220        );
20221        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
20222        assert_eq!(
20223            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20224            "dw-stream:command-7:0:0"
20225        );
20226        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
20227
20228        let recorded = history_event(
20229            "SideEffectRecorded",
20230            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
20231        );
20232        let mut replay_state = WorkflowState::new(
20233            vec![recorded],
20234            "rust-workers".to_string(),
20235            DEFAULT_CODEC.to_string(),
20236            None,
20237        )
20238        .expect("replay state");
20239        replay_state.workflow_command_identity = "command-7".to_string();
20240        let replay_context = WorkflowContext {
20241            state: Arc::new(Mutex::new(replay_state)),
20242            cancellation_scope_id: "root".into(),
20243        };
20244        replay_context
20245            .append_workflow_stream(
20246                "output",
20247                &[WorkflowStreamAppendItem::from_reference(
20248                    "s3://bucket/item.avro",
20249                )],
20250                Some(10),
20251            )
20252            .expect("replayed append");
20253        assert!(replay_context
20254            .take_commands()
20255            .expect("replayed commands")
20256            .is_empty());
20257    }
20258
20259    #[test]
20260    fn workflow_stream_authoring_requires_server_durable_command_identity() {
20261        let context = workflow_context(Vec::new());
20262        let error = context
20263            .append_workflow_stream(
20264                "output",
20265                &[WorkflowStreamAppendItem::from_reference(
20266                    "s3://bucket/item.avro",
20267                )],
20268                None,
20269            )
20270            .expect_err("stream append without durable command identity must fail closed");
20271
20272        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
20273        assert!(context.take_commands().expect("commands").is_empty());
20274    }
20275
20276    #[test]
20277    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
20278        let client = Client::builder("http://localhost:8080").build().unwrap();
20279        let mut worker = Worker::new(client, "rust-workers");
20280        worker.register_workflow("streams.worker", |ctx, _| async move {
20281            ctx.append_workflow_stream(
20282                "output",
20283                &[WorkflowStreamAppendItem::new(json!("hello"))?],
20284                None,
20285            )?;
20286            ctx.close_workflow_stream("output", None)?;
20287            Ok(json!("done"))
20288        });
20289        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
20290            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20291            task.workflow_command_id = command_id.clone();
20292            let expected_identity = command_id
20293                .as_deref()
20294                .filter(|id| !id.is_empty())
20295                .unwrap_or(&task.task_id)
20296                .to_string();
20297            let commands = worker
20298                .execute_workflow_task(task)
20299                .expect("ordinary worker stream output");
20300            assert_eq!(commands.len(), 3);
20301            assert_eq!(
20302                commands[0]["workflow_stream"]["command_identity"],
20303                expected_identity
20304            );
20305            assert_eq!(
20306                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20307                format!("dw-stream:{expected_identity}:0:0")
20308            );
20309            assert_eq!(
20310                commands[1]["workflow_stream"]["command_identity"],
20311                expected_identity
20312            );
20313            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
20314            let history = commands[..2]
20315                .iter()
20316                .enumerate()
20317                .map(|(index, command)| {
20318                    history_event(
20319                        "SideEffectRecorded",
20320                        json!({"sequence":index + 1,"result":command["result"]}),
20321                    )
20322                })
20323                .collect();
20324            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
20325            replay.task_id = "replacement-task".to_string();
20326            let replayed = worker
20327                .execute_workflow_task(replay)
20328                .expect("replacement worker consumes recorded stream effects");
20329            assert_eq!(replayed.len(), 1);
20330            assert_eq!(replayed[0]["type"], "complete_workflow");
20331        }
20332        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20333        missing.task_id.clear();
20334        assert!(matches!(
20335            worker.execute_workflow_task(missing),
20336            Err(Error::MissingWorkflowCommandIdentity)
20337        ));
20338    }
20339
20340    #[test]
20341    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
20342        fn worker(calls: Arc<AtomicUsize>) -> Worker {
20343            let client = Client::new("http://127.0.0.1:8080").expect("client");
20344            let mut worker = Worker::new(client, "rust-workers");
20345            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
20346                let calls = Arc::clone(&calls);
20347                async move {
20348                    let captured = ctx.side_effect(|| {
20349                        calls.fetch_add(1, Ordering::SeqCst);
20350                        "captured-once".to_string()
20351                    })?;
20352                    let version = ctx.get_version("cold-restart", 1, 2)?;
20353                    Ok(json!({"captured": captured, "version": version}))
20354                }
20355            });
20356            worker
20357        }
20358
20359        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
20360            WorkflowTask {
20361                task_id: "wft-side-effect-version".to_string(),
20362                workflow_command_id: None,
20363                workflow_id: Some("wf-side-effect-version".to_string()),
20364                run_id: Some("run-side-effect-version".to_string()),
20365                workflow_type: "rust.side-effect-version".to_string(),
20366                cancel_requested: false,
20367                payload_codec: DEFAULT_CODEC.to_string(),
20368                arguments: Some(
20369                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
20370                ),
20371                history_events,
20372                total_history_events: None,
20373                history_size_bytes: None,
20374                continue_as_new_recommended: None,
20375                history_budget_pressure: None,
20376                next_history_page_token: None,
20377                workflow_task_attempt: 1,
20378                workflow_signal_id: None,
20379                signal_name: None,
20380                signal_arguments: None,
20381                workflow_update_id: None,
20382                update_name: None,
20383                lease_owner: Some("rust-worker".to_string()),
20384            }
20385        }
20386
20387        let calls = Arc::new(AtomicUsize::new(0));
20388        let initial = worker(Arc::clone(&calls))
20389            .execute_workflow_task(task(Vec::new()))
20390            .expect("initial execution");
20391        assert_eq!(
20392            initial
20393                .iter()
20394                .map(|command| &command["type"])
20395                .collect::<Vec<_>>(),
20396            vec![
20397                "record_side_effect",
20398                "record_version_marker",
20399                "complete_workflow"
20400            ]
20401        );
20402        assert_eq!(calls.load(Ordering::SeqCst), 1);
20403
20404        let restarted = worker(Arc::clone(&calls));
20405        let replayed = restarted
20406            .execute_workflow_task(task(vec![
20407                history_event(
20408                    "SideEffectRecorded",
20409                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
20410                ),
20411                history_event(
20412                    "VersionMarkerRecorded",
20413                    json!({
20414                        "sequence": 2,
20415                        "change_id": "cold-restart",
20416                        "version": 2,
20417                        "min_supported": 1,
20418                        "max_supported": 2,
20419                    }),
20420                ),
20421            ]))
20422            .expect("cold replay");
20423        assert_eq!(replayed.len(), 1);
20424        assert_eq!(replayed[0]["type"], "complete_workflow");
20425        assert_eq!(calls.load(Ordering::SeqCst), 1);
20426    }
20427
20428    #[test]
20429    fn side_effect_replay_rejects_changed_rust_value_type() {
20430        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
20431        let ctx = workflow_context(vec![history_event(
20432            "SideEffectRecorded",
20433            json!({"sequence": 1, "result": result}),
20434        )]);
20435        let error = ctx
20436            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
20437            .expect_err("changed type must fail replay");
20438        assert!(matches!(
20439            error,
20440            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20441                if reason == "side_effect_type_mismatch"
20442        ));
20443    }
20444
20445    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
20446        vec![
20447            history_event(
20448                "ActivityScheduled",
20449                json!({
20450                    "sequence": 1,
20451                    "activity_type": "flaky",
20452                    "activity_execution_id": "act-1",
20453                    "activity": {
20454                        "id": "act-1",
20455                        "sequence": 1,
20456                        "type": "flaky",
20457                        "queue": "critical-activities",
20458                        "execution_mode": null,
20459                        "retry_policy": {
20460                            "snapshot_version": 1,
20461                            "max_attempts": 3,
20462                            "backoff_seconds": [2, 4],
20463                            "start_to_close_timeout": 30,
20464                            "schedule_to_start_timeout": 5,
20465                            "schedule_to_close_timeout": 90,
20466                            "heartbeat_timeout": 10,
20467                            "non_retryable_error_types": ["PermanentError"]
20468                        }
20469                    }
20470                }),
20471            ),
20472            history_event(
20473                "ActivityStarted",
20474                json!({
20475                    "sequence": 1,
20476                    "activity_type": "flaky",
20477                    "activity_execution_id": "act-1",
20478                    "activity_attempt_id": "attempt-1",
20479                    "attempt_number": 1
20480                }),
20481            ),
20482            history_event(
20483                "ActivityRetryScheduled",
20484                json!({
20485                    "sequence": 1,
20486                    "activity_type": "flaky",
20487                    "activity_execution_id": "act-1",
20488                    "activity_attempt_id": "attempt-1",
20489                    "attempt_number": 1,
20490                    "retry_after_attempt": 1,
20491                    "retry_backoff_seconds": 2,
20492                    "failure_category": "activity",
20493                    "exception_type": "TransientError"
20494                }),
20495            ),
20496            history_event(
20497                "ActivityStarted",
20498                json!({
20499                    "sequence": 1,
20500                    "activity_type": "flaky",
20501                    "activity_execution_id": "act-1",
20502                    "activity_attempt_id": "attempt-2",
20503                    "attempt_number": 2
20504                }),
20505            ),
20506            history_event(
20507                "ActivityCompleted",
20508                json!({
20509                    "sequence": 1,
20510                    "activity_type": "flaky",
20511                    "activity_execution_id": "act-1",
20512                    "activity_attempt_id": "attempt-2",
20513                    "attempt_number": 2,
20514                    "payload_codec": DEFAULT_CODEC,
20515                    "result": fixture_envelope(json!({"status":"recovered"}))
20516                }),
20517            ),
20518        ]
20519    }
20520
20521    fn retry_activity_options() -> ActivityOptions {
20522        ActivityOptions::new()
20523            .task_queue("critical-activities")
20524            .retry_policy(
20525                ActivityRetryPolicy::new(3)
20526                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
20527                    .non_retryable_error_type("PermanentError"),
20528            )
20529            .start_to_close_timeout(Duration::from_secs(30))
20530            .schedule_to_start_timeout(Duration::from_secs(5))
20531            .schedule_to_close_timeout(Duration::from_secs(90))
20532            .heartbeat_timeout(Duration::from_secs(10))
20533    }
20534
20535    #[test]
20536    fn fixed_avro_value_round_trips_json_values() {
20537        let value = json!({"greeting": "hello", "count": 3, "ok": true});
20538        let envelope = PayloadEnvelope::avro(&value).expect("encode");
20539        assert_eq!(envelope.codec, DEFAULT_CODEC);
20540        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
20541    }
20542
20543    #[tokio::test]
20544    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
20545        let client = Client::new("http://127.0.0.1:8080").expect("client");
20546        let mut worker = Worker::new(client, "rust-workers");
20547        worker.register_typed_workflow(
20548            "typed.contract.workflow",
20549            |_ctx, input: TypedContract| async move { Ok(input) },
20550        );
20551        worker.register_typed_activity(
20552            "typed.contract.activity",
20553            |_ctx, input: TypedContract| async move { Ok(input) },
20554        );
20555
20556        let expected = typed_contract();
20557        let arguments = AvroValue::Array(vec![
20558            AvroValue::from_serialize(&expected).expect("typed request")
20559        ]);
20560        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
20561        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
20562        workflow.arguments = Some(envelope.clone());
20563        let commands = worker
20564            .execute_workflow_task(workflow)
20565            .expect("typed workflow task");
20566        let workflow_result: TypedContract =
20567            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20568                .expect("workflow result envelope")
20569                .deserialize()
20570                .expect("workflow result type");
20571        assert_eq!(workflow_result, expected);
20572
20573        let activity = ActivityTask {
20574            task_id: "typed-contract-activity".to_string(),
20575            activity_attempt_id: Some("typed-contract-attempt".to_string()),
20576            attempt_id: None,
20577            activity_type: "typed.contract.activity".to_string(),
20578            payload_codec: DEFAULT_CODEC.to_string(),
20579            arguments: Some(envelope),
20580            attempt_number: 1,
20581            lease_owner: Some("rust-worker".to_string()),
20582        };
20583        let activity_result: TypedContract = worker
20584            .execute_activity_task(activity)
20585            .await
20586            .expect("typed activity task")
20587            .deserialize()
20588            .expect("activity result type");
20589        assert_eq!(activity_result, expected);
20590    }
20591
20592    #[tokio::test]
20593    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
20594        let client = Client::new("http://127.0.0.1:8080").expect("client");
20595        let mut worker = Worker::new(client, "rust-workers");
20596        worker.register_typed_workflow(
20597            "typed.shape.workflow",
20598            |_ctx, input: TypedContract| async move { Ok(input) },
20599        );
20600        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
20601            Ok(f64::NAN)
20602        });
20603
20604        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
20605        workflow.arguments = Some(
20606            encode_typed_envelope(
20607                &AvroValue::Array(vec![
20608                    AvroValue::String("first".to_string()),
20609                    AvroValue::String("second".to_string()),
20610                ]),
20611                DEFAULT_CODEC,
20612            )
20613            .expect("malformed typed arguments"),
20614        );
20615        let commands = worker
20616            .execute_workflow_task(workflow)
20617            .expect("shape mismatch becomes a workflow failure");
20618        let message = commands[0]["message"].as_str().expect("failure message");
20619        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
20620        assert!(message.contains(type_name::<TypedContract>()));
20621        assert!(message.contains("task carried 2 arguments"));
20622
20623        let activity = ActivityTask {
20624            task_id: "typed-unsupported-activity".to_string(),
20625            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
20626            attempt_id: None,
20627            activity_type: "typed.unsupported.activity".to_string(),
20628            payload_codec: DEFAULT_CODEC.to_string(),
20629            arguments: Some(
20630                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20631                    .expect("unit arguments"),
20632            ),
20633            attempt_number: 1,
20634            lease_owner: Some("rust-worker".to_string()),
20635        };
20636        let Error::HandlerType {
20637            handler_kind,
20638            handler_name,
20639            value_kind,
20640            rust_type,
20641            message,
20642        } = worker
20643            .execute_activity_task(activity)
20644            .await
20645            .expect_err("non-finite handler output must fail")
20646        else {
20647            panic!("expected contextual handler type failure");
20648        };
20649        assert_eq!(handler_kind, HandlerKind::Activity);
20650        assert_eq!(handler_name, "typed.unsupported.activity");
20651        assert_eq!(value_kind, HandlerValueKind::Result);
20652        assert_eq!(rust_type, type_name::<f64>());
20653        assert!(message.contains("non_finite_float"));
20654    }
20655
20656    #[tokio::test]
20657    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
20658        #[derive(Clone, Default)]
20659        struct State {
20660            observed: Option<TypedContract>,
20661        }
20662
20663        let client = Client::new("http://127.0.0.1:8080").expect("client");
20664        let mut worker = Worker::new(client, "rust-workers");
20665        worker.register_typed_replayed_workflow(
20666            "typed.contract.replayed",
20667            State::default,
20668            |ctx, input: TypedContract, state| async move {
20669                let result: TypedContract =
20670                    ctx.activity_typed("typed.contract.activity", input).await?;
20671                state.update(|current| current.observed = Some(result.clone()))?;
20672                Ok(result)
20673            },
20674        );
20675        worker.register_replayed_query::<State, _, _>(
20676            "typed.contract.replayed",
20677            "observed",
20678            |_ctx, state, _args| async move {
20679                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
20680            },
20681        );
20682
20683        let expected = typed_contract();
20684        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
20685        let workflow_arguments =
20686            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
20687                .expect("workflow arguments");
20688        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
20689        let task = QueryTask {
20690            query_task_id: "typed-replay-query".to_string(),
20691            query_task_attempt: 1,
20692            lease_owner: Some("rust-worker".to_string()),
20693            workflow_id: Some("typed-replay".to_string()),
20694            run_id: Some("typed-replay-run".to_string()),
20695            workflow_type: "typed.contract.replayed".to_string(),
20696            query_name: "observed".to_string(),
20697            payload_codec: DEFAULT_CODEC.to_string(),
20698            workflow_arguments: Some(workflow_arguments),
20699            query_arguments: Some(
20700                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20701                    .expect("query arguments"),
20702            ),
20703            history_events: vec![
20704                history_event(
20705                    "ActivityScheduled",
20706                    json!({
20707                        "sequence": 1,
20708                        "activity_type": "typed.contract.activity"
20709                    }),
20710                ),
20711                history_event(
20712                    "ActivityCompleted",
20713                    json!({
20714                        "sequence": 1,
20715                        "activity_type": "typed.contract.activity",
20716                        "payload_codec": DEFAULT_CODEC,
20717                        "result": result
20718                    }),
20719                ),
20720            ],
20721            history_export: None,
20722            run_status: Some("completed".to_string()),
20723        };
20724
20725        assert_eq!(
20726            worker
20727                .execute_query_task(task)
20728                .await
20729                .expect("typed replay query")
20730                .deserialize::<i64>()
20731                .expect("query result"),
20732            expected.signed
20733        );
20734    }
20735
20736    #[tokio::test]
20737    async fn update_context_preserves_workflow_input_and_committed_signals() {
20738        let client = Client::new("http://127.0.0.1:8080").expect("client");
20739        let mut worker = Worker::new(client, "rust-workers");
20740        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20741        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
20742        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
20743        let expected_input = workflow_input.clone();
20744        let expected_signals = signal_arguments.clone();
20745        let handler = move |context: QueryContext, arguments: AvroValue| {
20746            let expected_input = expected_input.clone();
20747            let expected_signals = expected_signals.clone();
20748            async move {
20749                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
20750                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
20751                assert_eq!(context.workflow_input_avro_value(), &expected_input);
20752                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
20753                assert_eq!(
20754                    context.signals_avro_value("changed"),
20755                    vec![expected_signals.clone()]
20756                );
20757                assert_eq!(
20758                    context.signals("changed"),
20759                    vec![expected_signals
20760                        .into_iter()
20761                        .map(AvroValue::into_json)
20762                        .collect::<Result<Vec<_>>>()?]
20763                );
20764                assert_eq!(
20765                    context.signal_events()[0].id.as_deref(),
20766                    Some("signal-original")
20767                );
20768                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
20769                Ok(arguments)
20770            }
20771        };
20772        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
20773        worker.register_update_avro_value("snapshot", "inspect", handler);
20774        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
20775        let update_envelope =
20776            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
20777        let mut task = workflow_task(
20778            "snapshot",
20779            vec![
20780                history_event(
20781                    "SignalReceived",
20782                    json!({
20783                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
20784                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
20785                    }),
20786                ),
20787                history_event(
20788                    "UpdateAccepted",
20789                    json!({
20790                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
20791                    }),
20792                ),
20793            ],
20794            DEFAULT_CODEC,
20795        );
20796        task.arguments =
20797            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
20798        task.workflow_update_id = Some("update-original".into());
20799        task.update_name = Some("inspect".into());
20800        let query = QueryTask {
20801            query_task_id: "query-snapshot".into(),
20802            query_task_attempt: 1,
20803            lease_owner: None,
20804            workflow_id: task.workflow_id.clone(),
20805            run_id: task.run_id.clone(),
20806            workflow_type: task.workflow_type.clone(),
20807            query_name: "inspect".into(),
20808            payload_codec: DEFAULT_CODEC.into(),
20809            workflow_arguments: task.arguments.clone(),
20810            query_arguments: Some(update_envelope),
20811            history_events: task.history_events.clone(),
20812            history_export: None,
20813            run_status: Some("running".into()),
20814        };
20815        assert_eq!(
20816            worker
20817                .execute_query_task(query)
20818                .await
20819                .expect("query snapshot"),
20820            update_arguments
20821        );
20822        for _ in 0..2 {
20823            let commands = worker
20824                .execute_workflow_task(task.clone())
20825                .expect("cold update snapshot");
20826            assert_eq!(commands[0]["type"], "complete_update");
20827            assert_eq!(commands[0]["update_id"], "update-original");
20828            assert_eq!(
20829                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20830                    .expect("update result"),
20831                update_arguments
20832            );
20833        }
20834    }
20835
20836    #[test]
20837    fn committed_signal_snapshot_counts_identities_once() {
20838        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
20839        let received = history_event(
20840            "SignalReceived",
20841            json!({
20842                "signal_id": "signal-first", "workflow_command_id": "command-first",
20843                "signal_name": "changed", "arguments": arguments.clone(),
20844            }),
20845        );
20846        let applied = history_event(
20847            "SignalApplied",
20848            json!({
20849                "signal_id": "signal-first", "workflow_command_id": "command-first",
20850                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
20851            }),
20852        );
20853        let distinct = history_event(
20854            "SignalReceived",
20855            json!({
20856                "signal_id": "signal-second", "workflow_command_id": "command-second",
20857                "signal_name": "changed", "arguments": arguments,
20858            }),
20859        );
20860        let history = vec![received.clone(), applied.clone(), distinct];
20861        let signals =
20862            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
20863        assert_eq!(signals.len(), 2);
20864        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20865        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
20866        assert_eq!(signals[0].workflow_sequence, Some(1));
20867        assert_eq!(signals[0].arguments, signals[1].arguments);
20868        let mut command_only = received.clone();
20869        command_only
20870            .payload
20871            .as_object_mut()
20872            .expect("payload")
20873            .remove("signal_id");
20874        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
20875            .expect("command identity");
20876        assert_eq!(signals.len(), 1);
20877        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20878        let mut conflicting = applied;
20879        conflicting.payload["value"] =
20880            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
20881        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
20882    }
20883
20884    #[test]
20885    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
20886        for arguments in [
20887            vec![],
20888            vec![AvroValue::Array(vec![
20889                AvroValue::Long(1),
20890                AvroValue::Long(2),
20891            ])],
20892            vec![AvroValue::Bytes(vec![0, 255])],
20893            vec![AvroValue::Null],
20894            vec![AvroValue::Boolean(false)],
20895            vec![
20896                AvroValue::Long(1),
20897                AvroValue::Array(vec![AvroValue::Long(2)]),
20898            ],
20899        ] {
20900            let applied = match arguments.as_slice() {
20901                [] => AvroValue::Boolean(true),
20902                [value] => value.clone(),
20903                values => AvroValue::Array(values.to_vec()),
20904            };
20905            for applied in [applied, AvroValue::Array(arguments.clone())] {
20906                let events = vec![
20907                    history_event(
20908                        "SignalReceived",
20909                        json!({
20910                            "signal_id": "original", "signal_name": "changed",
20911                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
20912                        }),
20913                    ),
20914                    history_event(
20915                        "SignalApplied",
20916                        json!({
20917                            "signal_id": "original", "signal_name": "changed",
20918                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
20919                        }),
20920                    ),
20921                ];
20922                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
20923                    .expect("canonical signal snapshot");
20924                assert_eq!(signals.len(), 1);
20925                assert_eq!(signals[0].avro_arguments, arguments);
20926            }
20927        }
20928    }
20929
20930    #[tokio::test]
20931    async fn update_context_rejects_malformed_snapshot_before_handler() {
20932        let client = Client::new("http://127.0.0.1:8080").expect("client");
20933        let mut worker = Worker::new(client, "rust-workers");
20934        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20935        let calls = Arc::new(AtomicUsize::new(0));
20936        let observed = Arc::clone(&calls);
20937        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
20938            observed.fetch_add(1, Ordering::SeqCst);
20939            async { Ok(Value::Null) }
20940        });
20941        let mut task = workflow_task(
20942            "snapshot",
20943            vec![history_event(
20944                "UpdateAccepted",
20945                json!({
20946                    "update_id": "update-original", "update_name": "inspect",
20947                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
20948                }),
20949            )],
20950            DEFAULT_CODEC,
20951        );
20952        task.workflow_update_id = Some("update-original".into());
20953        task.update_name = Some("inspect".into());
20954        let mut bad_input = task.clone();
20955        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
20956        assert!(worker.execute_workflow_task(bad_input).is_err());
20957        task.history_events.insert(0, history_event("SignalReceived", json!({
20958            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
20959        })));
20960        assert!(worker.execute_workflow_task(task).is_err());
20961        assert_eq!(calls.load(Ordering::SeqCst), 0);
20962    }
20963
20964    #[tokio::test]
20965    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
20966        let client = Client::new("http://127.0.0.1:8080").expect("client");
20967        let mut worker = Worker::new(client, "rust-workers");
20968        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
20969        worker
20970            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
20971        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
20972            Ok(input)
20973        });
20974        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
20975            Ok(input)
20976        });
20977        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
20978            Ok(AvroValue::Array(
20979                ctx.wait_signal_avro_value("changed").await?,
20980            ))
20981        });
20982
20983        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
20984        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
20985
20986        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
20987        workflow.arguments = Some(envelope.clone());
20988        let commands = worker
20989            .execute_workflow_task(workflow)
20990            .expect("typed workflow task");
20991        assert_eq!(commands[0]["type"], "complete_workflow");
20992        assert_eq!(
20993            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20994                .expect("typed workflow result"),
20995            arguments
20996        );
20997
20998        let activity = ActivityTask {
20999            task_id: "activity-typed".to_string(),
21000            activity_attempt_id: Some("attempt-typed".to_string()),
21001            attempt_id: None,
21002            activity_type: "typed.activity".to_string(),
21003            payload_codec: DEFAULT_CODEC.to_string(),
21004            arguments: Some(envelope.clone()),
21005            attempt_number: 1,
21006            lease_owner: Some("rust-worker".to_string()),
21007        };
21008        assert_eq!(
21009            worker
21010                .execute_activity_task(activity)
21011                .await
21012                .expect("typed activity result"),
21013            arguments
21014        );
21015
21016        let query = QueryTask {
21017            query_task_id: "query-typed".to_string(),
21018            query_task_attempt: 1,
21019            lease_owner: Some("rust-worker".to_string()),
21020            workflow_id: Some("typed-1".to_string()),
21021            run_id: Some("run-typed".to_string()),
21022            workflow_type: "typed.echo".to_string(),
21023            query_name: "inspect".to_string(),
21024            payload_codec: DEFAULT_CODEC.to_string(),
21025            workflow_arguments: Some(
21026                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21027                    .expect("workflow input"),
21028            ),
21029            query_arguments: Some(envelope.clone()),
21030            history_events: Vec::new(),
21031            history_export: None,
21032            run_status: Some("running".to_string()),
21033        };
21034        assert_eq!(
21035            worker
21036                .execute_query_task(query)
21037                .await
21038                .expect("typed query result"),
21039            arguments
21040        );
21041
21042        let mut update = workflow_task(
21043            "typed.echo",
21044            vec![history_event(
21045                "UpdateAccepted",
21046                json!({
21047                    "update_id": "update-typed",
21048                    "update_name": "replace",
21049                    "arguments": envelope.clone(),
21050                }),
21051            )],
21052            DEFAULT_CODEC,
21053        );
21054        update.workflow_update_id = Some("update-typed".to_string());
21055        update.update_name = Some("replace".to_string());
21056        let commands = worker
21057            .execute_workflow_task(update)
21058            .expect("typed update task");
21059        assert_eq!(commands[0]["type"], "complete_update");
21060        assert_eq!(
21061            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21062                .expect("typed update result"),
21063            arguments
21064        );
21065
21066        let mut signal = workflow_task(
21067            "typed.signal",
21068            vec![history_event(
21069                "SignalReceived",
21070                json!({
21071                    "signal_id": "signal-typed",
21072                    "signal_name": "changed",
21073                    "arguments": envelope.clone(),
21074                }),
21075            )],
21076            DEFAULT_CODEC,
21077        );
21078        signal.workflow_signal_id = Some("signal-typed".to_string());
21079        signal.signal_name = Some("changed".to_string());
21080        signal.signal_arguments = Some(envelope);
21081        let commands = worker
21082            .execute_workflow_task(signal)
21083            .expect("typed signal resume");
21084        assert_eq!(
21085            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21086                .expect("typed signal result"),
21087            arguments
21088        );
21089    }
21090
21091    #[tokio::test]
21092    async fn typed_helpers_never_parse_json_inspection_projection() {
21093        let collision_values = projection_collision_probe();
21094        let expected = AvroValue::Array(collision_values.clone());
21095        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
21096
21097        let activity_context = workflow_context_with_codec(
21098            vec![history_event(
21099                "ActivityCompleted",
21100                json!({
21101                    "sequence": 1,
21102                    "activity_type": "collision.activity",
21103                    "payload_codec": DEFAULT_CODEC,
21104                    "result": envelope.clone(),
21105                }),
21106            )],
21107            DEFAULT_CODEC,
21108        );
21109        assert_eq!(
21110            activity_context
21111                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
21112                .await
21113                .expect("typed activity collision result"),
21114            expected
21115        );
21116
21117        let signal_context = workflow_context_with_codec(
21118            vec![
21119                history_event(
21120                    "SignalWaitOpened",
21121                    json!({"sequence": 1, "signal_name": "collision"}),
21122                ),
21123                history_event(
21124                    "SignalApplied",
21125                    json!({
21126                        "sequence": 1,
21127                        "signal_name": "collision",
21128                        "payload_codec": DEFAULT_CODEC,
21129                        "value": envelope.clone(),
21130                    }),
21131                ),
21132            ],
21133            DEFAULT_CODEC,
21134        );
21135        assert_eq!(
21136            signal_context
21137                .wait_signal_avro_value("collision")
21138                .await
21139                .expect("typed signal collision arguments"),
21140            collision_values
21141        );
21142
21143        let child_context = workflow_context_with_codec(
21144            vec![
21145                history_event(
21146                    "ChildWorkflowScheduled",
21147                    json!({
21148                        "sequence": 1,
21149                        "child_workflow_instance_id": "collision-child",
21150                        "child_workflow_run_id": "collision-run",
21151                        "child_workflow_type": "collision.child",
21152                    }),
21153                ),
21154                history_event(
21155                    "ChildRunCompleted",
21156                    json!({
21157                        "sequence": 1,
21158                        "child_workflow_instance_id": "collision-child",
21159                        "child_workflow_run_id": "collision-run",
21160                        "child_workflow_type": "collision.child",
21161                        "payload_codec": DEFAULT_CODEC,
21162                        "result": envelope,
21163                    }),
21164                ),
21165            ],
21166            DEFAULT_CODEC,
21167        );
21168        let child = child_context
21169            .start_child_workflow_avro_value(
21170                "collision.child",
21171                ChildWorkflowOptions::new("collision-workers"),
21172                AvroValue::Array(Vec::new()),
21173            )
21174            .await
21175            .expect("typed child collision result");
21176        assert_eq!(child.result, expected);
21177    }
21178
21179    #[tokio::test]
21180    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
21181        let client = Client::new("http://127.0.0.1:8080").expect("client");
21182        let mut worker = Worker::new(client, "rust-workers");
21183        worker.register_replayed_workflow_avro_value(
21184            "typed.replayed",
21185            || (),
21186            |_ctx, input, _state| async move { Ok(input) },
21187        );
21188        worker.register_replayed_query_avro_value::<(), _, _>(
21189            "typed.replayed",
21190            "inspect",
21191            |ctx, _state, args| async move {
21192                let mut signals = ctx.signals_avro_value("collision");
21193                let signal = signals
21194                    .pop()
21195                    .map(AvroValue::Array)
21196                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
21197                Ok(AvroValue::Array(vec![
21198                    ctx.workflow_input_avro_value().clone(),
21199                    signal,
21200                    args,
21201                ]))
21202            },
21203        );
21204        let arguments = AvroValue::Array(projection_collision_probe());
21205        let signal_arguments =
21206            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
21207        let task = QueryTask {
21208            query_task_id: "query-typed-replay".to_string(),
21209            query_task_attempt: 1,
21210            lease_owner: Some("rust-worker".to_string()),
21211            workflow_id: Some("typed-replay".to_string()),
21212            run_id: Some("run-typed-replay".to_string()),
21213            workflow_type: "typed.replayed".to_string(),
21214            query_name: "inspect".to_string(),
21215            payload_codec: DEFAULT_CODEC.to_string(),
21216            workflow_arguments: Some(
21217                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
21218            ),
21219            query_arguments: Some(
21220                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
21221            ),
21222            history_events: vec![history_event(
21223                "SignalReceived",
21224                json!({
21225                    "signal_id": "collision-signal",
21226                    "signal_name": "collision",
21227                    "workflow_sequence": 1,
21228                    "payload_codec": DEFAULT_CODEC,
21229                    "arguments": signal_arguments,
21230                }),
21231            )],
21232            history_export: None,
21233            run_status: Some("completed".to_string()),
21234        };
21235
21236        assert_eq!(
21237            worker
21238                .execute_query_task(task)
21239                .await
21240                .expect("typed replay query"),
21241            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
21242        );
21243    }
21244
21245    #[test]
21246    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
21247        let value = BTreeMap::from([(1_i32, "integer key")]);
21248        let error = PayloadEnvelope::avro(&value)
21249            .expect_err("integer map keys must fail")
21250            .to_string();
21251
21252        assert!(error.contains("invalid_map_key"));
21253    }
21254
21255    #[test]
21256    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
21257        let envelope = PayloadEnvelope {
21258            codec: "json".to_string(),
21259            blob: r#"{"greeting":"hello"}"#.to_string(),
21260        };
21261
21262        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
21263        let diagnostic = error.to_string();
21264        assert!(diagnostic.contains("unsupported_payload_codec"));
21265        assert!(diagnostic.contains("codec=\"avro\""));
21266        assert!(diagnostic.contains("HTTP document transport"));
21267    }
21268
21269    #[test]
21270    fn untagged_json_payload_value_fails_closed() {
21271        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
21272            .expect_err("untagged JSON payload values must fail");
21273        let diagnostic = error.to_string();
21274        assert!(diagnostic.contains("unsupported_payload_codec"));
21275        assert!(diagnostic.contains("untagged durable payload"));
21276        assert!(diagnostic.contains("HTTP document transport"));
21277    }
21278
21279    #[test]
21280    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
21281        let envelope = PayloadEnvelope {
21282            codec: DEFAULT_CODEC.to_string(),
21283            blob: BASE64.encode([0x01]),
21284        };
21285
21286        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
21287        assert!(error.to_string().contains("invalid_payload_framing"));
21288    }
21289
21290    #[tokio::test]
21291    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
21292        let server = MockWorkerServer::start();
21293        let client = Client::builder(server.base_url())
21294            .timeout(Duration::from_secs(2))
21295            .build()
21296            .expect("client");
21297        let invalid_commands = [
21298            json!({
21299                "type": "complete_workflow",
21300                "result": {"codec": "json", "blob": null}
21301            }),
21302            json!({
21303                "type": "schedule_activity",
21304                "arguments": {"codec": "yaml", "blob": "ignored"}
21305            }),
21306            json!({
21307                "type": "start_child_workflow",
21308                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
21309            }),
21310            json!({"type": "continue_as_new", "arguments": []}),
21311            json!({"type": "complete_update"}),
21312            json!({"type": "record_side_effect", "result": null}),
21313            json!({
21314                "type": "start_service_operation",
21315                "payload_codec": DEFAULT_CODEC,
21316                "request_payload": "raw-avro-bytes"
21317            }),
21318        ];
21319
21320        for command in invalid_commands {
21321            let error = client
21322                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
21323                .await
21324                .expect_err("invalid durable payload must fail locally");
21325            let diagnostic = error.to_string();
21326            assert!(
21327                diagnostic.contains("unsupported_payload_codec")
21328                    || diagnostic.contains("invalid_payload_envelope")
21329                    || diagnostic.contains("untagged durable payload"),
21330                "unexpected validation diagnostic: {diagnostic}"
21331            );
21332        }
21333
21334        assert_eq!(
21335            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
21336            0,
21337            "invalid command payloads must not reach HTTP transport"
21338        );
21339    }
21340
21341    #[test]
21342    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
21343        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
21344        let commands = [
21345            json!({"type": "complete_workflow", "result": envelope.clone()}),
21346            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
21347            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
21348            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
21349            json!({"type": "complete_update", "result": envelope.clone()}),
21350            json!({"type": "record_side_effect", "result": envelope.clone()}),
21351            json!({
21352                "type": "start_service_operation",
21353                "payload_codec": DEFAULT_CODEC,
21354                "request_payload": envelope.clone()
21355            }),
21356            json!({
21357                "type": "complete_workflow",
21358                "result": envelope,
21359                "metadata": {
21360                    "codec": "json",
21361                    "payload_codec": "customer-codec",
21362                    "result": {"codec": "yaml", "blob": null}
21363                }
21364            }),
21365        ];
21366
21367        validate_workflow_task_commands(&commands)
21368            .expect("customer metadata must not become a protocol codec declaration");
21369    }
21370
21371    #[test]
21372    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
21373        assert_eq!(
21374            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
21375            AvroValue::Array(Vec::new())
21376        );
21377        assert_eq!(
21378            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
21379            AvroValue::Array(Vec::new())
21380        );
21381
21382        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21383        signal.signal_name = Some("empty-signal".to_string());
21384        signal.signal_arguments = None;
21385        let decoded = decode_resume_signal(&signal)
21386            .expect("valid Avro signal")
21387            .expect("named signal resumes the workflow");
21388        assert!(decoded.arguments.is_empty());
21389    }
21390
21391    #[tokio::test]
21392    async fn malformed_task_level_codecs_become_pre_handler_failures() {
21393        let client = Client::new("http://127.0.0.1:8080").expect("client");
21394        let mut worker = Worker::new(client, "rust-workers");
21395        let handler_calls = Arc::new(AtomicUsize::new(0));
21396
21397        let calls = Arc::clone(&handler_calls);
21398        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21399            calls.fetch_add(1, Ordering::SeqCst);
21400            async move { Ok(Value::Null) }
21401        });
21402        let calls = Arc::clone(&handler_calls);
21403        worker.register_activity("codec.activity", move |_ctx, _args| {
21404            calls.fetch_add(1, Ordering::SeqCst);
21405            async move { Ok(Value::Null) }
21406        });
21407        let calls = Arc::clone(&handler_calls);
21408        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21409            calls.fetch_add(1, Ordering::SeqCst);
21410            async move { Ok(Value::Null) }
21411        });
21412
21413        let mut failures = Vec::new();
21414        for codec_case in [
21415            InvalidTaskPayloadCodec::Missing,
21416            InvalidTaskPayloadCodec::Null,
21417            InvalidTaskPayloadCodec::NonString,
21418        ] {
21419            let mut workflow = json!({
21420                "task_id": format!("workflow-{}", codec_case.label()),
21421                "workflow_type": "codec.workflow"
21422            });
21423            codec_case.apply(&mut workflow);
21424            match serde_json::from_value::<WorkflowTask>(workflow) {
21425                Ok(task) => match worker.execute_workflow_task(task) {
21426                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21427                    outcome => failures.push(format!(
21428                        "workflow {} codec returned {outcome:?}",
21429                        codec_case.label()
21430                    )),
21431                },
21432                Err(error) => failures.push(format!(
21433                    "workflow {} codec failed transport deserialization: {error}",
21434                    codec_case.label()
21435                )),
21436            }
21437
21438            let mut activity = json!({
21439                "task_id": format!("activity-{}", codec_case.label()),
21440                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
21441                "activity_type": "codec.activity",
21442                "attempt_number": 1
21443            });
21444            codec_case.apply(&mut activity);
21445            match serde_json::from_value::<ActivityTask>(activity) {
21446                Ok(task) => match worker.execute_activity_task(task).await {
21447                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21448                    outcome => failures.push(format!(
21449                        "activity {} codec returned {outcome:?}",
21450                        codec_case.label()
21451                    )),
21452                },
21453                Err(error) => failures.push(format!(
21454                    "activity {} codec failed transport deserialization: {error}",
21455                    codec_case.label()
21456                )),
21457            }
21458
21459            let mut query = json!({
21460                "query_task_id": format!("query-{}", codec_case.label()),
21461                "workflow_type": "codec.workflow",
21462                "query_name": "known"
21463            });
21464            codec_case.apply(&mut query);
21465            match serde_json::from_value::<QueryTask>(query) {
21466                Ok(task) => match worker.execute_query_task(task).await {
21467                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
21468                    outcome => failures.push(format!(
21469                        "query {} codec returned {outcome:?}",
21470                        codec_case.label()
21471                    )),
21472                },
21473                Err(error) => failures.push(format!(
21474                    "query {} codec failed transport deserialization: {error}",
21475                    codec_case.label()
21476                )),
21477            }
21478        }
21479
21480        assert!(failures.is_empty(), "{}", failures.join("\n"));
21481        assert_eq!(
21482            handler_calls.load(Ordering::SeqCst),
21483            0,
21484            "invalid task codecs must not invoke a handler"
21485        );
21486    }
21487
21488    #[tokio::test]
21489    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
21490        for codec_case in [
21491            InvalidTaskPayloadCodec::Missing,
21492            InvalidTaskPayloadCodec::Null,
21493            InvalidTaskPayloadCodec::NonString,
21494        ] {
21495            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
21496            let client = Client::builder(server.base_url())
21497                .timeout(Duration::from_secs(2))
21498                .build()
21499                .expect("client");
21500            let mut worker = Worker::new(client, "rust-workers")
21501                .worker_id("codec-worker")
21502                .poll_timeout(Duration::from_millis(10));
21503            let handler_calls = Arc::new(AtomicUsize::new(0));
21504
21505            let calls = Arc::clone(&handler_calls);
21506            worker.register_workflow("codec.workflow", move |_ctx, _args| {
21507                calls.fetch_add(1, Ordering::SeqCst);
21508                async move { Ok(Value::Null) }
21509            });
21510            let calls = Arc::clone(&handler_calls);
21511            worker.register_activity("codec.activity", move |_ctx, _args| {
21512                calls.fetch_add(1, Ordering::SeqCst);
21513                async move { Ok(Value::Null) }
21514            });
21515            let calls = Arc::clone(&handler_calls);
21516            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21517                calls.fetch_add(1, Ordering::SeqCst);
21518                async move { Ok(Value::Null) }
21519            });
21520
21521            assert_eq!(
21522                worker.run_once().await.expect("invalid tasks are settled"),
21523                3,
21524                "all {} codec tasks must be handled",
21525                codec_case.label()
21526            );
21527            assert_eq!(
21528                handler_calls.load(Ordering::SeqCst),
21529                0,
21530                "{} task codecs must fail before every handler",
21531                codec_case.label()
21532            );
21533
21534            for path in [
21535                "/api/worker/workflow-tasks/codec-workflow/fail",
21536                "/api/worker/activity-tasks/codec-activity/fail",
21537                "/api/worker/query-tasks/codec-query/fail",
21538            ] {
21539                let body = server.request_body(path);
21540                assert!(
21541                    body["failure"]["message"]
21542                        .as_str()
21543                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
21544                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
21545                    codec_case.label()
21546                );
21547            }
21548            assert_eq!(
21549                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
21550                    ["reason"],
21551                "query_payload_decode_failed"
21552            );
21553            for path in [
21554                "/api/worker/workflow-tasks/codec-workflow/complete",
21555                "/api/worker/activity-tasks/codec-activity/complete",
21556                "/api/worker/query-tasks/codec-query/complete",
21557            ] {
21558                assert_eq!(
21559                    server.request_count(path),
21560                    0,
21561                    "invalid {} codec task reached {path}",
21562                    codec_case.label()
21563                );
21564            }
21565        }
21566    }
21567
21568    #[tokio::test]
21569    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
21570        let client = Client::new("http://127.0.0.1:8080").expect("client");
21571        let mut worker = Worker::new(client, "rust-workers");
21572        let handler_calls = Arc::new(AtomicUsize::new(0));
21573
21574        let calls = Arc::clone(&handler_calls);
21575        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21576            calls.fetch_add(1, Ordering::SeqCst);
21577            async move { Ok(Value::Null) }
21578        });
21579        let calls = Arc::clone(&handler_calls);
21580        worker.register_activity("codec.activity", move |_ctx, _args| {
21581            calls.fetch_add(1, Ordering::SeqCst);
21582            async move { Ok(Value::Null) }
21583        });
21584        let calls = Arc::clone(&handler_calls);
21585        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
21586            calls.fetch_add(1, Ordering::SeqCst);
21587            async move { Ok(Value::Null) }
21588        });
21589        let calls = Arc::clone(&handler_calls);
21590        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21591            calls.fetch_add(1, Ordering::SeqCst);
21592            async move { Ok(Value::Null) }
21593        });
21594
21595        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21596        workflow.payload_codec = "json".to_string();
21597        workflow.arguments = None;
21598        let error = worker
21599            .execute_workflow_task(workflow)
21600            .expect_err("task codec must be checked before workflow invocation");
21601        assert!(error.to_string().contains("unsupported_payload_codec"));
21602
21603        let activity = ActivityTask {
21604            task_id: "activity-invalid-codec".to_string(),
21605            activity_attempt_id: None,
21606            attempt_id: None,
21607            activity_type: "codec.activity".to_string(),
21608            payload_codec: "unknown".to_string(),
21609            arguments: None,
21610            attempt_number: 1,
21611            lease_owner: None,
21612        };
21613        let error = worker
21614            .execute_activity_task(activity)
21615            .await
21616            .expect_err("task codec must be checked before activity invocation");
21617        assert!(error.to_string().contains("unsupported_payload_codec"));
21618
21619        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21620        update.workflow_update_id = Some("update-invalid-codec".to_string());
21621        update.update_name = Some("known".to_string());
21622        update.history_events.push(history_event(
21623            "UpdateAccepted",
21624            json!({
21625                "update_id": "update-invalid-codec",
21626                "update_name": "known",
21627                "arguments": {"codec": "json", "blob": null}
21628            }),
21629        ));
21630        let error = worker
21631            .execute_workflow_task(update)
21632            .expect_err("nested update codec must be checked before handler lookup");
21633        assert!(error.to_string().contains("unsupported_payload_codec"));
21634
21635        let query: QueryTask = serde_json::from_value(json!({
21636            "query_task_id": "query-invalid-codec",
21637            "workflow_type": "codec.workflow",
21638            "query_name": "known",
21639            "payload_codec": DEFAULT_CODEC,
21640            "workflow_arguments": null,
21641            "query_arguments": null,
21642            "history_export": {
21643                "payloads": {"codec": DEFAULT_CODEC},
21644                "signals": [{
21645                    "name": "empty",
21646                    "payload_codec": "json",
21647                    "arguments": null
21648                }]
21649            }
21650        }))
21651        .expect("query task");
21652        let failure = worker
21653            .execute_query_task(query)
21654            .await
21655            .expect_err("exported signal codec must be checked before query invocation");
21656        assert_eq!(failure.reason, "query_payload_decode_failed");
21657        assert!(failure.message.contains("unsupported_payload_codec"));
21658
21659        let exported_history: QueryTask = serde_json::from_value(json!({
21660            "query_task_id": "query-invalid-history-codec",
21661            "workflow_type": "codec.workflow",
21662            "query_name": "known",
21663            "payload_codec": DEFAULT_CODEC,
21664            "history_export": {
21665                "payloads": {"codec": DEFAULT_CODEC},
21666                "history_events": [{
21667                    "type": "ActivityCompleted",
21668                    "payload": {"payload_codec": "unknown", "result": null}
21669                }]
21670            }
21671        }))
21672        .expect("query task");
21673        let failure = worker
21674            .execute_query_task(exported_history)
21675            .await
21676            .expect_err("exported history codec must be checked before query invocation");
21677        assert_eq!(failure.reason, "query_payload_decode_failed");
21678        assert!(failure.message.contains("unsupported_payload_codec"));
21679        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
21680
21681        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21682        unknown_workflow.arguments = None;
21683        unknown_workflow.history_events.push(history_event(
21684            "SignalReceived",
21685            json!({
21686                "signal_name": "empty",
21687                "payload_codec": "json",
21688                "arguments": null
21689            }),
21690        ));
21691        let error = worker
21692            .execute_workflow_task(unknown_workflow)
21693            .expect_err("history codec must precede unknown workflow outcome");
21694        assert!(error.to_string().contains("unsupported_payload_codec"));
21695
21696        let unknown_activity = ActivityTask {
21697            task_id: "activity-unknown".to_string(),
21698            activity_attempt_id: None,
21699            attempt_id: None,
21700            activity_type: "missing".to_string(),
21701            payload_codec: "json".to_string(),
21702            arguments: None,
21703            attempt_number: 1,
21704            lease_owner: None,
21705        };
21706        let error = worker
21707            .execute_activity_task(unknown_activity)
21708            .await
21709            .expect_err("codec must precede unknown activity outcome");
21710        assert!(error.to_string().contains("unsupported_payload_codec"));
21711
21712        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21713        unknown_update.payload_codec = "json".to_string();
21714        unknown_update.arguments = None;
21715        unknown_update.workflow_update_id = Some("update-unknown".to_string());
21716        unknown_update.update_name = Some("missing".to_string());
21717        let error = worker
21718            .execute_workflow_task(unknown_update)
21719            .expect_err("codec must precede fail_update shortcut");
21720        assert!(error.to_string().contains("unsupported_payload_codec"));
21721
21722        let unknown_query: QueryTask = serde_json::from_value(json!({
21723            "query_task_id": "query-unknown",
21724            "workflow_type": "missing",
21725            "query_name": "missing",
21726            "payload_codec": "json",
21727            "workflow_arguments": null,
21728            "query_arguments": null
21729        }))
21730        .expect("query task");
21731        let failure = worker
21732            .execute_query_task(unknown_query)
21733            .await
21734            .expect_err("codec must precede unknown query outcome");
21735        assert_eq!(failure.reason, "query_payload_decode_failed");
21736        assert!(failure.message.contains("unsupported_payload_codec"));
21737    }
21738
21739    #[tokio::test]
21740    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
21741        let client = Client::new("http://127.0.0.1:8080").expect("client");
21742        let worker = Worker::new(client, "rust-workers");
21743
21744        for event_type in ["SignalReceived", "SignalApplied"] {
21745            for (payload_field, codec) in [
21746                ("value", "json"),
21747                ("input", "unknown"),
21748                ("arguments", "json"),
21749            ] {
21750                let payload = json!({
21751                    "signal_name": "empty",
21752                    payload_field: {"codec": codec, "blob": null}
21753                });
21754                let workflow = workflow_task(
21755                    "missing",
21756                    vec![history_event(event_type, payload.clone())],
21757                    DEFAULT_CODEC,
21758                );
21759                let error = worker
21760                    .execute_workflow_task(workflow)
21761                    .expect_err("signal payload codec must precede unknown workflow outcome");
21762                assert!(
21763                    error.to_string().contains("unsupported_payload_codec"),
21764                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
21765                );
21766
21767                let query: QueryTask = serde_json::from_value(json!({
21768                    "query_task_id": format!("query-{event_type}-{payload_field}"),
21769                    "workflow_type": "missing",
21770                    "query_name": "missing",
21771                    "payload_codec": DEFAULT_CODEC,
21772                    "workflow_arguments": null,
21773                    "query_arguments": null,
21774                    "history_events": [{
21775                        "event_type": event_type,
21776                        "payload": payload
21777                    }]
21778                }))
21779                .expect("query task");
21780                let failure = worker
21781                    .execute_query_task(query)
21782                    .await
21783                    .expect_err("signal payload codec must precede unknown query outcome");
21784                assert_eq!(
21785                    failure.reason, "query_payload_decode_failed",
21786                    "{event_type}.{payload_field} returned an unrelated query outcome"
21787                );
21788                assert!(
21789                    failure.message.contains("unsupported_payload_codec"),
21790                    "{event_type}.{payload_field} returned an unrelated query error: {}",
21791                    failure.message
21792                );
21793            }
21794        }
21795    }
21796
21797    #[test]
21798    fn workflow_context_schedules_activity_until_completion_is_in_history() {
21799        let ctx = WorkflowContext {
21800            cancellation_scope_id: "root".into(),
21801            state: Arc::new(Mutex::new(
21802                WorkflowState::new_with_identity(
21803                    Vec::new(),
21804                    Some("wf-parent".to_string()),
21805                    Some("run-parent".to_string()),
21806                    "rust-workers".to_string(),
21807                    DEFAULT_CODEC.to_string(),
21808                    None,
21809                )
21810                .expect("workflow state"),
21811            )),
21812        };
21813
21814        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
21815        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21816        assert!(matches!(
21817            call.as_mut().poll(&mut task_context),
21818            Poll::Pending
21819        ));
21820
21821        let commands = ctx.take_commands().expect("commands");
21822        assert_eq!(commands[0]["type"], "schedule_activity");
21823        assert_eq!(commands[0]["activity_type"], "hello.activity");
21824    }
21825
21826    #[test]
21827    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
21828        let ctx = workflow_context(Vec::new());
21829        let options = ActivityOptions::new()
21830            .task_queue("payments")
21831            .retry_policy(
21832                ActivityRetryPolicy::new(4)
21833                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
21834                    .non_retryable_error_type("ValidationError"),
21835            )
21836            .start_to_close_timeout(Duration::from_secs(120))
21837            .schedule_to_start_timeout(Duration::from_secs(10))
21838            .schedule_to_close_timeout(Duration::from_secs(300))
21839            .heartbeat_timeout(Duration::from_secs(15));
21840        let mut call = Box::pin(ctx.activity_with_options(
21841            "charge-card",
21842            options,
21843            json!([{"order_id": "o-1"}]),
21844        ));
21845        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21846
21847        assert!(matches!(
21848            call.as_mut().poll(&mut task_context),
21849            Poll::Pending
21850        ));
21851        assert!(matches!(
21852            call.as_mut().poll(&mut task_context),
21853            Poll::Pending
21854        ));
21855
21856        let commands = ctx.take_commands().expect("activity command");
21857        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
21858        assert_eq!(commands[0]["queue"], "payments");
21859        assert_eq!(
21860            commands[0]["retry_policy"],
21861            json!({
21862                "max_attempts": 4,
21863                "backoff_seconds": [1, 3, 9],
21864                "non_retryable_error_types": ["ValidationError"],
21865            })
21866        );
21867        assert_eq!(commands[0]["start_to_close_timeout"], 120);
21868        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
21869        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
21870        assert_eq!(commands[0]["heartbeat_timeout"], 15);
21871    }
21872
21873    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
21874        vec![
21875            history_event(
21876                "ActivityScheduled",
21877                json!({"sequence":1,"activity_type":"render",
21878                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
21879            ),
21880            history_event(
21881                "ActivityCompleted",
21882                json!({"sequence":1,"activity_type":"render",
21883                "payload_codec":DEFAULT_CODEC,
21884                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
21885            ),
21886        ]
21887    }
21888
21889    #[test]
21890    fn worker_session_activity_routes_to_session_queue_once() {
21891        let ctx = workflow_context(Vec::new());
21892        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21893        let mut call = Box::pin(
21894            ctx.activity("render", json!([]))
21895                .in_worker_session(session.clone()),
21896        );
21897        let mut cx = TaskContext::from_waker(noop_waker_ref());
21898        assert!(call.as_mut().poll(&mut cx).is_pending());
21899        assert!(call.as_mut().poll(&mut cx).is_pending());
21900        let commands = ctx.take_commands().unwrap();
21901        assert_eq!(commands.len(), 1);
21902        assert_eq!(commands[0]["queue"], "gpu-workers");
21903        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
21904    }
21905
21906    #[tokio::test]
21907    async fn worker_session_cold_replay_uses_recorded_avro_result() {
21908        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21909        for _replacement in 0..2 {
21910            let ctx = workflow_context(completed_worker_session_history(&session));
21911            let result: i64 = ctx
21912                .activity("render", json!([]))
21913                .in_worker_session(session.clone())
21914                .typed()
21915                .await
21916                .unwrap();
21917            assert_eq!(result, 42);
21918            assert!(ctx.take_commands().unwrap().is_empty());
21919        }
21920    }
21921
21922    #[test]
21923    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
21924        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21925        for changed in [
21926            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
21927            Some(original.clone().ttl_seconds(60)),
21928            Some(original.clone().requirements(["gpu:l4"])),
21929            None,
21930        ] {
21931            let ctx = workflow_context(completed_worker_session_history(&original));
21932            let mut call = ctx.activity_with_options(
21933                "render",
21934                ActivityOptions::new().task_queue("gpu-workers"),
21935                json!([]),
21936            );
21937            if let Some(changed) = changed {
21938                call = call.in_worker_session(changed);
21939            }
21940            let mut call = Box::pin(call);
21941            let mut cx = TaskContext::from_waker(noop_waker_ref());
21942            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21943                call.as_mut().poll(&mut cx)
21944            else {
21945                panic!("changed session must fail replay");
21946            };
21947            assert_eq!(failure.reason, "activity_worker_session_mismatch");
21948            assert!(ctx.take_commands().unwrap().is_empty());
21949        }
21950    }
21951
21952    #[test]
21953    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
21954        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21955        let ctx = workflow_context(Vec::new());
21956        let mut local = Box::pin(
21957            ctx.local_activity("render", json!([]))
21958                .in_worker_session(session.clone()),
21959        );
21960        let mut cx = TaskContext::from_waker(noop_waker_ref());
21961        assert!(matches!(
21962            local.as_mut().poll(&mut cx),
21963            Poll::Ready(Err(Error::WorkerLoop(_)))
21964        ));
21965        assert!(ctx.take_commands().unwrap().is_empty());
21966        let mut remote = Box::pin(
21967            ctx.activity_with_options(
21968                "render",
21969                ActivityOptions::new().task_queue("other"),
21970                json!([]),
21971            )
21972            .in_worker_session(session),
21973        );
21974        assert!(matches!(
21975            remote.as_mut().poll(&mut cx),
21976            Poll::Ready(Err(Error::WorkerLoop(_)))
21977        ));
21978        assert!(ctx.take_commands().unwrap().is_empty());
21979    }
21980
21981    #[test]
21982    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
21983        let ctx = workflow_context(Vec::new());
21984        let options = ActivityOptions::new().retry_policy(
21985            ActivityRetryPolicy::new(3)
21986                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
21987        );
21988        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21989        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21990
21991        assert!(matches!(
21992            call.as_mut().poll(&mut task_context),
21993            Poll::Pending
21994        ));
21995        assert_eq!(
21996            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
21997            json!([1, 2])
21998        );
21999    }
22000
22001    #[test]
22002    fn activity_options_preserve_unused_explicit_backoff_entries() {
22003        for max_attempts in [1, 2, 10] {
22004            let ctx = workflow_context(Vec::new());
22005            let options =
22006                ActivityOptions::new()
22007                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
22008                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
22009                    ));
22010            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22011            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22012            assert!(matches!(
22013                call.as_mut().poll(&mut task_context),
22014                Poll::Pending
22015            ));
22016            let commands = ctx.take_commands().expect("command");
22017            assert_eq!(commands.len(), 1);
22018            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
22019            assert_eq!(
22020                commands[0]["retry_policy"]["backoff_seconds"],
22021                json!([1, 2, 5, 10, 15, 30, 60, 120])
22022            );
22023        }
22024        let default_options = ActivityOptions::new().validate().expect("default options");
22025        let default_policy = current_activity_retry_snapshot(&default_options);
22026        assert_eq!(
22027            default_policy.max_attempts,
22028            RecordedSnapshotValue::Known(Some(1))
22029        );
22030        assert_eq!(
22031            default_policy.backoff_seconds,
22032            RecordedSnapshotValue::Known(Vec::new())
22033        );
22034    }
22035
22036    #[test]
22037    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
22038        let fixture: Value = serde_json::from_str(include_str!(
22039            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
22040        ))
22041        .expect("published PHP fixture");
22042        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
22043            .expect("unchanged published history");
22044        let matching = ActivityOptions::new().task_queue("default").retry_policy(
22045            ActivityRetryPolicy::new(1)
22046                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
22047        );
22048        let mut changed_tail = matching.clone();
22049        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
22050            [1, 2, 5, 10, 15, 30, 60, 121]
22051                .map(Duration::from_secs)
22052                .to_vec(),
22053        ));
22054        let mut changed_first = matching.clone();
22055        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
22056            [2, 2, 5, 10, 15, 30, 60, 120]
22057                .map(Duration::from_secs)
22058                .to_vec(),
22059        ));
22060        let mut changed_attempts = matching.clone();
22061        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
22062        let mut changed_types = matching.clone();
22063        changed_types
22064            .retry_policy
22065            .as_mut()
22066            .unwrap()
22067            .non_retryable_error_types = vec!["ChangedError".into()];
22068        let mut changed_start = matching.clone();
22069        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
22070        let mut changed_schedule_start = matching.clone();
22071        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
22072        let mut changed_schedule_close = matching.clone();
22073        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
22074        let mut changed_heartbeat = matching;
22075        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
22076        let unchanged_defaults = ActivityOptions::new().task_queue("default");
22077        for options in [
22078            changed_tail,
22079            changed_first,
22080            changed_attempts,
22081            changed_types,
22082            changed_start,
22083            changed_schedule_start,
22084            changed_schedule_close,
22085            changed_heartbeat,
22086            unchanged_defaults,
22087        ] {
22088            let ctx = workflow_context(history.clone());
22089            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
22090            assert!(!ctx.patched("frozen-zero").unwrap());
22091            ctx.deprecate_patch("frozen-zero").unwrap();
22092            let mut call =
22093                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
22094            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22095            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22096                call.as_mut().poll(&mut task_context)
22097            else {
22098                panic!("changed explicit policy must fail replay")
22099            };
22100            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
22101            assert_eq!(failure.sequence, Some(2));
22102            assert!(ctx.take_commands().unwrap().is_empty());
22103        }
22104    }
22105
22106    #[test]
22107    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
22108        let cases = [
22109            (
22110                ActivityOptions::new().task_queue("  "),
22111                ActivityOptionsErrorKind::EmptyTaskQueue,
22112            ),
22113            (
22114                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
22115                ActivityOptionsErrorKind::EmptyRetryPolicy,
22116            ),
22117            (
22118                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
22119                ActivityOptionsErrorKind::InvalidMaxAttempts,
22120            ),
22121            (
22122                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
22123                    max_attempts: None,
22124                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
22125                    non_retryable_error_types: Vec::new(),
22126                }),
22127                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
22128            ),
22129            (
22130                ActivityOptions::new().retry_policy(
22131                    ActivityRetryPolicy::new(2).exponential_backoff(
22132                        Duration::from_secs(1),
22133                        0,
22134                        None,
22135                    ),
22136                ),
22137                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
22138            ),
22139            (
22140                ActivityOptions::new()
22141                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
22142                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
22143            ),
22144            (
22145                ActivityOptions::new().retry_policy(
22146                    ActivityRetryPolicy::new(10_002).exponential_backoff(
22147                        Duration::from_secs(1),
22148                        1,
22149                        None,
22150                    ),
22151                ),
22152                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
22153            ),
22154            (
22155                ActivityOptions::new().retry_policy(
22156                    ActivityRetryPolicy::new(2)
22157                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
22158                ),
22159                ActivityOptionsErrorKind::BackoffOverflow,
22160            ),
22161        ];
22162
22163        for (options, expected_kind) in cases {
22164            let ctx = workflow_context(Vec::new());
22165            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22166            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22167            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
22168                call.as_mut().poll(&mut task_context)
22169            else {
22170                panic!("expected typed activity validation error");
22171            };
22172            assert_eq!(error.kind, expected_kind);
22173            assert!(ctx.take_commands().expect("commands").is_empty());
22174        }
22175    }
22176
22177    #[test]
22178    fn activity_options_validate_positive_and_ordered_timeouts() {
22179        let zero_timeout_cases = [
22180            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
22181            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
22182            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
22183            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
22184        ];
22185        for options in zero_timeout_cases {
22186            assert_eq!(
22187                options.validate().expect_err("zero timeout").kind,
22188                ActivityOptionsErrorKind::TimeoutNotPositive
22189            );
22190        }
22191
22192        let ordering_cases = [
22193            ActivityOptions::new()
22194                .heartbeat_timeout(Duration::from_secs(11))
22195                .start_to_close_timeout(Duration::from_secs(10)),
22196            ActivityOptions::new()
22197                .start_to_close_timeout(Duration::from_secs(31))
22198                .schedule_to_close_timeout(Duration::from_secs(30)),
22199            ActivityOptions::new()
22200                .schedule_to_start_timeout(Duration::from_secs(31))
22201                .schedule_to_close_timeout(Duration::from_secs(30)),
22202        ];
22203        for options in ordering_cases {
22204            assert_eq!(
22205                options.validate().expect_err("timeout order").kind,
22206                ActivityOptionsErrorKind::TimeoutOrder
22207            );
22208        }
22209
22210        assert_eq!(
22211            ActivityOptions::new()
22212                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
22213                .validate()
22214                .expect_err("protocol integer overflow")
22215                .kind,
22216            ActivityOptionsErrorKind::TimeoutOverflow
22217        );
22218    }
22219
22220    #[test]
22221    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
22222        let ctx = workflow_context(completed_retry_activity_history());
22223        let mut call =
22224            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22225        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22226
22227        assert!(matches!(
22228            call.as_mut().poll(&mut task_context),
22229            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22230        ));
22231        assert!(ctx.take_commands().expect("commands").is_empty());
22232        ctx.ensure_history_consumed().expect("history consumed");
22233    }
22234
22235    #[test]
22236    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
22237        let mut options = retry_activity_options();
22238        options
22239            .retry_policy
22240            .as_mut()
22241            .expect("retry policy")
22242            .non_retryable_error_types
22243            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
22244
22245        let new_ctx = workflow_context(Vec::new());
22246        let mut new_call =
22247            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
22248        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22249        assert!(matches!(
22250            new_call.as_mut().poll(&mut task_context),
22251            Poll::Pending
22252        ));
22253        let commands = new_ctx.take_commands().expect("commands");
22254        assert_eq!(commands.len(), 1);
22255        assert_eq!(
22256            commands[0]["retry_policy"]["non_retryable_error_types"],
22257            json!(["PermanentError"])
22258        );
22259
22260        let replay_ctx = workflow_context(completed_retry_activity_history());
22261        let mut replay_call =
22262            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
22263        assert!(matches!(
22264            replay_call.as_mut().poll(&mut task_context),
22265            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22266        ));
22267        assert!(replay_ctx.take_commands().expect("commands").is_empty());
22268        replay_ctx
22269            .ensure_history_consumed()
22270            .expect("history consumed");
22271    }
22272
22273    #[test]
22274    fn replayed_intermediate_retry_remains_pending_across_restarts() {
22275        let history = completed_retry_activity_history()
22276            .into_iter()
22277            .take(3)
22278            .collect::<Vec<_>>();
22279
22280        for _restart in 0..2 {
22281            let ctx = workflow_context(history.clone());
22282            let mut call =
22283                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22284            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22285            assert!(matches!(
22286                call.as_mut().poll(&mut task_context),
22287                Poll::Pending
22288            ));
22289            assert!(ctx.take_commands().expect("commands").is_empty());
22290        }
22291    }
22292
22293    #[test]
22294    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
22295        let mut changed_queue = retry_activity_options();
22296        changed_queue.task_queue = Some("different-queue".to_string());
22297
22298        let mut changed_max_attempts = retry_activity_options();
22299        let retry_policy = changed_max_attempts
22300            .retry_policy
22301            .as_mut()
22302            .expect("retry policy");
22303        retry_policy.max_attempts = Some(4);
22304
22305        let mut changed_backoff = retry_activity_options();
22306        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
22307        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
22308            Duration::from_secs(3),
22309            Duration::from_secs(4),
22310        ]));
22311
22312        let mut changed_non_retryable_types = retry_activity_options();
22313        let retry_policy = changed_non_retryable_types
22314            .retry_policy
22315            .as_mut()
22316            .expect("retry policy");
22317        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
22318
22319        let mut changed_start_to_close = retry_activity_options();
22320        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
22321        let mut changed_schedule_to_start = retry_activity_options();
22322        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
22323        let mut changed_schedule_to_close = retry_activity_options();
22324        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
22325        let mut changed_heartbeat = retry_activity_options();
22326        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
22327
22328        let cases = [
22329            (changed_queue, "activity_task_queue_mismatch"),
22330            (changed_max_attempts, "activity_retry_policy_mismatch"),
22331            (changed_backoff, "activity_retry_policy_mismatch"),
22332            (
22333                changed_non_retryable_types,
22334                "activity_retry_policy_mismatch",
22335            ),
22336            (changed_start_to_close, "activity_retry_policy_mismatch"),
22337            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
22338            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
22339            (changed_heartbeat, "activity_retry_policy_mismatch"),
22340        ];
22341
22342        for (options, expected_reason) in cases {
22343            let ctx = workflow_context(completed_retry_activity_history());
22344            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
22345            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22346            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22347                call.as_mut().poll(&mut task_context)
22348            else {
22349                panic!("changed activity options must fail replay");
22350            };
22351            assert_eq!(failure.reason, expected_reason);
22352            assert_eq!(failure.sequence, Some(1));
22353            assert!(ctx.take_commands().expect("commands").is_empty());
22354        }
22355    }
22356
22357    #[test]
22358    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
22359        let cases = [
22360            (
22361                "execution_mode",
22362                json!("local"),
22363                "activity_execution_mode_mismatch",
22364            ),
22365            (
22366                "snapshot_version",
22367                json!(2),
22368                "activity_retry_policy_mismatch",
22369            ),
22370        ];
22371
22372        for (field, value, expected_reason) in cases {
22373            let mut history = completed_retry_activity_history();
22374            let activity = history[0].payload["activity"]
22375                .as_object_mut()
22376                .expect("activity snapshot");
22377            if field == "execution_mode" {
22378                activity.insert(field.to_string(), value);
22379            } else {
22380                activity["retry_policy"]
22381                    .as_object_mut()
22382                    .expect("retry snapshot")
22383                    .insert(field.to_string(), value);
22384            }
22385
22386            let ctx = workflow_context(history);
22387            let mut call =
22388                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22389            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22390            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22391                call.as_mut().poll(&mut task_context)
22392            else {
22393                panic!("changed {field} must fail replay");
22394            };
22395            assert_eq!(failure.reason, expected_reason);
22396            assert_eq!(failure.sequence, Some(1));
22397            assert!(ctx.take_commands().expect("commands").is_empty());
22398        }
22399    }
22400
22401    #[test]
22402    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
22403        for (nested, field, value, terminal_only) in [
22404            (false, "execution_mode", json!("local"), false),
22405            (false, "local_activity", json!(true), false),
22406            (true, "local_activity", json!(true), false),
22407            (false, "local_activity", json!(true), true),
22408        ] {
22409            let mut history = completed_retry_activity_history();
22410            history[0]
22411                .payload
22412                .as_object_mut()
22413                .unwrap()
22414                .remove("activity");
22415            let event = if terminal_only {
22416                history.last_mut().unwrap()
22417            } else {
22418                &mut history[0]
22419            };
22420            if nested {
22421                event.payload["activity"] = json!({(field): value});
22422            } else {
22423                event.payload[field] = value;
22424            }
22425            let ctx = workflow_context(history);
22426            let mut call =
22427                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22428            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22429            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22430                call.as_mut().poll(&mut task_context)
22431            else {
22432                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
22433            };
22434            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
22435            assert_eq!(failure.sequence, Some(1));
22436            assert!(ctx.take_commands().expect("commands").is_empty());
22437        }
22438    }
22439
22440    #[test]
22441    fn activity_history_rejects_conflicting_local_execution_markers() {
22442        let mut history = completed_retry_activity_history();
22443        history.last_mut().unwrap().payload["local_activity"] = json!(true);
22444        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
22445            .expect_err("remote schedule cannot become a local completion");
22446        assert!(
22447            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
22448            if reason == "activity_execution_mode_conflict")
22449        );
22450    }
22451
22452    #[test]
22453    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
22454        let mut history = completed_retry_activity_history();
22455        let activity = history[0].payload["activity"]
22456            .as_object_mut()
22457            .expect("activity snapshot");
22458        activity.remove("execution_mode");
22459        activity.remove("retry_policy");
22460
22461        let mut current = retry_activity_options();
22462        current.start_to_close_timeout = Some(Duration::from_secs(45));
22463        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
22464        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
22465        current.heartbeat_timeout = Some(Duration::from_secs(12));
22466
22467        let ctx = workflow_context(history);
22468        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
22469        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22470        assert!(matches!(
22471            call.as_mut().poll(&mut task_context),
22472            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22473        ));
22474        assert!(ctx.take_commands().expect("commands").is_empty());
22475        ctx.ensure_history_consumed().expect("history consumed");
22476    }
22477
22478    #[test]
22479    fn terminal_activity_failed_after_start_returns_typed_failure() {
22480        let history = vec![
22481            history_event(
22482                "ActivityScheduled",
22483                json!({
22484                    "sequence": 1,
22485                    "activity_type": "flaky",
22486                    "activity_execution_id": "act-terminal",
22487                    "activity": {
22488                        "id": "act-terminal",
22489                        "sequence": 1,
22490                        "type": "flaky",
22491                        "queue": "critical-activities",
22492                        "retry_policy": {
22493                            "snapshot_version": 1,
22494                            "max_attempts": 3,
22495                            "backoff_seconds": [2, 4],
22496                            "non_retryable_error_types": ["PermanentError"]
22497                        }
22498                    }
22499                }),
22500            ),
22501            history_event(
22502                "ActivityStarted",
22503                json!({
22504                    "sequence": 1,
22505                    "activity_type": "flaky",
22506                    "activity_execution_id": "act-terminal",
22507                    "activity_attempt_id": "attempt-1",
22508                    "attempt_number": 1
22509                }),
22510            ),
22511            history_event(
22512                "ActivityFailed",
22513                json!({
22514                    "sequence": 1,
22515                    "activity_type": "flaky",
22516                    "activity_execution_id": "act-terminal",
22517                    "activity_attempt_id": "attempt-1",
22518                    "attempt_number": 1,
22519                    "failure_id": "failure-terminal",
22520                    "failure_category": "activity",
22521                    "exception_type": "PermanentError",
22522                    "message": "cannot retry",
22523                    "non_retryable": true
22524                }),
22525            ),
22526        ];
22527        let ctx = workflow_context(history);
22528        let mut call =
22529            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22530        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22531
22532        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22533            call.as_mut().poll(&mut task_context)
22534        else {
22535            panic!("terminal ActivityFailed must settle the activity future");
22536        };
22537        assert_eq!(failure.kind, ActivityFailureKind::Failed);
22538        assert_eq!(
22539            failure.activity_execution_id.as_deref(),
22540            Some("act-terminal")
22541        );
22542        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
22543        assert!(failure.non_retryable);
22544        assert!(ctx.take_commands().expect("commands").is_empty());
22545        ctx.ensure_history_consumed().expect("history consumed");
22546    }
22547
22548    #[test]
22549    fn activity_terminal_events_return_machine_readable_failures() {
22550        let cases = [
22551            (
22552                "ActivityFailed",
22553                json!({
22554                    "sequence": 1,
22555                    "activity_type": "charge-card",
22556                    "activity_execution_id": "act-1",
22557                    "activity_attempt_id": "attempt-2",
22558                    "attempt_number": 2,
22559                    "failure_id": "failure-1",
22560                    "failure_category": "activity",
22561                    "exception_type": "PaymentDeclined",
22562                    "exception_class": "payments.PaymentDeclined",
22563                    "message": "card declined",
22564                    "non_retryable": true
22565                }),
22566                ActivityFailureKind::Failed,
22567                "activity",
22568            ),
22569            (
22570                "ActivityCancelled",
22571                json!({
22572                    "sequence": 1,
22573                    "activity_type": "charge-card",
22574                    "activity_execution_id": "act-1",
22575                    "activity_attempt_id": "attempt-1"
22576                }),
22577                ActivityFailureKind::Cancelled,
22578                "cancelled",
22579            ),
22580        ];
22581
22582        for (event_type, payload, expected_kind, expected_reason) in cases {
22583            let ctx = workflow_context(vec![history_event(event_type, payload)]);
22584            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
22585            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22586            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22587                call.as_mut().poll(&mut task_context)
22588            else {
22589                panic!("expected terminal activity failure");
22590            };
22591            assert_eq!(failure.kind, expected_kind);
22592            assert_eq!(failure.reason, expected_reason);
22593            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
22594            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
22595        }
22596    }
22597
22598    #[test]
22599    fn every_activity_timeout_class_is_typed() {
22600        for timeout_kind in [
22601            "start_to_close",
22602            "schedule_to_start",
22603            "schedule_to_close",
22604            "heartbeat",
22605        ] {
22606            let ctx = workflow_context(vec![history_event(
22607                "ActivityTimedOut",
22608                json!({
22609                    "sequence": 1,
22610                    "activity_type": "slow",
22611                    "activity_execution_id": "act-timeout",
22612                    "activity_attempt_id": "attempt-timeout",
22613                    "failure_category": "timeout",
22614                    "timeout_kind": timeout_kind,
22615                    "message": "deadline expired"
22616                }),
22617            )]);
22618            let mut call = Box::pin(ctx.activity("slow", json!([])));
22619            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22620            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22621                call.as_mut().poll(&mut task_context)
22622            else {
22623                panic!("expected timeout failure");
22624            };
22625            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
22626            assert_eq!(failure.reason, timeout_kind);
22627            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
22628            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
22629        }
22630    }
22631
22632    #[test]
22633    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
22634        let ctx = workflow_context(Vec::new());
22635        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
22636        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22637
22638        assert!(matches!(
22639            sleep.as_mut().poll(&mut task_context),
22640            Poll::Pending
22641        ));
22642        assert!(matches!(
22643            sleep.as_mut().poll(&mut task_context),
22644            Poll::Pending
22645        ));
22646
22647        let commands = ctx.take_commands().expect("timer command");
22648        assert_eq!(
22649            commands,
22650            vec![json!({
22651                "type": "start_timer",
22652                "delay_seconds": 2,
22653            })]
22654        );
22655    }
22656
22657    #[test]
22658    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
22659        let history = vec![
22660            history_event(
22661                "TimerScheduled",
22662                json!({
22663                    "sequence": 1,
22664                    "timer_id": "timer-1",
22665                    "delay_seconds": 5,
22666                    "fire_at": "2026-07-11T12:00:05Z",
22667                }),
22668            ),
22669            history_event(
22670                "TimerFired",
22671                json!({
22672                    "sequence": 1,
22673                    "timer_id": "timer-1",
22674                    "delay_seconds": 5,
22675                    "fire_at": "2026-07-11T12:00:05Z",
22676                    "fired_at": "2026-07-11T12:00:05Z",
22677                }),
22678            ),
22679        ];
22680
22681        for _restart in 0..2 {
22682            let ctx = workflow_context(history.clone());
22683            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
22684            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22685            assert!(matches!(
22686                sleep.as_mut().poll(&mut task_context),
22687                Poll::Ready(Ok(()))
22688            ));
22689            assert!(ctx.take_commands().expect("commands").is_empty());
22690            ctx.ensure_history_consumed().expect("history consumed");
22691        }
22692    }
22693
22694    #[test]
22695    fn workflow_sleep_rejects_changed_delay_during_replay() {
22696        let ctx = workflow_context(vec![
22697            history_event(
22698                "TimerScheduled",
22699                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22700            ),
22701            history_event(
22702                "TimerFired",
22703                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22704            ),
22705        ]);
22706        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
22707        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22708
22709        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22710            sleep.as_mut().poll(&mut task_context)
22711        else {
22712            panic!("changed timer delay must be rejected");
22713        };
22714        assert_eq!(failure.reason, "timer_delay_mismatch");
22715        assert_eq!(failure.sequence, Some(1));
22716    }
22717
22718    #[test]
22719    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
22720        let ctx = workflow_context(Vec::new());
22721        let mut wait = Box::pin(
22722            ctx.wait_condition(
22723                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
22724                    .timeout(Duration::from_millis(60_001)),
22725                || Ok(false),
22726            ),
22727        );
22728        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22729
22730        assert!(matches!(
22731            wait.as_mut().poll(&mut task_context),
22732            Poll::Pending
22733        ));
22734        assert!(matches!(
22735            wait.as_mut().poll(&mut task_context),
22736            Poll::Pending
22737        ));
22738        assert_eq!(
22739            ctx.take_commands().expect("condition command"),
22740            vec![json!({
22741                "type": "open_condition_wait",
22742                "condition_wait_occurrence_id": "rust:condition-wait:0",
22743                "condition_key": "approval.ready",
22744                "condition_definition_fingerprint": "sha256:approval-v1",
22745                "timeout_seconds": 61,
22746            })]
22747        );
22748    }
22749
22750    #[test]
22751    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
22752        let ctx = workflow_context(Vec::new());
22753        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
22754        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22755        assert!(matches!(
22756            satisfied.as_mut().poll(&mut task_context),
22757            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22758        ));
22759
22760        let mut timed_out = Box::pin(wait_condition!(
22761            ctx,
22762            "no-wait",
22763            timeout: Duration::ZERO,
22764            || Ok(false),
22765        ));
22766        assert!(matches!(
22767            timed_out.as_mut().poll(&mut task_context),
22768            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22769        ));
22770        assert!(ctx.take_commands().expect("commands").is_empty());
22771    }
22772
22773    #[test]
22774    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
22775        let signal_history = vec![
22776            history_event(
22777                "ConditionWaitOpened",
22778                json!({
22779                    "sequence": 4,
22780                    "condition_wait_id": "condition:4",
22781                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22782                    "condition_key": "approval",
22783                    "condition_definition_fingerprint": "sha256:approval-v1",
22784                    "timeout_seconds": 30,
22785                }),
22786            ),
22787            history_event(
22788                "SignalReceived",
22789                json!({
22790                    "workflow_sequence": 4,
22791                    "signal_name": "approve",
22792                    "arguments": fixture_envelope(json!(["Ada"])),
22793                }),
22794            ),
22795        ];
22796        for _worker_before_or_after_restart in 0..2 {
22797            let ctx = workflow_context(signal_history.clone());
22798            let predicate_ctx = ctx.clone();
22799            let mut wait = Box::pin(
22800                ctx.wait_condition(
22801                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
22802                        .timeout(Duration::from_secs(30)),
22803                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
22804                ),
22805            );
22806            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22807            assert!(matches!(
22808                wait.as_mut().poll(&mut task_context),
22809                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22810            ));
22811            assert!(ctx.take_commands().expect("commands").is_empty());
22812            ctx.ensure_history_consumed().expect("condition consumed");
22813        }
22814
22815        let update_history = vec![
22816            history_event(
22817                "ConditionWaitOpened",
22818                json!({
22819                    "sequence": 7,
22820                    "condition_wait_id": "condition:7",
22821                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22822                    "condition_key": "update-approval",
22823                    "condition_definition_fingerprint": "sha256:update-approval-v1",
22824                }),
22825            ),
22826            history_event(
22827                "UpdateApplied",
22828                json!({
22829                    "sequence": 7,
22830                    "update_id": "update-1",
22831                    "update_name": "approve",
22832                    "arguments": fixture_envelope(json!([true])),
22833                }),
22834            ),
22835        ];
22836        let ctx = workflow_context(update_history);
22837        let predicate_ctx = ctx.clone();
22838        let mut wait = Box::pin(ctx.wait_condition(
22839            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
22840            move || {
22841                Ok(predicate_ctx
22842                    .updates("approve")?
22843                    .first()
22844                    .and_then(|arguments| arguments.first())
22845                    .and_then(Value::as_bool)
22846                    == Some(true))
22847            },
22848        ));
22849        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22850        assert!(matches!(
22851            wait.as_mut().poll(&mut task_context),
22852            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22853        ));
22854        assert!(ctx.take_commands().expect("commands").is_empty());
22855        ctx.ensure_history_consumed().expect("condition consumed");
22856    }
22857
22858    #[test]
22859    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
22860        let open_history = vec![
22861            history_event(
22862                "ConditionWaitOpened",
22863                json!({
22864                    "sequence": 3,
22865                    "condition_wait_id": "condition:3",
22866                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22867                    "condition_key": "two-votes",
22868                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22869                    "timeout_seconds": 120,
22870                }),
22871            ),
22872            history_event(
22873                "SignalReceived",
22874                json!({
22875                    "workflow_sequence": 3,
22876                    "signal_name": "vote",
22877                    "arguments": fixture_envelope(json!(["first"])),
22878                }),
22879            ),
22880        ];
22881        for _worker_before_or_after_restart in 0..2 {
22882            let ctx = workflow_context(open_history.clone());
22883            let predicate_ctx = ctx.clone();
22884            let mut wait = Box::pin(
22885                ctx.wait_condition(
22886                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22887                        .timeout(Duration::from_secs(120)),
22888                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22889                ),
22890            );
22891            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22892            assert!(matches!(
22893                wait.as_mut().poll(&mut task_context),
22894                Poll::Pending
22895            ));
22896            assert_eq!(
22897                ctx.take_commands().expect("reopened condition"),
22898                vec![json!({
22899                    "type": "open_condition_wait",
22900                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22901                    "condition_key": "two-votes",
22902                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22903                    "timeout_seconds": 120,
22904                })]
22905            );
22906        }
22907
22908        let satisfied_ctx = workflow_context(vec![
22909            history_event(
22910                "ConditionWaitOpened",
22911                json!({
22912                    "sequence": 5,
22913                    "condition_wait_id": "condition:5",
22914                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22915                    "condition_key": "approval",
22916                    "condition_definition_fingerprint": "sha256:approval-v1",
22917                }),
22918            ),
22919            history_event(
22920                "ConditionWaitSatisfied",
22921                json!({
22922                    "sequence": 5,
22923                    "condition_wait_id": "condition:5",
22924                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22925                    "condition_key": "approval",
22926                    "condition_definition_fingerprint": "sha256:approval-v1",
22927                }),
22928            ),
22929        ]);
22930        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
22931            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
22932            || Ok(false),
22933        ));
22934        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22935        assert!(matches!(
22936            satisfied.as_mut().poll(&mut task_context),
22937            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22938        ));
22939
22940        let timed_out_ctx = workflow_context(vec![
22941            history_event(
22942                "ConditionWaitOpened",
22943                json!({
22944                    "sequence": 8,
22945                    "condition_wait_id": "condition:8",
22946                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22947                    "condition_key": "approval-timeout",
22948                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
22949                    "timeout_seconds": 5,
22950                }),
22951            ),
22952            history_event(
22953                "TimerScheduled",
22954                json!({
22955                    "sequence": 9,
22956                    "timer_id": "condition-timer:9",
22957                    "timer_kind": "condition_timeout",
22958                    "condition_wait_id": "condition:8",
22959                    "delay_seconds": 5,
22960                }),
22961            ),
22962            history_event(
22963                "TimerFired",
22964                json!({
22965                    "sequence": 9,
22966                    "timer_id": "condition-timer:9",
22967                    "timer_kind": "condition_timeout",
22968                    "condition_wait_id": "condition:8",
22969                    "delay_seconds": 5,
22970                }),
22971            ),
22972        ]);
22973        let mut timed_out = Box::pin(
22974            timed_out_ctx.wait_condition(
22975                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
22976                    .timeout(Duration::from_secs(5)),
22977                || Ok(true),
22978            ),
22979        );
22980        assert!(matches!(
22981            timed_out.as_mut().poll(&mut task_context),
22982            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22983        ));
22984    }
22985
22986    #[test]
22987    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
22988        let ctx = workflow_context(reopened_selection_condition_history());
22989        {
22990            let state = ctx.state.lock().unwrap();
22991            assert!(matches!(
22992                selection_member_recorded_command(&state, 2),
22993                Some(RecordedCommand::ConditionWait {
22994                    sequence: 3,
22995                    result: None,
22996                    ..
22997                })
22998            ));
22999        }
23000        let mut selected = Box::pin(ctx.select_keyed(vec![
23001            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
23002            (
23003                "votes",
23004                ParallelOperation::condition(
23005                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
23006                    || Ok(true),
23007                ),
23008            ),
23009        ]));
23010        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23011        assert!(selected.as_mut().poll(&mut task_context).is_pending());
23012        assert!(
23013            ctx.take_commands().unwrap().is_empty(),
23014            "true predicate must not reopen the recorded wait"
23015        );
23016        ctx.ensure_history_consumed()
23017            .expect("physical reopens are consumed while canonical selection is pending");
23018    }
23019
23020    #[test]
23021    fn reopened_selection_condition_replays_its_latest_physical_winner() {
23022        for (terminal_type, acknowledge_timeout) in [
23023            ("ConditionWaitSatisfied", false),
23024            ("ConditionWaitTimedOut", false),
23025            ("TimerFired", false),
23026            ("TimerFired", true),
23027        ] {
23028            let mut history = reopened_selection_condition_history();
23029            let original_identity = history[1].payload["condition_wait_id"].clone();
23030            let uses_timer = terminal_type == "TimerFired";
23031            let mut resolution_payload = history[3].payload.clone();
23032            if uses_timer {
23033                for event in &mut history[1..] {
23034                    event.payload["timeout_seconds"] = json!(3);
23035                }
23036                resolution_payload = history[3].payload.clone();
23037                resolution_payload["timer_kind"] = json!("condition_timeout");
23038                resolution_payload["timer_id"] = json!("condition-timeout-3");
23039                resolution_payload["delay_seconds"] = json!(3);
23040                history.push(history_event("TimerScheduled", resolution_payload.clone()));
23041            }
23042            let mut resolution = history_event(terminal_type, resolution_payload.clone());
23043            resolution
23044                .raw
23045                .insert("id".into(), json!("latest-condition-resolution"));
23046            history.push(resolution);
23047            history.push(history_event(
23048                "SelectionResolved",
23049                json!({
23050                    "selection_group_id": "select-calls:1:2",
23051                    "selection_group_base_sequence": 1,
23052                    "selection_group_size": 2,
23053                    "member_key": "votes",
23054                    "member_index": 1,
23055                    "member_base_sequence": 2,
23056                    "member_size": 1,
23057                    "operation_kind": "condition",
23058                    "operation_identity": original_identity,
23059                    "outcome": "completed",
23060                    "resolution_event_id": "latest-condition-resolution",
23061                    "resolution_event_type": terminal_type,
23062                }),
23063            ));
23064            if acknowledge_timeout {
23065                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
23066            }
23067            let ctx = workflow_context(history);
23068            let mut selected = Box::pin(ctx.select_keyed(vec![
23069                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
23070                (
23071                    "votes",
23072                    ParallelOperation::condition(
23073                        if uses_timer {
23074                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23075                                .timeout(Duration::from_secs(3))
23076                        } else {
23077                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23078                        },
23079                        || Ok(true),
23080                    ),
23081                ),
23082            ]));
23083            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23084            match selected.as_mut().poll(&mut task_context) {
23085                Poll::Ready(Ok(result)) => {
23086                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
23087                    let expected = if terminal_type == "ConditionWaitSatisfied" {
23088                        ConditionWaitResult::Satisfied
23089                    } else {
23090                        ConditionWaitResult::TimedOut
23091                    };
23092                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
23093                }
23094                other => panic!("latest physical winner must replay: {other:?}"),
23095            }
23096            assert!(ctx.take_commands().unwrap().is_empty());
23097            ctx.ensure_history_consumed()
23098                .expect("winner history consumed");
23099        }
23100    }
23101
23102    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
23103        let fixture: Value = serde_json::from_str(include_str!(
23104            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
23105        ))
23106        .expect("grouped condition fixture");
23107        fixture["history"]
23108            .as_array()
23109            .unwrap()
23110            .iter()
23111            .map(|event| {
23112                let mut payload = event["payload"].clone();
23113                let index = payload["parallel_group_index"].as_u64().unwrap();
23114                payload["parallel_group_id"] = json!("select-calls:1:2");
23115                payload["parallel_group_mode"] = json!("select");
23116                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
23117                payload["selection_member_index"] = json!(index);
23118                payload["selection_member_base_sequence"] = json!(index + 1);
23119                payload["selection_member_size"] = json!(1);
23120                payload["selection_member_kind"] =
23121                    json!(if index == 0 { "timer" } else { "condition" });
23122                history_event(event["event_type"].as_str().unwrap(), payload)
23123            })
23124            .collect()
23125    }
23126
23127    #[test]
23128    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
23129        let fixture: Value = serde_json::from_str(include_str!(
23130            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
23131        ))
23132        .expect("grouped condition fixture");
23133        let original = fixture["history"].as_array().expect("fixture history");
23134        let decode = |events: &[Value]| {
23135            let history = events
23136                .iter()
23137                .map(|event| {
23138                    history_event(
23139                        event["event_type"].as_str().unwrap(),
23140                        event["payload"].clone(),
23141                    )
23142                })
23143                .collect::<Vec<_>>();
23144            recorded_commands(
23145                &history,
23146                DEFAULT_CODEC,
23147                WorkflowIdentity {
23148                    workflow_id: None,
23149                    run_id: None,
23150                },
23151            )
23152        };
23153        assert!(decode(original).is_ok());
23154        for field in [
23155            "condition_wait_occurrence_id",
23156            "condition_key",
23157            "condition_definition_fingerprint",
23158            "timeout_seconds",
23159            "parallel_group_id",
23160            "parallel_group_size",
23161            "parallel_group_index",
23162        ] {
23163            let mut changed = original.clone();
23164            changed[3]["payload"][field] = match field {
23165                "timeout_seconds" | "parallel_group_size" => json!(30),
23166                "parallel_group_index" => json!(0),
23167                _ => json!("changed"),
23168            };
23169            assert!(
23170                decode(&changed).is_err(),
23171                "reopen must reject changed {field}"
23172            );
23173        }
23174        let mut unsettled = original.clone();
23175        unsettled.remove(2);
23176        assert!(
23177            decode(&unsettled).is_err(),
23178            "physical predecessor must be resolved"
23179        );
23180        let mut timed_out = original.clone();
23181        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
23182        assert!(decode(&timed_out).is_err(), "timeout is terminal");
23183        let mut late_resolution = original.clone();
23184        late_resolution.swap(2, 3);
23185        assert!(
23186            decode(&late_resolution).is_err(),
23187            "later history cannot authorize a reopen"
23188        );
23189    }
23190
23191    #[test]
23192    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
23193        let history = vec![
23194            history_event(
23195                "ConditionWaitOpened",
23196                json!({
23197                    "sequence": 3,
23198                    "condition_wait_id": "condition:3",
23199                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23200                    "condition_key": "two-votes",
23201                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23202                }),
23203            ),
23204            history_event(
23205                "SignalReceived",
23206                json!({
23207                    "workflow_sequence": 3,
23208                    "signal_name": "vote",
23209                    "arguments": fixture_envelope(json!(["first"])),
23210                }),
23211            ),
23212            history_event(
23213                "ConditionWaitSatisfied",
23214                json!({
23215                    "sequence": 3,
23216                    "condition_wait_id": "condition:3",
23217                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23218                    "condition_key": "two-votes",
23219                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23220                }),
23221            ),
23222            history_event(
23223                "ConditionWaitOpened",
23224                json!({
23225                    "sequence": 5,
23226                    "condition_wait_id": "condition:5",
23227                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23228                    "condition_key": "two-votes",
23229                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23230                }),
23231            ),
23232            history_event(
23233                "SignalReceived",
23234                json!({
23235                    "workflow_sequence": 5,
23236                    "signal_name": "vote",
23237                    "arguments": fixture_envelope(json!(["second"])),
23238                }),
23239            ),
23240            history_event(
23241                "ConditionWaitSatisfied",
23242                json!({
23243                    "sequence": 5,
23244                    "condition_wait_id": "condition:5",
23245                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23246                    "condition_key": "two-votes",
23247                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23248                }),
23249            ),
23250        ];
23251        for _cold_worker_or_restart in 0..2 {
23252            let ctx = workflow_context(history.clone());
23253            let predicate_ctx = ctx.clone();
23254            let mut wait = Box::pin(ctx.wait_condition(
23255                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
23256                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23257            ));
23258            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23259
23260            assert!(matches!(
23261                wait.as_mut().poll(&mut task_context),
23262                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23263            ));
23264            assert!(ctx.take_commands().expect("commands").is_empty());
23265            ctx.ensure_history_consumed()
23266                .expect("every physical wait-open is consumed");
23267        }
23268    }
23269
23270    #[test]
23271    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
23272        let history = vec![
23273            history_event(
23274                "ConditionWaitOpened",
23275                json!({
23276                    "sequence": 3,
23277                    "condition_wait_id": "condition:3",
23278                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23279                    "condition_key": "approved",
23280                    "condition_definition_fingerprint": "sha256:approved-v1",
23281                }),
23282            ),
23283            history_event(
23284                "UpdateApplied",
23285                json!({
23286                    "sequence": 3,
23287                    "update_id": "update-1",
23288                    "update_name": "approve",
23289                    "arguments": fixture_envelope(json!([false])),
23290                }),
23291            ),
23292            history_event(
23293                "ConditionWaitOpened",
23294                json!({
23295                    "sequence": 5,
23296                    "condition_wait_id": "condition:5",
23297                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23298                    "condition_key": "approved",
23299                    "condition_definition_fingerprint": "sha256:approved-v1",
23300                }),
23301            ),
23302            history_event(
23303                "UpdateApplied",
23304                json!({
23305                    "sequence": 5,
23306                    "update_id": "update-2",
23307                    "update_name": "approve",
23308                    "arguments": fixture_envelope(json!([true])),
23309                }),
23310            ),
23311        ];
23312
23313        for _cold_worker_or_restart in 0..2 {
23314            let ctx = workflow_context(history.clone());
23315            let predicate_ctx = ctx.clone();
23316            let mut wait = Box::pin(ctx.wait_condition(
23317                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
23318                move || {
23319                    Ok(predicate_ctx
23320                        .updates("approve")?
23321                        .last()
23322                        .and_then(|arguments| arguments.first())
23323                        .and_then(Value::as_bool)
23324                        == Some(true))
23325                },
23326            ));
23327            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23328
23329            assert!(matches!(
23330                wait.as_mut().poll(&mut task_context),
23331                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23332            ));
23333            assert!(ctx.take_commands().expect("commands").is_empty());
23334            ctx.ensure_history_consumed()
23335                .expect("every update-driven reopen is consumed");
23336        }
23337    }
23338
23339    #[test]
23340    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
23341        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
23342            ("shared", "sha256:first", "shared", "sha256:second"),
23343            ("first", "sha256:shared", "second", "sha256:shared"),
23344            ("shared", "sha256:shared", "shared", "sha256:shared"),
23345            ("first", "sha256:first", "second", "sha256:second"),
23346        ] {
23347            let history = vec![
23348                history_event(
23349                    "ConditionWaitOpened",
23350                    json!({
23351                        "sequence": 3,
23352                        "condition_wait_id": "condition:3",
23353                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23354                        "condition_key": first_key,
23355                        "condition_definition_fingerprint": first_fingerprint,
23356                    }),
23357                ),
23358                history_event(
23359                    "ConditionWaitSatisfied",
23360                    json!({
23361                        "sequence": 3,
23362                        "condition_wait_id": "condition:3",
23363                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23364                        "condition_key": first_key,
23365                        "condition_definition_fingerprint": first_fingerprint,
23366                    }),
23367                ),
23368                history_event(
23369                    "ConditionWaitOpened",
23370                    json!({
23371                        "sequence": 4,
23372                        "condition_wait_id": "condition:4",
23373                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23374                        "condition_key": second_key,
23375                        "condition_definition_fingerprint": second_fingerprint,
23376                    }),
23377                ),
23378                history_event(
23379                    "ConditionWaitSatisfied",
23380                    json!({
23381                        "sequence": 4,
23382                        "condition_wait_id": "condition:4",
23383                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23384                        "condition_key": second_key,
23385                        "condition_definition_fingerprint": second_fingerprint,
23386                    }),
23387                ),
23388            ];
23389            for _cold_worker_or_restart in 0..2 {
23390                let ctx = workflow_context(history.clone());
23391                let mut task_context = TaskContext::from_waker(noop_waker_ref());
23392                let mut first = Box::pin(ctx.wait_condition(
23393                    ConditionWaitOptions::new(first_key, first_fingerprint),
23394                    || Ok(false),
23395                ));
23396                assert!(matches!(
23397                    first.as_mut().poll(&mut task_context),
23398                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23399                ));
23400
23401                let mut second = Box::pin(ctx.wait_condition(
23402                    ConditionWaitOptions::new(second_key, second_fingerprint),
23403                    || Ok(false),
23404                ));
23405                assert!(matches!(
23406                    second.as_mut().poll(&mut task_context),
23407                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23408                ));
23409                assert!(ctx.take_commands().expect("commands").is_empty());
23410                ctx.ensure_history_consumed()
23411                    .expect("each authored wait consumes one occurrence");
23412            }
23413        }
23414    }
23415
23416    #[test]
23417    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
23418        fn worker() -> Worker {
23419            let client = Client::new("http://127.0.0.1:8080").expect("client");
23420            let mut worker = Worker::new(client, "rust-workers");
23421            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
23422                let mut outcomes = Vec::new();
23423                for _ in 0..2 {
23424                    outcomes.push(
23425                        ctx.wait_condition(
23426                            ConditionWaitOptions::new("shared", "sha256:shared"),
23427                            || Ok(false),
23428                        )
23429                        .await?,
23430                    );
23431                }
23432                Ok(json!(outcomes))
23433            });
23434            worker
23435        }
23436
23437        let task = workflow_task(
23438            "rust.condition-loop",
23439            vec![
23440                history_event(
23441                    "ConditionWaitOpened",
23442                    json!({
23443                        "sequence": 1,
23444                        "condition_wait_id": "condition:1",
23445                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23446                        "condition_key": "shared",
23447                        "condition_definition_fingerprint": "sha256:shared",
23448                    }),
23449                ),
23450                history_event(
23451                    "ConditionWaitSatisfied",
23452                    json!({
23453                        "sequence": 1,
23454                        "condition_wait_id": "condition:1",
23455                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23456                        "condition_key": "shared",
23457                        "condition_definition_fingerprint": "sha256:shared",
23458                    }),
23459                ),
23460                history_event(
23461                    "ConditionWaitOpened",
23462                    json!({
23463                        "sequence": 2,
23464                        "condition_wait_id": "condition:2",
23465                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23466                        "condition_key": "shared",
23467                        "condition_definition_fingerprint": "sha256:shared",
23468                    }),
23469                ),
23470                history_event(
23471                    "ConditionWaitSatisfied",
23472                    json!({
23473                        "sequence": 2,
23474                        "condition_wait_id": "condition:2",
23475                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23476                        "condition_key": "shared",
23477                        "condition_definition_fingerprint": "sha256:shared",
23478                    }),
23479                ),
23480            ],
23481            DEFAULT_CODEC,
23482        );
23483
23484        for _cold_worker_or_restart in 0..2 {
23485            let commands = worker()
23486                .execute_workflow_task(task.clone())
23487                .expect("adjacent loop waits replay deterministically");
23488            assert_eq!(commands.len(), 1);
23489            assert_eq!(commands[0]["type"], "complete_workflow");
23490            assert_eq!(
23491                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23492                json!(["satisfied", "satisfied"])
23493            );
23494        }
23495    }
23496
23497    #[test]
23498    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
23499        let history = vec![history_event(
23500            "ConditionWaitOpened",
23501            json!({
23502                "sequence": 12,
23503                "condition_wait_id": "condition:12",
23504                "condition_wait_occurrence_id": "rust:condition-wait:0",
23505                "condition_key": "approval",
23506                "condition_definition_fingerprint": "sha256:approval-v1",
23507                "timeout_seconds": 30,
23508            }),
23509        )];
23510        for (options, expected_reason) in [
23511            (
23512                ConditionWaitOptions::new("changed", "sha256:approval-v1")
23513                    .timeout(Duration::from_secs(30)),
23514                "condition_wait_key_mismatch",
23515            ),
23516            (
23517                ConditionWaitOptions::new("approval", "sha256:approval-v2")
23518                    .timeout(Duration::from_secs(30)),
23519                "condition_wait_predicate_mismatch",
23520            ),
23521            (
23522                ConditionWaitOptions::new("approval", "sha256:approval-v1")
23523                    .timeout(Duration::from_secs(29)),
23524                "condition_wait_timeout_mismatch",
23525            ),
23526        ] {
23527            let ctx = workflow_context(history.clone());
23528            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
23529            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23530            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23531                wait.as_mut().poll(&mut task_context)
23532            else {
23533                panic!("changed condition definition must fail replay");
23534            };
23535            assert_eq!(failure.reason, expected_reason);
23536            assert_eq!(failure.sequence, Some(12));
23537        }
23538    }
23539
23540    #[test]
23541    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
23542        let error = WorkflowState::new(
23543            vec![history_event(
23544                "ConditionWaitOpened",
23545                json!({
23546                    "sequence": 12,
23547                    "condition_wait_id": "condition:12",
23548                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23549                    "condition_key": "approval",
23550                }),
23551            )],
23552            "rust-workers".to_string(),
23553            DEFAULT_CODEC.to_string(),
23554            None,
23555        )
23556        .expect_err("condition history without a predicate fingerprint must fail");
23557
23558        assert!(matches!(
23559            error,
23560            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23561                if reason == "condition_wait_predicate_fingerprint_missing"
23562        ));
23563    }
23564
23565    #[test]
23566    fn condition_wait_history_requires_authored_occurrence_identity() {
23567        let error = WorkflowState::new(
23568            vec![history_event(
23569                "ConditionWaitOpened",
23570                json!({
23571                    "sequence": 12,
23572                    "condition_wait_id": "condition:12",
23573                    "condition_key": "approval",
23574                    "condition_definition_fingerprint": "sha256:approval-v1",
23575                }),
23576            )],
23577            "rust-workers".to_string(),
23578            DEFAULT_CODEC.to_string(),
23579            None,
23580        )
23581        .expect_err("condition history without occurrence identity must fail");
23582
23583        assert!(matches!(
23584            error,
23585            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23586                if reason == "condition_wait_occurrence_id_missing"
23587        ));
23588    }
23589
23590    #[test]
23591    fn typed_search_attribute_updates_validate_emit_and_replay() {
23592        let update = SearchAttributeUpdate::new()
23593            .keyword("OrderStatus", " waiting ")
23594            .expect("keyword")
23595            .int("Attempt", 3)
23596            .expect("int")
23597            .bool("Escalated", false)
23598            .expect("bool")
23599            .keyword_list("Regions", ["us-east", "eu-west"])
23600            .expect("list")
23601            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
23602            .expect("datetime")
23603            .delete("LegacyStatus")
23604            .expect("delete");
23605        let ctx = workflow_context(Vec::new());
23606        ctx.upsert_search_attributes(update.clone())
23607            .expect("typed update");
23608        assert_eq!(
23609            ctx.take_commands().expect("search-attribute command"),
23610            vec![json!({
23611                "type": "upsert_search_attributes",
23612                "attributes": {
23613                    "Attempt": 3,
23614                    "Escalated": false,
23615                    "LegacyStatus": null,
23616                    "OrderStatus": "waiting",
23617                    "Regions": ["us-east", "eu-west"],
23618                    "UpdatedAt": "2026-08-22T04:00:00Z",
23619                },
23620                "attribute_types": {
23621                    "Attempt": "int",
23622                    "Escalated": "bool",
23623                    "OrderStatus": "keyword",
23624                    "Regions": "keyword_list",
23625                    "UpdatedAt": "datetime",
23626                },
23627            })]
23628        );
23629
23630        let replay = workflow_context(vec![history_event(
23631            "SearchAttributesUpserted",
23632            json!({
23633                "sequence": 6,
23634                "attributes": {
23635                    "Attempt": 3,
23636                    "Escalated": false,
23637                    "LegacyStatus": null,
23638                    "OrderStatus": "waiting",
23639                    "Regions": ["us-east", "eu-west"],
23640                    "UpdatedAt": "2026-08-22T04:00:00Z",
23641                },
23642                "attribute_types": {
23643                    "Attempt": "int",
23644                    "Escalated": "bool",
23645                    "OrderStatus": "keyword",
23646                    "Regions": "keyword_list",
23647                    "UpdatedAt": "datetime",
23648                },
23649                "merged": {},
23650            }),
23651        )]);
23652        replay
23653            .upsert_search_attributes(update)
23654            .expect("matching update replays");
23655        assert!(replay.take_commands().expect("commands").is_empty());
23656        replay.ensure_history_consumed().expect("history consumed");
23657
23658        let type_drift = workflow_context(vec![history_event(
23659            "SearchAttributesUpserted",
23660            json!({
23661                "sequence": 7,
23662                "attributes": {"OrderStatus": "waiting"},
23663                "attribute_types": {"OrderStatus": "keyword"},
23664                "merged": {"OrderStatus": "waiting"},
23665            }),
23666        )]);
23667        let error = type_drift
23668            .upsert_search_attributes(
23669                SearchAttributeUpdate::new()
23670                    .string("OrderStatus", "waiting")
23671                    .expect("string update"),
23672            )
23673            .expect_err("same JSON value with a changed type must fail replay");
23674        assert!(matches!(
23675            error,
23676            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23677                if reason == "search_attribute_type_mismatch"
23678        ));
23679
23680        let malformed_types = WorkflowState::new(
23681            vec![history_event(
23682                "SearchAttributesUpserted",
23683                json!({
23684                    "sequence": 8,
23685                    "attributes": {"OrderStatus": "waiting"},
23686                    "attribute_types": {"OrderStatus": "unsupported"},
23687                    "merged": {"OrderStatus": "waiting"},
23688                }),
23689            )],
23690            "rust-workers".to_string(),
23691            DEFAULT_CODEC.to_string(),
23692            None,
23693        )
23694        .expect_err("unsupported search-attribute type metadata must fail");
23695        assert!(matches!(
23696            malformed_types,
23697            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23698                if reason == "search_attribute_types_malformed"
23699        ));
23700
23701        assert!(matches!(
23702            SearchAttributeUpdate::new().keyword("bad key", "value"),
23703            Err(SearchAttributeUpdateError::InvalidKey(_))
23704        ));
23705        assert!(matches!(
23706            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
23707            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
23708        ));
23709        assert!(matches!(
23710            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
23711            Err(SearchAttributeUpdateError::ValueTooLong { .. })
23712        ));
23713        assert!(matches!(
23714            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
23715            Err(SearchAttributeUpdateError::InvalidDateTime(_))
23716        ));
23717        assert!(matches!(
23718            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
23719            Err(Error::InvalidSearchAttributeUpdate(
23720                SearchAttributeUpdateError::Empty
23721            ))
23722        ));
23723    }
23724
23725    #[test]
23726    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
23727        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
23728        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
23729
23730        assert!(SearchAttributeUpdate::new()
23731            .string("AsciiDescription", ascii)
23732            .is_ok());
23733        assert!(SearchAttributeUpdate::new()
23734            .string("Utf8Description", utf8)
23735            .is_ok());
23736        assert!(matches!(
23737            SearchAttributeUpdate::new().string(
23738                "TooLongDescription",
23739                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
23740            ),
23741            Err(SearchAttributeUpdateError::ValueTooLong {
23742                kind: "string",
23743                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
23744                ..
23745            })
23746        ));
23747    }
23748
23749    #[test]
23750    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
23751        let lone_fire = WorkflowState::new(
23752            vec![history_event(
23753                "TimerFired",
23754                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23755            )],
23756            "rust-workers".to_string(),
23757            DEFAULT_CODEC.to_string(),
23758            None,
23759        )
23760        .expect_err("TimerFired requires TimerScheduled");
23761        assert!(matches!(
23762            lone_fire,
23763            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23764                if reason == "timer_schedule_missing_or_duplicate"
23765        ));
23766
23767        let wrong_identity = WorkflowState::new(
23768            vec![
23769                history_event(
23770                    "TimerScheduled",
23771                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23772                ),
23773                history_event(
23774                    "TimerFired",
23775                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23776                ),
23777            ],
23778            "rust-workers".to_string(),
23779            DEFAULT_CODEC.to_string(),
23780            None,
23781        )
23782        .expect_err("fire must match scheduled timer identity");
23783        assert!(matches!(
23784            wrong_identity,
23785            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23786                if reason == "timer_identity_mismatch"
23787        ));
23788
23789        let duplicate_fire = WorkflowState::new(
23790            vec![
23791                history_event(
23792                    "TimerScheduled",
23793                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23794                ),
23795                history_event(
23796                    "TimerFired",
23797                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23798                ),
23799                history_event(
23800                    "TimerFired",
23801                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23802                ),
23803            ],
23804            "rust-workers".to_string(),
23805            DEFAULT_CODEC.to_string(),
23806            None,
23807        )
23808        .expect_err("a durable timer cannot fire twice");
23809        assert!(matches!(
23810            duplicate_fire,
23811            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23812                if reason == "duplicate_timer_fire"
23813        ));
23814
23815        let wrong_fired_delay = WorkflowState::new(
23816            vec![
23817                history_event(
23818                    "TimerScheduled",
23819                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23820                ),
23821                history_event(
23822                    "TimerFired",
23823                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
23824                ),
23825            ],
23826            "rust-workers".to_string(),
23827            DEFAULT_CODEC.to_string(),
23828            None,
23829        )
23830        .expect_err("timer schedule and fire delays must agree");
23831        assert!(matches!(
23832            wrong_fired_delay,
23833            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23834                if reason == "timer_history_delay_mismatch"
23835        ));
23836    }
23837
23838    #[test]
23839    fn replay_rejects_activity_moved_before_recorded_timer() {
23840        let ctx = workflow_context(vec![
23841            history_event(
23842                "TimerScheduled",
23843                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23844            ),
23845            history_event(
23846                "TimerFired",
23847                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23848            ),
23849            history_event(
23850                "ActivityCompleted",
23851                json!({
23852                    "sequence": 2,
23853                    "activity_type": "after-timer",
23854                    "payload_codec": DEFAULT_CODEC,
23855                    "result": fixture_envelope(json!("done")),
23856                }),
23857            ),
23858        ]);
23859        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
23860        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23861
23862        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23863            activity.as_mut().poll(&mut task_context)
23864        else {
23865            panic!("reordered durable command must be rejected");
23866        };
23867        assert_eq!(failure.reason, "recorded_command_mismatch");
23868        assert_eq!(failure.sequence, Some(1));
23869        assert_eq!(failure.expected.as_deref(), Some("timer"));
23870        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
23871    }
23872
23873    #[test]
23874    fn workflow_context_emits_a_typed_named_signal_wait() {
23875        let ctx = workflow_context(Vec::new());
23876        let mut signal = Box::pin(ctx.wait_signal("finish"));
23877        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23878
23879        assert!(matches!(
23880            signal.as_mut().poll(&mut task_context),
23881            Poll::Pending
23882        ));
23883        assert_eq!(
23884            ctx.take_commands().expect("signal-wait command"),
23885            vec![json!({
23886                "type": "open_signal_wait",
23887                "signal_name": "finish",
23888            })]
23889        );
23890    }
23891
23892    #[test]
23893    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
23894        let ctx = workflow_context(Vec::new());
23895        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
23896        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23897
23898        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
23899        else {
23900            panic!("runtime-reserved signal should be rejected");
23901        };
23902        assert!(message.contains("reserved by the workflow runtime"));
23903        assert!(ctx.take_commands().expect("commands").is_empty());
23904    }
23905
23906    #[tokio::test]
23907    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
23908        let client = Client::builder("http://127.0.0.1:9")
23909            .build()
23910            .expect("client");
23911        let error = client
23912            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
23913            .await
23914            .expect_err("runtime-reserved signal should be rejected before transport");
23915
23916        assert!(
23917            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
23918        );
23919    }
23920
23921    #[test]
23922    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
23923        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23924            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23925                value.to_string(),
23926            )]))
23927            .expect("message payload");
23928            json!({
23929                "schema": MESSAGE_STREAM_SCHEMA,
23930                "stream_name": "orders",
23931                "message_id": message_id,
23932                "position": position,
23933                "payload_envelope": payload,
23934            })
23935        }
23936
23937        fn opened(sequence: u64) -> HistoryEvent {
23938            history_event(
23939                "SignalWaitOpened",
23940                json!({
23941                    "sequence": sequence,
23942                    "signal_name": MESSAGE_STREAM_SIGNAL,
23943                }),
23944            )
23945        }
23946
23947        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23948            history_event(
23949                "SignalApplied",
23950                json!({
23951                    "sequence": sequence,
23952                    "signal_name": MESSAGE_STREAM_SIGNAL,
23953                    "value": fixture_envelope(json!([delivery])),
23954                }),
23955            )
23956        }
23957
23958        fn received(delivery: Value) -> HistoryEvent {
23959            history_event(
23960                "SignalReceived",
23961                json!({
23962                    "signal_name": MESSAGE_STREAM_SIGNAL,
23963                    "arguments": fixture_envelope(json!([delivery])),
23964                    "payload_codec": DEFAULT_CODEC,
23965                }),
23966            )
23967        }
23968
23969        let client = Client::new("http://127.0.0.1:8080").expect("client");
23970        let mut worker = Worker::new(client, "rust-workers");
23971        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
23972            let messages = ctx.message_stream("orders")?.receive(2).await?;
23973            Ok(json!(messages
23974                .into_iter()
23975                .map(|message| message.message_id)
23976                .collect::<Vec<_>>()))
23977        });
23978
23979        let first = delivery("message-1", 1, "one");
23980        let second = delivery("message-2", 2, "two");
23981        let batch = worker
23982            .execute_workflow_task_decision(workflow_task(
23983                "rust.message-stream-batch",
23984                vec![
23985                    opened(1),
23986                    received(first.clone()),
23987                    applied(1, first.clone()),
23988                    received(first.clone()),
23989                    received(second),
23990                ],
23991                DEFAULT_CODEC,
23992            ))
23993            .expect("worker task consumes the available batch");
23994
23995        assert_eq!(batch.commands.len(), 1);
23996        assert_eq!(batch.commands[0]["type"], "complete_workflow");
23997        assert_eq!(
23998            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
23999                .expect("workflow result"),
24000            json!(["message-1", "message-2"])
24001        );
24002        assert_eq!(
24003            batch.message_stream_cursors,
24004            vec![json!({"stream_name": "orders", "through_position": 2})]
24005        );
24006        assert!(batch.message_stream_waits.is_empty());
24007
24008        let partial = worker
24009            .execute_workflow_task_decision(workflow_task(
24010                "rust.message-stream-batch",
24011                vec![opened(1), received(first.clone()), applied(1, first)],
24012                DEFAULT_CODEC,
24013            ))
24014            .expect("worker task returns without waiting for a missing second item");
24015        assert_eq!(partial.commands.len(), 1);
24016        assert_eq!(partial.commands[0]["type"], "complete_workflow");
24017        assert_eq!(
24018            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
24019                .expect("workflow result"),
24020            json!(["message-1"])
24021        );
24022        assert_eq!(
24023            partial.message_stream_cursors,
24024            vec![json!({"stream_name": "orders", "through_position": 1})]
24025        );
24026        assert!(partial.message_stream_waits.is_empty());
24027    }
24028
24029    #[test]
24030    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
24031        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24032            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24033                value.to_string(),
24034            )]))
24035            .expect("message payload");
24036            json!({
24037                "schema": MESSAGE_STREAM_SCHEMA,
24038                "stream_name": "orders",
24039                "message_id": message_id,
24040                "position": position,
24041                "payload_envelope": payload,
24042            })
24043        }
24044
24045        fn opened(sequence: u64) -> HistoryEvent {
24046            history_event(
24047                "SignalWaitOpened",
24048                json!({
24049                    "sequence": sequence,
24050                    "signal_name": MESSAGE_STREAM_SIGNAL,
24051                }),
24052            )
24053        }
24054
24055        fn received(delivery: Value) -> HistoryEvent {
24056            history_event(
24057                "SignalReceived",
24058                json!({
24059                    "signal_name": MESSAGE_STREAM_SIGNAL,
24060                    "arguments": fixture_envelope(json!([delivery])),
24061                    "payload_codec": DEFAULT_CODEC,
24062                }),
24063            )
24064        }
24065
24066        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24067            history_event(
24068                "SignalApplied",
24069                json!({
24070                    "sequence": sequence,
24071                    "signal_name": MESSAGE_STREAM_SIGNAL,
24072                    "value": fixture_envelope(json!([delivery])),
24073                }),
24074            )
24075        }
24076
24077        let client = Client::new("http://127.0.0.1:8080").expect("client");
24078        let mut worker = Worker::new(client, "rust-workers");
24079        worker.register_workflow(
24080            "rust.message-stream-partial-batches",
24081            |ctx, _input| async move {
24082                let stream = ctx.message_stream("orders")?;
24083                let first = stream.receive(10).await?;
24084                let second = stream.receive(10).await?;
24085                Ok(json!([
24086                    first
24087                        .into_iter()
24088                        .map(|message| message.message_id)
24089                        .collect::<Vec<_>>(),
24090                    second
24091                        .into_iter()
24092                        .map(|message| message.message_id)
24093                        .collect::<Vec<_>>(),
24094                ]))
24095            },
24096        );
24097
24098        let first = delivery("message-1", 1, "one");
24099        let second = delivery("message-2", 2, "two");
24100        let decision = worker
24101            .execute_workflow_task_decision(workflow_task(
24102                "rust.message-stream-partial-batches",
24103                vec![
24104                    opened(1),
24105                    received(first.clone()),
24106                    applied(1, first),
24107                    opened(2),
24108                    received(second.clone()),
24109                    applied(2, second),
24110                ],
24111                DEFAULT_CODEC,
24112            ))
24113            .expect("cold replay preserves both authored receive boundaries");
24114
24115        assert_eq!(decision.commands.len(), 1);
24116        assert_eq!(decision.commands[0]["type"], "complete_workflow");
24117        assert_eq!(
24118            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
24119                .expect("workflow result"),
24120            json!([["message-1"], ["message-2"]])
24121        );
24122        assert_eq!(
24123            decision.message_stream_cursors,
24124            vec![json!({"stream_name": "orders", "through_position": 2})]
24125        );
24126        assert!(decision.message_stream_waits.is_empty());
24127    }
24128
24129    #[test]
24130    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
24131        let ctx = workflow_context(Vec::new());
24132        let stream = ctx.message_stream("orders").expect("message stream");
24133        let mut receive = Box::pin(stream.receive(10));
24134        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24135
24136        assert!(matches!(
24137            receive.as_mut().poll(&mut task_context),
24138            Poll::Pending
24139        ));
24140        assert_eq!(
24141            ctx.take_commands().expect("message-stream wait command"),
24142            vec![json!({
24143                "type": "open_signal_wait",
24144                "signal_name": MESSAGE_STREAM_SIGNAL,
24145            })]
24146        );
24147        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
24148        assert!(cursors.is_empty());
24149        assert_eq!(
24150            waits,
24151            vec![json!({"stream_name": "orders", "after_position": 0})]
24152        );
24153    }
24154
24155    #[test]
24156    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
24157        let ctx = workflow_context(vec![history_event(
24158            "SignalReceived",
24159            json!({
24160                "signal_name": MESSAGE_STREAM_SIGNAL,
24161                "arguments": fixture_envelope(json!([{
24162                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
24163                    "stream_name": "orders",
24164                    "through_position": 2,
24165                }])),
24166                "payload_codec": DEFAULT_CODEC,
24167            }),
24168        )]);
24169        let stream = ctx.message_stream("orders").expect("message stream");
24170        let mut receive = Box::pin(stream.receive(10));
24171        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24172
24173        assert!(matches!(
24174            receive.as_mut().poll(&mut task_context),
24175            Poll::Pending
24176        ));
24177        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
24178        assert_eq!(
24179            cursors,
24180            vec![json!({"stream_name": "orders", "through_position": 2})]
24181        );
24182        assert_eq!(
24183            waits,
24184            vec![json!({"stream_name": "orders", "after_position": 2})]
24185        );
24186    }
24187
24188    #[test]
24189    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
24190        let mut empty_map = BTreeMap::new();
24191        let mut nested = BTreeMap::new();
24192        nested.insert(
24193            "value".to_string(),
24194            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
24195        );
24196        let values = vec![
24197            AvroValue::Bytes(vec![0, 255]),
24198            AvroValue::Long(1),
24199            AvroValue::Double(1.0),
24200            AvroValue::Array(Vec::new()),
24201            AvroValue::Map(std::mem::take(&mut empty_map)),
24202            AvroValue::Map(nested),
24203        ];
24204        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
24205        let transport = vec![json!({
24206            "schema": MESSAGE_STREAM_SCHEMA,
24207            "stream_name": "orders",
24208            "message_id": "message-1",
24209            "position": 1,
24210            "payload_envelope": payload,
24211        })];
24212
24213        for _ in 0..2 {
24214            let Some(MessageStreamDelivery::Message(message)) =
24215                decode_message_stream_delivery(transport.clone()).expect("delivery")
24216            else {
24217                panic!("message delivery expected");
24218            };
24219            assert_eq!(message.arguments, values);
24220            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
24221            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
24222        }
24223    }
24224
24225    #[test]
24226    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
24227        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24228            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24229                value.to_string(),
24230            )]))
24231            .expect("message payload");
24232            json!({
24233                "schema": MESSAGE_STREAM_SCHEMA,
24234                "stream_name": "orders",
24235                "message_id": message_id,
24236                "position": position,
24237                "payload_envelope": payload,
24238            })
24239        }
24240
24241        fn opened(sequence: u64) -> HistoryEvent {
24242            history_event(
24243                "SignalWaitOpened",
24244                json!({
24245                    "sequence": sequence,
24246                    "signal_name": MESSAGE_STREAM_SIGNAL,
24247                }),
24248            )
24249        }
24250
24251        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24252            history_event(
24253                "SignalApplied",
24254                json!({
24255                    "sequence": sequence,
24256                    "signal_name": MESSAGE_STREAM_SIGNAL,
24257                    "value": fixture_envelope(json!([delivery])),
24258                }),
24259            )
24260        }
24261
24262        fn worker() -> Worker {
24263            let client = Client::new("http://127.0.0.1:8080").expect("client");
24264            let mut worker = Worker::new(client, "rust-workers");
24265            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
24266                let stream = ctx.message_stream("orders")?;
24267                let first = stream.receive_one().await?;
24268                let second = stream.receive_one().await?;
24269                Ok(json!([first.message_id, second.message_id]))
24270            });
24271            worker
24272        }
24273
24274        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
24275            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
24276            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
24277            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
24278            task
24279        }
24280
24281        let waiting = worker()
24282            .execute_workflow_task_decision(workflow_task(
24283                "rust.message-stream",
24284                Vec::new(),
24285                DEFAULT_CODEC,
24286            ))
24287            .expect("first worker opens the stream wait");
24288        assert_eq!(
24289            waiting.commands,
24290            vec![json!({
24291                "type": "open_signal_wait",
24292                "signal_name": MESSAGE_STREAM_SIGNAL,
24293            })]
24294        );
24295        assert!(waiting.message_stream_cursors.is_empty());
24296        assert_eq!(
24297            waiting.message_stream_waits,
24298            vec![json!({"stream_name": "orders", "after_position": 0})]
24299        );
24300
24301        let first_delivery = delivery("message-1", 1, "one");
24302        let first_arrival = worker()
24303            .execute_workflow_task_decision(task_with_resume(
24304                vec![opened(1)],
24305                first_delivery.clone(),
24306            ))
24307            .expect("replacement worker consumes the first arrival");
24308        assert_eq!(
24309            first_arrival.commands,
24310            vec![json!({
24311                "type": "open_signal_wait",
24312                "signal_name": MESSAGE_STREAM_SIGNAL,
24313            })]
24314        );
24315        assert_eq!(
24316            first_arrival.message_stream_cursors,
24317            vec![json!({"stream_name": "orders", "through_position": 1})]
24318        );
24319        assert_eq!(
24320            first_arrival.message_stream_waits,
24321            vec![json!({"stream_name": "orders", "after_position": 1})]
24322        );
24323
24324        let second_delivery = delivery("message-2", 2, "two");
24325        let first_applied = applied(1, first_delivery);
24326        let completed = worker()
24327            .execute_workflow_task_decision(task_with_resume(
24328                vec![opened(1), first_applied.clone(), opened(2)],
24329                second_delivery.clone(),
24330            ))
24331            .expect("next replacement worker consumes the second arrival");
24332        assert_eq!(completed.commands.len(), 1);
24333        assert_eq!(completed.commands[0]["type"], "complete_workflow");
24334        assert_eq!(
24335            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
24336                .expect("workflow result"),
24337            json!(["message-1", "message-2"])
24338        );
24339        assert_eq!(
24340            completed.message_stream_cursors,
24341            vec![json!({"stream_name": "orders", "through_position": 2})]
24342        );
24343        assert!(completed.message_stream_waits.is_empty());
24344
24345        let replay_history = vec![
24346            opened(1),
24347            first_applied,
24348            opened(2),
24349            applied(2, second_delivery),
24350        ];
24351        for _cold_worker_or_restart in 0..2 {
24352            let replayed = worker()
24353                .execute_workflow_task_decision(workflow_task(
24354                    "rust.message-stream",
24355                    replay_history.clone(),
24356                    DEFAULT_CODEC,
24357                ))
24358                .expect("cold worker replays each logical message exactly once");
24359            assert_eq!(replayed.commands.len(), 1);
24360            assert_eq!(
24361                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
24362                    .expect("replayed workflow result"),
24363                json!(["message-1", "message-2"])
24364            );
24365            assert_eq!(
24366                replayed.message_stream_cursors,
24367                vec![json!({"stream_name": "orders", "through_position": 2})]
24368            );
24369            assert!(replayed.message_stream_waits.is_empty());
24370        }
24371    }
24372
24373    #[test]
24374    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
24375        assert!(!worker_protocol_supports_message_streams("1.14"));
24376        assert!(worker_protocol_supports_message_streams("1.15"));
24377        assert!(worker_protocol_supports_message_streams("1.16"));
24378        assert!(worker_protocol_supports_message_streams(
24379            WORKER_PROTOCOL_VERSION
24380        ));
24381        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
24382    }
24383
24384    #[test]
24385    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
24386        let ctx = workflow_context(vec![
24387            history_event(
24388                "ConditionWaitOpened",
24389                json!({
24390                    "sequence": 1,
24391                    "condition_wait_id": "condition:1",
24392                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24393                    "condition_key": "signal:finish",
24394                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24395                }),
24396            ),
24397            history_event(
24398                "ConditionWaitSatisfied",
24399                json!({
24400                    "sequence": 1,
24401                    "condition_wait_id": "condition:1",
24402                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24403                    "condition_key": "signal:finish",
24404                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24405                }),
24406            ),
24407            history_event(
24408                "SignalReceived",
24409                json!({"signal_name": "finish", "arguments": []}),
24410            ),
24411        ]);
24412        let mut signal = Box::pin(ctx.wait_signal("finish"));
24413        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24414
24415        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24416            signal.as_mut().poll(&mut task_context)
24417        else {
24418            panic!("condition history must not resolve as a typed signal wait");
24419        };
24420        assert_eq!(failure.reason, "recorded_command_mismatch");
24421        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
24422    }
24423
24424    #[test]
24425    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
24426        let signal_then_timer = vec![
24427            history_event(
24428                "SignalWaitOpened",
24429                json!({"sequence": 1, "signal_name": "go"}),
24430            ),
24431            history_event(
24432                "SignalApplied",
24433                json!({
24434                    "sequence": 1,
24435                    "signal_name": "go",
24436                    "value": fixture_envelope(json!(["now"])),
24437                }),
24438            ),
24439            history_event(
24440                "TimerScheduled",
24441                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24442            ),
24443            history_event(
24444                "TimerFired",
24445                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24446            ),
24447        ];
24448
24449        let ctx = workflow_context(signal_then_timer.clone());
24450        let mut signal = Box::pin(ctx.wait_signal("go"));
24451        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24452        assert!(matches!(
24453            signal.as_mut().poll(&mut task_context),
24454            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
24455        ));
24456        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
24457        assert!(matches!(
24458            timer.as_mut().poll(&mut task_context),
24459            Poll::Ready(Ok(()))
24460        ));
24461        ctx.ensure_history_consumed()
24462            .expect("signal and timer history consumed in order");
24463
24464        let reordered = workflow_context(signal_then_timer);
24465        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
24466        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24467            timer_first.as_mut().poll(&mut task_context)
24468        else {
24469            panic!("timer cannot consume signal-wait-first history");
24470        };
24471        assert_eq!(failure.reason, "recorded_command_mismatch");
24472        assert_eq!(failure.sequence, Some(1));
24473        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
24474
24475        let timer_then_signal = vec![
24476            history_event(
24477                "TimerScheduled",
24478                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24479            ),
24480            history_event(
24481                "TimerFired",
24482                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24483            ),
24484            history_event(
24485                "SignalWaitOpened",
24486                json!({"sequence": 2, "signal_name": "go"}),
24487            ),
24488            history_event(
24489                "SignalApplied",
24490                json!({
24491                    "sequence": 2,
24492                    "signal_name": "go",
24493                    "value": fixture_envelope(json!([])),
24494                }),
24495            ),
24496        ];
24497        let reordered = workflow_context(timer_then_signal);
24498        let mut signal_first = Box::pin(reordered.wait_signal("go"));
24499        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24500            signal_first.as_mut().poll(&mut task_context)
24501        else {
24502            panic!("signal wait cannot consume timer-first history");
24503        };
24504        assert_eq!(failure.reason, "recorded_command_mismatch");
24505        assert_eq!(failure.sequence, Some(1));
24506        assert_eq!(failure.expected.as_deref(), Some("timer"));
24507    }
24508
24509    #[test]
24510    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
24511        let duplicate_timer = WorkflowState::new(
24512            vec![
24513                history_event(
24514                    "TimerScheduled",
24515                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24516                ),
24517                history_event(
24518                    "TimerScheduled",
24519                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24520                ),
24521            ],
24522            "rust-workers".to_string(),
24523            DEFAULT_CODEC.to_string(),
24524            None,
24525        )
24526        .expect_err("one workflow sequence cannot schedule two timers");
24527        assert!(matches!(
24528            duplicate_timer,
24529            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24530                if reason == "timer_schedule_missing_or_duplicate"
24531        ));
24532
24533        let colliding_kinds = WorkflowState::new(
24534            vec![
24535                history_event(
24536                    "TimerScheduled",
24537                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24538                ),
24539                history_event(
24540                    "ActivityCompleted",
24541                    json!({"sequence": 1, "activity_type": "same-sequence"}),
24542                ),
24543            ],
24544            "rust-workers".to_string(),
24545            DEFAULT_CODEC.to_string(),
24546            None,
24547        )
24548        .expect_err("one workflow sequence cannot identify two command kinds");
24549        assert!(matches!(
24550            colliding_kinds,
24551            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24552                if reason == "durable_command_sequence_collision"
24553        ));
24554
24555        let duplicate_signal_wait = WorkflowState::new(
24556            vec![
24557                history_event(
24558                    "SignalWaitOpened",
24559                    json!({"sequence": 1, "signal_name": "go"}),
24560                ),
24561                history_event(
24562                    "SignalWaitOpened",
24563                    json!({"sequence": 1, "signal_name": "go"}),
24564                ),
24565            ],
24566            "rust-workers".to_string(),
24567            DEFAULT_CODEC.to_string(),
24568            None,
24569        )
24570        .expect_err("one workflow sequence cannot open two signal waits");
24571        assert!(matches!(
24572            duplicate_signal_wait,
24573            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24574                if reason == "signal_wait_open_missing_or_duplicate"
24575        ));
24576    }
24577
24578    #[test]
24579    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
24580        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
24581            .expect("side-effect result");
24582        let ctx = workflow_context(vec![history_event(
24583            "SideEffectRecorded",
24584            json!({"sequence": 99, "result": result}),
24585        )]);
24586
24587        let replayed: Value = ctx
24588            .side_effect(|| panic!("recorded side effect must not run"))
24589            .expect("positive global workflow sequence is valid");
24590        assert_eq!(replayed, json!({"captured": true}));
24591        ctx.ensure_history_consumed().expect("history consumed");
24592    }
24593
24594    #[test]
24595    fn workflow_history_rejects_zero_and_descending_command_sequences() {
24596        let result =
24597            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
24598        let zero = WorkflowState::new(
24599            vec![history_event(
24600                "SideEffectRecorded",
24601                json!({"sequence": 0, "result": result.clone()}),
24602            )],
24603            "rust-workers".to_string(),
24604            DEFAULT_CODEC.to_string(),
24605            None,
24606        )
24607        .expect_err("durable command sequences must be positive");
24608        assert!(matches!(
24609            zero,
24610            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24611                if reason == "durable_command_sequence_invalid"
24612        ));
24613
24614        let descending = WorkflowState::new(
24615            vec![
24616                history_event(
24617                    "SideEffectRecorded",
24618                    json!({"sequence": 3, "result": result}),
24619                ),
24620                history_event(
24621                    "VersionMarkerRecorded",
24622                    json!({
24623                        "sequence": 2,
24624                        "change_id": "descending-marker",
24625                        "version": 1,
24626                        "min_supported": 1,
24627                        "max_supported": 1,
24628                    }),
24629                ),
24630            ],
24631            "rust-workers".to_string(),
24632            DEFAULT_CODEC.to_string(),
24633            None,
24634        )
24635        .expect_err("new durable commands must remain strictly ordered");
24636        let Error::NonDeterministicReplay(failure) = descending else {
24637            panic!("expected typed replay failure");
24638        };
24639        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
24640        assert_eq!(failure.sequence, Some(2));
24641        assert_eq!(
24642            failure.expected.as_deref(),
24643            Some("workflow sequence greater than 3")
24644        );
24645        assert_eq!(failure.actual.as_deref(), Some("2"));
24646    }
24647
24648    #[test]
24649    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
24650        fn worker() -> Worker {
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.finish-after-gaps", |ctx, _input| async move {
24654                ctx.wait_signal("finish").await?;
24655                let marker: String =
24656                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
24657                assert_eq!(marker, "after-finish");
24658                Ok(json!("finished"))
24659            });
24660            worker
24661        }
24662
24663        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
24664            .expect("side-effect result");
24665        let task = workflow_task(
24666            "rust.finish-after-gaps",
24667            vec![
24668                history_event(
24669                    "SignalWaitOpened",
24670                    json!({"sequence": 1, "signal_name": "finish"}),
24671                ),
24672                history_event(
24673                    "SignalReceived",
24674                    json!({
24675                        "signal_id": "increment-3",
24676                        "signal_name": "increment",
24677                        "workflow_sequence": 2,
24678                        "payload_codec": DEFAULT_CODEC,
24679                        "arguments": fixture_envelope(json!([3])),
24680                    }),
24681                ),
24682                history_event(
24683                    "SignalReceived",
24684                    json!({
24685                        "signal_id": "increment-5",
24686                        "signal_name": "increment",
24687                        "workflow_sequence": 3,
24688                        "payload_codec": DEFAULT_CODEC,
24689                        "arguments": fixture_envelope(json!([5])),
24690                    }),
24691                ),
24692                history_event(
24693                    "SignalReceived",
24694                    json!({
24695                        "signal_id": "finish",
24696                        "signal_name": "finish",
24697                        "workflow_sequence": 4,
24698                        "payload_codec": DEFAULT_CODEC,
24699                        "arguments": fixture_envelope(json!([])),
24700                    }),
24701                ),
24702                history_event(
24703                    "SignalApplied",
24704                    json!({
24705                        "sequence": 1,
24706                        "signal_id": "finish",
24707                        "signal_name": "finish",
24708                        "payload_codec": DEFAULT_CODEC,
24709                        "value": fixture_envelope(json!([])),
24710                    }),
24711                ),
24712                history_event(
24713                    "SideEffectRecorded",
24714                    json!({"sequence": 5, "result": marker}),
24715                ),
24716            ],
24717            DEFAULT_CODEC,
24718        );
24719
24720        for _original_or_cold_worker in 0..2 {
24721            let commands = worker()
24722                .execute_workflow_task(task.clone())
24723                .expect("signal gaps preserve deterministic replay");
24724            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
24725            assert_eq!(commands[0]["type"], "complete_workflow");
24726            assert_eq!(
24727                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24728                json!("finished")
24729            );
24730        }
24731    }
24732
24733    #[test]
24734    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
24735        let ctx = workflow_context(Vec::new());
24736        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
24737        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24738        assert!(matches!(
24739            sleep.as_mut().poll(&mut task_context),
24740            Poll::Ready(Err(Error::TimerDurationOverflow))
24741        ));
24742        assert!(ctx.take_commands().expect("commands").is_empty());
24743    }
24744
24745    #[test]
24746    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
24747        let entries = AvroValue::Map(BTreeMap::from([
24748            ("text".to_string(), AvroValue::String("same".to_string())),
24749            (
24750                "nested".to_string(),
24751                AvroValue::Map(BTreeMap::from([
24752                    ("beta".to_string(), AvroValue::Long(2)),
24753                    ("alpha".to_string(), AvroValue::Long(1)),
24754                ])),
24755            ),
24756            ("long".to_string(), AvroValue::Long(7)),
24757            ("double".to_string(), AvroValue::Double(7.0)),
24758            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
24759        ]));
24760        let ctx = workflow_context(Vec::new());
24761        ctx.upsert_memo(entries.clone()).expect("valid memo update");
24762        let commands = ctx.take_commands().expect("commands");
24763
24764        assert_eq!(commands.len(), 1);
24765        assert_eq!(commands[0]["type"], "upsert_memo");
24766        let server_entries = json!({
24767            "codec": "avro",
24768            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
24769        });
24770        assert_eq!(
24771            commands[0]["entries"]
24772                .as_object()
24773                .expect("entries envelope")
24774                .keys()
24775                .collect::<Vec<_>>(),
24776            vec!["blob", "codec"]
24777        );
24778        assert_eq!(commands[0]["entries"], server_entries);
24779        let wire_entries =
24780            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
24781        assert_eq!(wire_entries, entries);
24782
24783        let history = vec![history_event(
24784            "MemoUpserted",
24785            json!({
24786                "sequence": 1,
24787                "entries": server_entries.clone(),
24788                "merged": server_entries,
24789            }),
24790        )];
24791        let replay = workflow_context(history.clone());
24792        replay
24793            .upsert_memo(entries.clone())
24794            .expect("matching replay identity");
24795        assert!(replay.take_commands().expect("replay commands").is_empty());
24796
24797        let changed_types = AvroValue::Map(BTreeMap::from([
24798            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
24799            (
24800                "nested".to_string(),
24801                AvroValue::Map(BTreeMap::from([
24802                    ("alpha".to_string(), AvroValue::Long(1)),
24803                    ("beta".to_string(), AvroValue::Long(2)),
24804                ])),
24805            ),
24806            ("long".to_string(), AvroValue::Double(7.0)),
24807            ("double".to_string(), AvroValue::Long(7)),
24808            ("binary".to_string(), AvroValue::String("same".to_string())),
24809        ]));
24810        let error = workflow_context(history)
24811            .upsert_memo(changed_types)
24812            .expect_err("memo replay identity must preserve Avro value types");
24813        assert!(matches!(
24814            error,
24815            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24816        ));
24817    }
24818
24819    #[test]
24820    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
24821        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
24822            .expect("memo envelope");
24823        let replay = workflow_context(vec![history_event(
24824            "MemoUpserted",
24825            json!({
24826                "sequence": 1,
24827                "entries": original.clone(),
24828                "merged": original
24829            }),
24830        )]);
24831        let error = replay
24832            .upsert_memo(json!({"stage": "changed"}))
24833            .expect_err("changed memo update must fail replay");
24834        assert!(matches!(
24835            error,
24836            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24837        ));
24838
24839        let invalid = workflow_context(Vec::new())
24840            .upsert_memo(
24841                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
24842            )
24843            .expect_err("oversized key");
24844        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
24845    }
24846
24847    #[test]
24848    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
24849        let negative_zero = AvroValue::Map(BTreeMap::from([(
24850            "reading".to_string(),
24851            AvroValue::Double(-0.0),
24852        )]));
24853        let negative_zero_envelope =
24854            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
24855        let history = vec![history_event(
24856            "MemoUpserted",
24857            json!({
24858                "sequence": 1,
24859                "entries": negative_zero_envelope.clone(),
24860                "merged": negative_zero_envelope,
24861            }),
24862        )];
24863
24864        workflow_context(history.clone())
24865            .upsert_memo(negative_zero)
24866            .expect("matching negative-zero history identity");
24867
24868        let error = workflow_context(history)
24869            .upsert_memo(AvroValue::Map(BTreeMap::from([(
24870                "reading".to_string(),
24871                AvroValue::Double(0.0),
24872            )])))
24873            .expect_err("positive zero must not consume negative-zero memo history");
24874        assert!(matches!(
24875            error,
24876            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24877        ));
24878    }
24879
24880    #[test]
24881    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
24882        let supported = json!({
24883            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
24884            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
24885        });
24886        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
24887        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
24888            "workflow_memo_updates": {"supported": false},
24889            "supported_workflow_task_commands": ["upsert_memo"]
24890        }))));
24891        assert!(commands_use_workflow_memo_updates(&[json!({
24892            "type": "upsert_memo",
24893            "entries": {"stage": "processing"}
24894        })]));
24895    }
24896
24897    #[test]
24898    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
24899        let client = Client::new("http://127.0.0.1:8080").expect("client");
24900        let mut worker = Worker::new(client, "rust-workers");
24901        worker.register_workflow("rust.timer", |ctx, _input| async move {
24902            ctx.sleep(Duration::from_secs(5)).await?;
24903            ctx.activity("after-timer", json!([])).await
24904        });
24905
24906        let task = |history_events| WorkflowTask {
24907            task_id: "wft-rust-timer-1".to_string(),
24908            workflow_command_id: None,
24909            workflow_id: Some("wf-rust-timer".to_string()),
24910            run_id: Some("run-rust-timer".to_string()),
24911            workflow_type: "rust.timer".to_string(),
24912            cancel_requested: false,
24913            payload_codec: DEFAULT_CODEC.to_string(),
24914            arguments: Some(
24915                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24916            ),
24917            history_events,
24918            total_history_events: None,
24919            history_size_bytes: None,
24920            continue_as_new_recommended: None,
24921            history_budget_pressure: None,
24922            next_history_page_token: None,
24923            workflow_task_attempt: 1,
24924            workflow_signal_id: None,
24925            signal_name: None,
24926            signal_arguments: None,
24927            workflow_update_id: None,
24928            update_name: None,
24929            lease_owner: Some("rust-worker".to_string()),
24930        };
24931
24932        let initial = worker
24933            .execute_workflow_task(task(Vec::new()))
24934            .expect("initial timer task");
24935        assert_eq!(
24936            initial,
24937            vec![json!({"type": "start_timer", "delay_seconds": 5})]
24938        );
24939
24940        let activity_result =
24941            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
24942        let replayed = worker
24943            .execute_workflow_task(task(vec![
24944                history_event(
24945                    "TimerScheduled",
24946                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24947                ),
24948                history_event(
24949                    "TimerFired",
24950                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24951                ),
24952                history_event(
24953                    "ActivityCompleted",
24954                    json!({
24955                        "sequence": 2,
24956                        "activity_type": "after-timer",
24957                        "payload_codec": DEFAULT_CODEC,
24958                        "result": activity_result,
24959                    }),
24960                ),
24961            ]))
24962            .expect("replayed workflow task");
24963        assert_eq!(replayed.len(), 1);
24964        assert_eq!(replayed[0]["type"], "complete_workflow");
24965        assert_eq!(
24966            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
24967            json!("done")
24968        );
24969    }
24970
24971    #[test]
24972    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
24973        let client = Client::new("http://127.0.0.1:8080").expect("client");
24974        let mut worker = Worker::new(client, "rust-workers");
24975        worker.register_workflow("rust.continue", |ctx, _input| async move {
24976            ctx.continue_as_new_with_options(
24977                ContinueAsNewOptions::new()
24978                    .workflow_type("rust.next")
24979                    .task_queue("next-workers"),
24980                json!([2, {"cursor": "next"}]),
24981            )
24982        });
24983
24984        let commands = worker
24985            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
24986            .expect("continue-as-new command");
24987
24988        assert_eq!(commands.len(), 1);
24989        assert_eq!(commands[0]["type"], "continue_as_new");
24990        assert_eq!(commands[0]["workflow_type"], "rust.next");
24991        assert_eq!(commands[0]["queue"], "next-workers");
24992        assert_eq!(
24993            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
24994                .expect("continue-as-new arguments"),
24995            json!([2, {"cursor": "next"}])
24996        );
24997    }
24998
24999    #[test]
25000    fn continue_as_new_preserves_typed_arguments() {
25001        let client = Client::new("http://127.0.0.1:8080").expect("client");
25002        let mut worker = Worker::new(client, "rust-workers");
25003        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
25004            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
25005            unreachable!("continue-as-new returns a control-flow error")
25006        });
25007
25008        let commands = worker
25009            .execute_workflow_task(workflow_task(
25010                "rust.typed-continue",
25011                Vec::new(),
25012                DEFAULT_CODEC,
25013            ))
25014            .expect("typed continue-as-new command");
25015
25016        assert_eq!(commands[0]["type"], "continue_as_new");
25017        assert_eq!(
25018            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
25019                .expect("typed continue arguments"),
25020            AvroValue::Array(vec![typed_fidelity_probe()])
25021        );
25022    }
25023
25024    #[test]
25025    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
25026        let client = Client::new("http://127.0.0.1:8080").expect("client");
25027        let mut worker = Worker::new(client, "rust-workers");
25028        worker.register_workflow("rust.continue", |ctx, _input| async move {
25029            ctx.continue_as_new(json!([2]))
25030        });
25031        let task = workflow_task(
25032            "rust.continue",
25033            vec![history_event(
25034                "WorkflowContinuedAsNew",
25035                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
25036            )],
25037            DEFAULT_CODEC,
25038        );
25039
25040        for _worker_restart_or_redelivery in 0..2 {
25041            let commands = worker
25042                .execute_workflow_task(task.clone())
25043                .expect("recorded transition replays");
25044            assert!(
25045                commands.is_empty(),
25046                "replay must not emit another successor"
25047            );
25048        }
25049    }
25050
25051    #[test]
25052    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
25053        let ctx = workflow_context(Vec::new());
25054        let error = ctx
25055            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
25056            .expect_err("blank queue must be rejected");
25057
25058        let Error::InvalidContinueAsNewOptions(error) = error else {
25059            panic!("expected typed continue-as-new validation error");
25060        };
25061        assert_eq!(error.field, "task_queue");
25062        assert!(ctx.take_commands().expect("commands").is_empty());
25063    }
25064
25065    #[test]
25066    fn workflow_context_exposes_server_history_budget() {
25067        let client = Client::new("http://127.0.0.1:8080").expect("client");
25068        let mut worker = Worker::new(client, "rust-workers");
25069        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
25070            let budget = ctx.history_budget()?;
25071            Ok(json!({
25072                "events": budget.event_count,
25073                "bytes": budget.size_bytes,
25074                "recommended": budget.continue_as_new_recommended,
25075                "pressure": budget.pressure,
25076            }))
25077        });
25078        let task: WorkflowTask = serde_json::from_value(json!({
25079            "task_id": "task-history-budget",
25080            "workflow_type": "rust.history-budget",
25081            "payload_codec": DEFAULT_CODEC,
25082            "history_events": [],
25083            "total_history_events": 480,
25084            "history_size_bytes": 1_048_576,
25085            "continue_as_new_recommended": true,
25086            "history_budget_pressure": "continue_as_new_recommended",
25087        }))
25088        .expect("published workflow task");
25089
25090        let commands = worker
25091            .execute_workflow_task(task)
25092            .expect("history-budget workflow");
25093        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
25094        assert_eq!(result["events"], 480);
25095        assert_eq!(result["bytes"], 1_048_576);
25096        assert_eq!(result["recommended"], true);
25097        assert_eq!(result["pressure"], "continue_as_new_recommended");
25098    }
25099
25100    #[test]
25101    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
25102        let client = Client::new("http://127.0.0.1:8080").expect("client");
25103        let mut worker = Worker::new(client, "rust-workers");
25104        worker.register_workflow("rust.failing", |_ctx, _input| async move {
25105            Err(Error::Codec("rust_conformance_failure".to_string()))
25106        });
25107        let task = WorkflowTask {
25108            task_id: "wft-rust-failing-1".to_string(),
25109            workflow_command_id: None,
25110            workflow_id: Some("wf-rust-failing".to_string()),
25111            run_id: Some("run-rust-failing".to_string()),
25112            workflow_type: "rust.failing".to_string(),
25113            cancel_requested: false,
25114            payload_codec: DEFAULT_CODEC.to_string(),
25115            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25116            history_events: Vec::new(),
25117            total_history_events: Some(0),
25118            history_size_bytes: None,
25119            continue_as_new_recommended: None,
25120            history_budget_pressure: None,
25121            next_history_page_token: None,
25122            workflow_task_attempt: 1,
25123            workflow_signal_id: None,
25124            signal_name: None,
25125            signal_arguments: None,
25126            workflow_update_id: None,
25127            update_name: None,
25128            lease_owner: Some("rust-worker".to_string()),
25129        };
25130
25131        let commands = worker
25132            .execute_workflow_task(task)
25133            .expect("handler failure becomes a workflow command");
25134
25135        assert_eq!(commands.len(), 1);
25136        assert_eq!(commands[0]["type"], "fail_workflow");
25137        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
25138        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
25139        assert_eq!(commands[0]["non_retryable"], false);
25140        assert_eq!(
25141            commands[0]["message"],
25142            "codec error: rust_conformance_failure"
25143        );
25144        assert_eq!(
25145            commands[0]["exception"]["message"],
25146            "codec error: rust_conformance_failure"
25147        );
25148    }
25149
25150    #[test]
25151    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
25152        let client = Client::new("http://127.0.0.1:8080").expect("client");
25153        let mut worker = Worker::new(client, "rust-workers");
25154        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
25155            let _: String = ctx.side_effect(|| "captured".to_string())?;
25156            Err(Error::WorkerLoop("application failure".to_string()))
25157        });
25158
25159        let commands = worker
25160            .execute_workflow_task(workflow_task(
25161                "rust.failing-after-side-effect",
25162                Vec::new(),
25163                DEFAULT_CODEC,
25164            ))
25165            .expect("ordinary failure remains a workflow decision");
25166
25167        assert_eq!(commands.len(), 2);
25168        assert_eq!(commands[0]["type"], "record_side_effect");
25169        assert_eq!(commands[1]["type"], "fail_workflow");
25170    }
25171
25172    #[test]
25173    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
25174        let client = Client::new("http://127.0.0.1:8080").expect("client");
25175        let mut worker = Worker::new(client, "rust-workers");
25176        worker.register_workflow("rust.redrive", |ctx, _input| async move {
25177            ctx.activity("greet", json!([])).await?;
25178            Ok(Value::Null)
25179        });
25180        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
25181            match ctx.activity("greet", json!([])).await {
25182                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
25183                result => result,
25184            }
25185        });
25186
25187        let failed = history_event(
25188            "ActivityFailed",
25189            json!({
25190                "sequence": 1,
25191                "activity_type": "greet",
25192                "activity_execution_id": "activity-1",
25193                "message": "failed"
25194            }),
25195        );
25196        let commands = worker
25197            .execute_workflow_task(workflow_task(
25198                "rust.redrive",
25199                vec![failed.clone()],
25200                DEFAULT_CODEC,
25201            ))
25202            .expect("recorded failure becomes a workflow command");
25203        assert_eq!(commands[0]["type"], "fail_workflow");
25204        assert_eq!(commands[0]["failed_step_sequence"], 1);
25205        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
25206
25207        let translated = worker
25208            .execute_workflow_task(workflow_task(
25209                "rust.redrive-translated",
25210                vec![failed],
25211                DEFAULT_CODEC,
25212            ))
25213            .expect("translated failure becomes a workflow command");
25214        assert_eq!(translated[0]["type"], "fail_workflow");
25215        assert!(translated[0].get("failed_step_sequence").is_none());
25216        assert!(translated[0].get("failed_activity_execution_id").is_none());
25217
25218        let without_identity = worker
25219            .execute_workflow_task(workflow_task(
25220                "rust.redrive",
25221                vec![history_event(
25222                    "ActivityFailed",
25223                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
25224                )],
25225                DEFAULT_CODEC,
25226            ))
25227            .expect("incomplete identity still fails the workflow");
25228        assert!(without_identity[0].get("failed_step_sequence").is_none());
25229
25230        let timed_out = worker
25231            .execute_workflow_task(workflow_task(
25232                "rust.redrive",
25233                vec![history_event(
25234                    "ActivityTimedOut",
25235                    json!({
25236                        "sequence": 1,
25237                        "activity_type": "greet",
25238                        "activity_execution_id": "activity-timeout",
25239                    }),
25240                )],
25241                DEFAULT_CODEC,
25242            ))
25243            .expect("timeout still fails the workflow");
25244        assert!(timed_out[0].get("failed_step_sequence").is_none());
25245    }
25246
25247    #[test]
25248    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
25249        let client = Client::new("http://127.0.0.1:8080").expect("client");
25250        let mut worker = Worker::new(client, "rust-workers");
25251        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
25252            let first = ctx.activity("first", json!([])).await?;
25253            let second = ctx.activity("second", json!([first.clone()])).await?;
25254            Ok(json!({"first": first, "second": second}))
25255        });
25256        let first = history_event(
25257            "ActivityCompleted",
25258            json!({
25259                "sequence": 1,
25260                "activity_type": "first",
25261                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
25262                "payload_codec": DEFAULT_CODEC,
25263                "reused_from_run_id": "failed-run",
25264                "reused_activity_execution_id": "original-first",
25265            }),
25266        );
25267
25268        let retry = worker
25269            .execute_workflow_task(workflow_task(
25270                "rust.redrive-successor",
25271                vec![first.clone()],
25272                DEFAULT_CODEC,
25273            ))
25274            .expect("reused result replays before failed step");
25275        assert_eq!(retry.len(), 1);
25276        assert_eq!(retry[0]["type"], "schedule_activity");
25277        assert_eq!(retry[0]["activity_type"], "second");
25278        assert_eq!(
25279            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
25280            json!(["recorded"]),
25281        );
25282
25283        let second = history_event(
25284            "ActivityCompleted",
25285            json!({
25286                "sequence": 2,
25287                "activity_type": "second",
25288                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
25289                "payload_codec": DEFAULT_CODEC,
25290            }),
25291        );
25292        let completed = worker
25293            .execute_workflow_task(workflow_task(
25294                "rust.redrive-successor",
25295                vec![first, second],
25296                DEFAULT_CODEC,
25297            ))
25298            .expect("retried step completes the successor");
25299        assert_eq!(completed.len(), 1);
25300        assert_eq!(completed[0]["type"], "complete_workflow");
25301        assert_eq!(
25302            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
25303            json!({"first": "recorded", "second": "retried"}),
25304        );
25305    }
25306
25307    #[test]
25308    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
25309        let client = Client::new("http://127.0.0.1:8080").expect("client");
25310        let mut worker = Worker::new(client, "rust-workers");
25311        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
25312            Err(Error::WorkerLoop("application failure".to_string()))
25313        });
25314        let result =
25315            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
25316
25317        let error = worker
25318            .execute_workflow_task(workflow_task(
25319                "rust.removed-side-effect",
25320                vec![history_event(
25321                    "SideEffectRecorded",
25322                    json!({"sequence": 1, "result": result}),
25323                )],
25324                DEFAULT_CODEC,
25325            ))
25326            .expect_err("removed committed history must not become fail_workflow");
25327
25328        let Error::NonDeterministicReplay(failure) = error else {
25329            panic!("expected typed replay failure");
25330        };
25331        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25332        assert_eq!(failure.sequence, Some(1));
25333        assert_eq!(failure.expected.as_deref(), Some("side effect"));
25334    }
25335
25336    #[test]
25337    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
25338        let client = Client::new("http://127.0.0.1:8080").expect("client");
25339        let mut worker = Worker::new(client, "rust-workers");
25340        worker.register_workflow(
25341            "rust.side-effect-before-marker-error",
25342            |ctx, _input| async move {
25343                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
25344                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
25345                ctx.get_version("restart-safe", 2, 2)?;
25346                Ok(Value::Null)
25347            },
25348        );
25349
25350        let error = worker
25351            .execute_workflow_task(workflow_task(
25352                "rust.side-effect-before-marker-error",
25353                vec![history_event(
25354                    "VersionMarkerRecorded",
25355                    json!({
25356                        "sequence": 1,
25357                        "change_id": "restart-safe",
25358                        "version": 1,
25359                        "min_supported": 1,
25360                        "max_supported": 1,
25361                    }),
25362                )],
25363                DEFAULT_CODEC,
25364            ))
25365            .expect_err("replay error must return no queued workflow commands");
25366
25367        let Error::NonDeterministicReplay(failure) = error else {
25368            panic!("expected typed replay failure");
25369        };
25370        assert_eq!(failure.reason, "version_marker_incompatible_range");
25371        assert_eq!(failure.sequence, Some(1));
25372    }
25373
25374    #[test]
25375    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
25376        let client = Client::new("http://127.0.0.1:8080").expect("client");
25377        let mut worker = Worker::new(client, "rust-workers");
25378        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
25379            ctx.sleep(Duration::from_secs(5)).await?;
25380            Ok(json!({"status": "timer fired"}))
25381        });
25382
25383        let task = WorkflowTask {
25384            task_id: "wft-rust-timer-pending".to_string(),
25385            workflow_command_id: None,
25386            workflow_id: Some("wf-rust-timer".to_string()),
25387            run_id: Some("run-rust-timer".to_string()),
25388            workflow_type: "rust.timer.pending".to_string(),
25389            cancel_requested: false,
25390            payload_codec: DEFAULT_CODEC.to_string(),
25391            arguments: Some(
25392                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25393            ),
25394            history_events: vec![history_event(
25395                "TimerScheduled",
25396                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25397            )],
25398            total_history_events: Some(1),
25399            history_size_bytes: None,
25400            continue_as_new_recommended: None,
25401            history_budget_pressure: None,
25402            next_history_page_token: None,
25403            workflow_task_attempt: 1,
25404            workflow_signal_id: None,
25405            signal_name: None,
25406            signal_arguments: None,
25407            workflow_update_id: None,
25408            update_name: None,
25409            lease_owner: Some("rust-worker".to_string()),
25410        };
25411
25412        for _redelivery_or_restart in 0..2 {
25413            let commands = worker
25414                .execute_workflow_task(task.clone())
25415                .expect("recorded timer remains pending");
25416            assert!(
25417                commands.is_empty(),
25418                "recorded timer must not be rescheduled"
25419            );
25420        }
25421    }
25422
25423    #[test]
25424    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
25425        let client = Client::new("http://127.0.0.1:8080").expect("client");
25426        let mut worker = Worker::new(client, "rust-workers");
25427        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
25428            Ok(json!({"status": "completed"}))
25429        });
25430        let task = WorkflowTask {
25431            task_id: "wft-rust-timer-removed".to_string(),
25432            workflow_command_id: None,
25433            workflow_id: Some("wf-rust-timer".to_string()),
25434            run_id: Some("run-rust-timer".to_string()),
25435            workflow_type: "rust.timer.removed".to_string(),
25436            cancel_requested: false,
25437            payload_codec: DEFAULT_CODEC.to_string(),
25438            arguments: Some(
25439                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25440            ),
25441            history_events: vec![
25442                history_event(
25443                    "TimerScheduled",
25444                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25445                ),
25446                history_event(
25447                    "TimerFired",
25448                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25449                ),
25450            ],
25451            total_history_events: Some(2),
25452            history_size_bytes: None,
25453            continue_as_new_recommended: None,
25454            history_budget_pressure: None,
25455            next_history_page_token: None,
25456            workflow_task_attempt: 1,
25457            workflow_signal_id: None,
25458            signal_name: None,
25459            signal_arguments: None,
25460            workflow_update_id: None,
25461            update_name: None,
25462            lease_owner: Some("rust-worker".to_string()),
25463        };
25464
25465        let Error::NonDeterministicReplay(failure) = worker
25466            .execute_workflow_task(task)
25467            .expect_err("removed timer must fail replay")
25468        else {
25469            panic!("expected typed replay failure");
25470        };
25471        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25472        assert_eq!(failure.sequence, Some(1));
25473    }
25474
25475    #[test]
25476    fn workflow_context_emits_explicit_child_workflow_contract() {
25477        let ctx = WorkflowContext {
25478            cancellation_scope_id: "root".into(),
25479            state: Arc::new(Mutex::new(
25480                WorkflowState::new_with_identity(
25481                    Vec::new(),
25482                    Some("wf-parent".to_string()),
25483                    Some("run-parent".to_string()),
25484                    "parent-workers".to_string(),
25485                    DEFAULT_CODEC.to_string(),
25486                    None,
25487                )
25488                .expect("workflow state"),
25489            )),
25490        };
25491        let options = ChildWorkflowOptions::new("python-workers")
25492            .parent_close_policy(ParentClosePolicy::RequestCancel)
25493            .retry_policy(ChildWorkflowRetryPolicy {
25494                max_attempts: Some(3),
25495                backoff_seconds: vec![1, 5],
25496                non_retryable_error_types: vec!["ValidationError".to_string()],
25497            })
25498            .execution_timeout_seconds(600)
25499            .run_timeout_seconds(120);
25500        let mut call = Box::pin(ctx.start_child_workflow(
25501            "python.fulfil-order",
25502            options,
25503            json!([{"order_id": "order-42"}]),
25504        ));
25505        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25506
25507        assert!(matches!(
25508            call.as_mut().poll(&mut task_context),
25509            Poll::Pending
25510        ));
25511        let commands = ctx.take_commands().expect("commands");
25512        assert_eq!(commands.len(), 1);
25513        let command = &commands[0];
25514        assert_eq!(command["type"], "start_child_workflow");
25515        assert_eq!(command["workflow_type"], "python.fulfil-order");
25516        assert_eq!(command["queue"], "python-workers");
25517        assert_eq!(command["parent_close_policy"], "request_cancel");
25518        assert_eq!(command["retry_policy"]["max_attempts"], 3);
25519        assert_eq!(command["execution_timeout_seconds"], 600);
25520        assert_eq!(command["run_timeout_seconds"], 120);
25521        assert_eq!(
25522            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
25523            json!([{"order_id": "order-42"}])
25524        );
25525    }
25526
25527    fn child_parent_worker() -> Worker {
25528        let client = Client::new("http://127.0.0.1:8080").expect("client");
25529        let mut worker = Worker::new(client, "rust-parent-workers");
25530        worker.register_workflow("rust.parent", |ctx, _input| async move {
25531            let child = ctx
25532                .start_child_workflow(
25533                    "python.child",
25534                    ChildWorkflowOptions::new("python-child-workers")
25535                        .parent_close_policy(ParentClosePolicy::Terminate),
25536                    json!([{"codec_probe": [1, true, "rust"]}]),
25537                )
25538                .await?;
25539            Ok(json!({
25540                "parent_workflow_id": child.parent.workflow_id,
25541                "parent_run_id": child.parent.run_id,
25542                "child_workflow_id": child.child.workflow_id,
25543                "child_run_id": child.child.run_id,
25544                "child_workflow_type": child.child_workflow_type,
25545                "result": child.result,
25546            }))
25547        });
25548        worker
25549    }
25550
25551    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
25552        WorkflowTask {
25553            task_id: "wft-child-parent".to_string(),
25554            workflow_command_id: None,
25555            workflow_id: Some("wf-parent".to_string()),
25556            run_id: Some("run-parent".to_string()),
25557            workflow_type: "rust.parent".to_string(),
25558            cancel_requested: false,
25559            payload_codec: DEFAULT_CODEC.to_string(),
25560            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25561            history_events: vec![
25562                HistoryEvent {
25563                    event_type: "ChildWorkflowScheduled".to_string(),
25564                    payload: json!({
25565                        "sequence": 1,
25566                        "child_call_id": "call-child",
25567                        "child_workflow_instance_id": "wf-child",
25568                        "child_workflow_run_id": "run-child",
25569                        "child_workflow_type": "python.child",
25570                        "parent_close_policy": "terminate",
25571                    }),
25572                    raw: HashMap::new(),
25573                },
25574                HistoryEvent {
25575                    event_type: event_type.to_string(),
25576                    payload,
25577                    raw: HashMap::new(),
25578                },
25579            ],
25580            total_history_events: Some(2),
25581            history_size_bytes: None,
25582            continue_as_new_recommended: None,
25583            history_budget_pressure: None,
25584            next_history_page_token: None,
25585            workflow_task_attempt: 1,
25586            workflow_signal_id: None,
25587            signal_name: None,
25588            signal_arguments: None,
25589            workflow_update_id: None,
25590            update_name: None,
25591            lease_owner: Some("rust-worker".to_string()),
25592        }
25593    }
25594
25595    #[test]
25596    fn committed_child_result_replays_without_starting_a_duplicate() {
25597        let worker = child_parent_worker();
25598        let task = child_parent_task(
25599            "ChildRunCompleted",
25600            json!({
25601                "sequence": 1,
25602                "child_call_id": "call-child",
25603                "child_workflow_instance_id": "wf-child",
25604                "child_workflow_run_id": "run-child",
25605                "child_workflow_type": "python.child",
25606                "payload_codec": DEFAULT_CODEC,
25607                "result": fixture_envelope(json!({"from":"python","ok":true})),
25608            }),
25609        );
25610
25611        for _restart in 0..2 {
25612            let commands = worker
25613                .execute_workflow_task(task.clone())
25614                .expect("replayed parent task");
25615            assert_eq!(commands.len(), 1);
25616            assert_eq!(commands[0]["type"], "complete_workflow");
25617            assert!(!commands
25618                .iter()
25619                .any(|command| command["type"] == "start_child_workflow"));
25620            let output =
25621                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25622            assert_eq!(output["parent_workflow_id"], "wf-parent");
25623            assert_eq!(output["parent_run_id"], "run-parent");
25624            assert_eq!(output["child_workflow_id"], "wf-child");
25625            assert_eq!(output["child_run_id"], "run-child");
25626            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
25627        }
25628    }
25629
25630    #[test]
25631    fn typed_child_arguments_and_results_survive_replay() {
25632        let client = Client::new("http://127.0.0.1:8080").expect("client");
25633        let mut worker = Worker::new(client, "rust-parent-workers");
25634        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
25635            let child = ctx
25636                .start_child_workflow_avro_value(
25637                    "python.typed-child",
25638                    ChildWorkflowOptions::new("python-workers"),
25639                    AvroValue::Array(vec![typed_fidelity_probe()]),
25640                )
25641                .await?;
25642            Ok(child.result)
25643        });
25644
25645        let initial = worker
25646            .execute_workflow_task(workflow_task(
25647                "rust.typed-parent",
25648                Vec::new(),
25649                DEFAULT_CODEC,
25650            ))
25651            .expect("typed child start");
25652        assert_eq!(initial[0]["type"], "start_child_workflow");
25653        assert_eq!(
25654            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
25655                .expect("typed child arguments"),
25656            AvroValue::Array(vec![typed_fidelity_probe()])
25657        );
25658
25659        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
25660            .expect("typed child result");
25661        let task = workflow_task(
25662            "rust.typed-parent",
25663            vec![
25664                history_event(
25665                    "ChildWorkflowScheduled",
25666                    json!({
25667                        "sequence": 1,
25668                        "child_call_id": "call-typed",
25669                        "child_workflow_instance_id": "wf-child",
25670                        "child_workflow_run_id": "run-child",
25671                        "child_workflow_type": "python.typed-child",
25672                    }),
25673                ),
25674                history_event(
25675                    "ChildRunCompleted",
25676                    json!({
25677                        "sequence": 1,
25678                        "child_call_id": "call-typed",
25679                        "child_workflow_instance_id": "wf-child",
25680                        "child_workflow_run_id": "run-child",
25681                        "child_workflow_type": "python.typed-child",
25682                        "payload_codec": DEFAULT_CODEC,
25683                        "result": result,
25684                    }),
25685                ),
25686            ],
25687            DEFAULT_CODEC,
25688        );
25689
25690        let commands = worker
25691            .execute_workflow_task(task)
25692            .expect("typed child replay");
25693        assert_eq!(commands[0]["type"], "complete_workflow");
25694        assert_eq!(
25695            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
25696                .expect("typed parent result"),
25697            typed_fidelity_probe()
25698        );
25699    }
25700
25701    #[test]
25702    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
25703        let worker = child_parent_worker();
25704        let mut task = child_parent_task("unused", Value::Null);
25705        task.history_events.truncate(1);
25706        task.total_history_events = Some(1);
25707
25708        for _redelivery_or_restart in 0..2 {
25709            let commands = worker
25710                .execute_workflow_task(task.clone())
25711                .expect("recorded child remains pending");
25712            assert!(
25713                commands.is_empty(),
25714                "recorded pending child must not be started again"
25715            );
25716        }
25717    }
25718
25719    #[test]
25720    fn child_cancellation_becomes_stable_parent_failure_command() {
25721        let worker = child_parent_worker();
25722        let task = child_parent_task(
25723            "ChildRunCancelled",
25724            json!({
25725                "sequence": 1,
25726                "child_workflow_instance_id": "wf-child",
25727                "child_workflow_run_id": "run-child",
25728                "child_workflow_type": "python.child",
25729                "failure_id": "failure-child",
25730                "failure_category": "cancelled",
25731                "message": "cancelled by parent-close policy",
25732            }),
25733        );
25734
25735        let commands = worker
25736            .execute_workflow_task(task)
25737            .expect("parent settlement");
25738        assert_eq!(commands.len(), 1);
25739        assert_eq!(commands[0]["type"], "fail_workflow");
25740        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
25741        assert_eq!(
25742            commands[0]["exception"]["properties"]["reason"],
25743            "cancelled"
25744        );
25745        assert_eq!(
25746            commands[0]["exception"]["properties"]["child_workflow_run_id"],
25747            "run-child"
25748        );
25749    }
25750
25751    #[test]
25752    fn workflow_can_handle_typed_child_failure() {
25753        let client = Client::new("http://127.0.0.1:8080").expect("client");
25754        let mut worker = Worker::new(client, "rust-parent-workers");
25755        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
25756            match ctx
25757                .start_child_workflow(
25758                    "python.child",
25759                    ChildWorkflowOptions::new("python-child-workers"),
25760                    json!([]),
25761                )
25762                .await
25763            {
25764                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
25765                    "reason": failure.reason,
25766                    "failure_id": failure.failure_id,
25767                    "exception_class": failure.exception_class,
25768                    "child_run_id": failure.child_workflow_run_id,
25769                })),
25770                Err(error) => Err(error),
25771                Ok(_) => Err(Error::WorkerLoop(
25772                    "child unexpectedly succeeded".to_string(),
25773                )),
25774            }
25775        });
25776        let mut task = child_parent_task(
25777            "ChildRunFailed",
25778            json!({
25779                "sequence": 1,
25780                "child_workflow_instance_id": "wf-child",
25781                "child_workflow_run_id": "run-child",
25782                "child_workflow_type": "python.child",
25783                "failure_id": "failure-child",
25784                "failure_category": "child_workflow",
25785                "message": "payment rejected",
25786                "exception": {
25787                    "type": "PaymentRejected",
25788                    "class": "payments.PaymentRejected",
25789                    "message": "payment rejected"
25790                }
25791            }),
25792        );
25793        task.workflow_type = "rust.handled-parent".to_string();
25794        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
25795
25796        let commands = worker.execute_workflow_task(task).expect("handled failure");
25797        assert_eq!(commands[0]["type"], "complete_workflow");
25798        let output =
25799            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25800        assert_eq!(output["reason"], "child_workflow");
25801        assert_eq!(output["failure_id"], "failure-child");
25802        assert_eq!(output["exception_class"], "payments.PaymentRejected");
25803        assert_eq!(output["child_run_id"], "run-child");
25804    }
25805
25806    #[test]
25807    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
25808        let client = Client::new("http://127.0.0.1:8080").expect("client");
25809        let mut worker = Worker::new(client, "rust-workers");
25810
25811        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
25812            let signal = ctx.wait_signal("start").await?;
25813            let name = signal
25814                .first()
25815                .and_then(|value| value.as_str())
25816                .unwrap_or("world");
25817            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
25818            Ok(json!({
25819                "greeting": greeting,
25820                "language": "rust"
25821            }))
25822        });
25823
25824        let signal_arguments =
25825            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
25826        let task = WorkflowTask {
25827            task_id: "wft-rust-signal-1".to_string(),
25828            workflow_command_id: None,
25829            workflow_id: Some("wf-rust-hello".to_string()),
25830            run_id: Some("run-rust-hello".to_string()),
25831            workflow_type: "rust.hello_workflow".to_string(),
25832            cancel_requested: false,
25833            payload_codec: DEFAULT_CODEC.to_string(),
25834            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25835            history_events: vec![HistoryEvent {
25836                event_type: "SignalReceived".to_string(),
25837                payload: json!({
25838                    "signal_id": "sig-rust-1",
25839                    "signal_name": "start"
25840                }),
25841                raw: HashMap::new(),
25842            }],
25843            total_history_events: Some(1),
25844            history_size_bytes: None,
25845            continue_as_new_recommended: None,
25846            history_budget_pressure: None,
25847            next_history_page_token: None,
25848            workflow_task_attempt: 1,
25849            workflow_signal_id: Some("sig-rust-1".to_string()),
25850            signal_name: Some("start".to_string()),
25851            signal_arguments: Some(signal_arguments),
25852            workflow_update_id: None,
25853            update_name: None,
25854            lease_owner: Some("rust-worker".to_string()),
25855        };
25856
25857        let commands = worker.execute_workflow_task(task).expect("workflow task");
25858
25859        assert_eq!(commands.len(), 1);
25860        assert_eq!(commands[0]["type"], "schedule_activity");
25861        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
25862        assert_eq!(
25863            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
25864            json!(["Rust"])
25865        );
25866    }
25867
25868    #[test]
25869    fn workflow_task_appends_paginated_history_events() {
25870        let mut task = WorkflowTask {
25871            task_id: "wft-rust-pages-1".to_string(),
25872            workflow_command_id: None,
25873            workflow_id: Some("wf-rust-pages".to_string()),
25874            run_id: Some("run-rust-pages".to_string()),
25875            workflow_type: "rust.hello_workflow".to_string(),
25876            cancel_requested: false,
25877            payload_codec: DEFAULT_CODEC.to_string(),
25878            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25879            history_events: vec![HistoryEvent {
25880                event_type: "WorkflowStarted".to_string(),
25881                payload: json!({}),
25882                raw: HashMap::new(),
25883            }],
25884            total_history_events: Some(3),
25885            history_size_bytes: None,
25886            continue_as_new_recommended: None,
25887            history_budget_pressure: None,
25888            next_history_page_token: Some("MQ==".to_string()),
25889            workflow_task_attempt: 1,
25890            workflow_signal_id: None,
25891            signal_name: None,
25892            signal_arguments: None,
25893            workflow_update_id: None,
25894            update_name: None,
25895            lease_owner: Some("rust-worker".to_string()),
25896        };
25897
25898        task.append_history_page(WorkflowTaskHistoryPage {
25899            history_events: vec![
25900                HistoryEvent {
25901                    event_type: "SignalReceived".to_string(),
25902                    payload: json!({
25903                        "signal_id": "sig-rust-1",
25904                        "signal_name": "start",
25905                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
25906                            .expect("signal arguments")
25907                    }),
25908                    raw: HashMap::new(),
25909                },
25910                HistoryEvent {
25911                    event_type: "MarkerRecorded".to_string(),
25912                    payload: json!({"sequence": 3}),
25913                    raw: HashMap::new(),
25914                },
25915            ],
25916            total_history_events: Some(3),
25917            next_history_page_token: None,
25918        });
25919
25920        assert_eq!(task.history_events.len(), 3);
25921        assert_eq!(task.total_history_events, Some(3));
25922        assert_eq!(task.next_history_page_token, None);
25923
25924        let signal = task
25925            .history_events
25926            .iter()
25927            .find(|event| event.event_type == "SignalReceived")
25928            .expect("signal event");
25929        assert_eq!(
25930            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
25931            vec![AvroValue::String("Rust".to_string())]
25932        );
25933    }
25934
25935    #[tokio::test]
25936    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
25937        let client = Client::new("http://127.0.0.1:8080").expect("client");
25938        let mut worker = Worker::new(client, "rust-workers");
25939        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25940        worker.register_query("counter", "current", |ctx, _args| async move {
25941            let mut count = 0_i64;
25942            for signal in ctx.signal_events() {
25943                let value = signal
25944                    .arguments
25945                    .first()
25946                    .and_then(Value::as_i64)
25947                    .unwrap_or_default();
25948                match signal.name.as_str() {
25949                    "increment" => count += value,
25950                    "set" => count = value,
25951                    _ => {}
25952                }
25953            }
25954            Ok(json!(count))
25955        });
25956
25957        let task = QueryTask {
25958            query_task_id: "query-rust-counter".to_string(),
25959            query_task_attempt: 1,
25960            lease_owner: Some("rust-worker".to_string()),
25961            workflow_id: Some("counter-1".to_string()),
25962            run_id: Some("run-counter-1".to_string()),
25963            workflow_type: "counter".to_string(),
25964            query_name: "current".to_string(),
25965            payload_codec: DEFAULT_CODEC.to_string(),
25966            workflow_arguments: Some(
25967                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25968            ),
25969            query_arguments: Some(
25970                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
25971            ),
25972            history_events: vec![
25973                HistoryEvent {
25974                    event_type: "SignalReceived".to_string(),
25975                    payload: json!({
25976                        "signal_id": "php-signal-1",
25977                        "signal_name": "increment",
25978                        "workflow_sequence": 1,
25979                        "payload_codec": DEFAULT_CODEC,
25980                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
25981                    }),
25982                    raw: HashMap::new(),
25983                },
25984                HistoryEvent {
25985                    event_type: "SignalReceived".to_string(),
25986                    payload: json!({
25987                        "signal_id": "python-signal-2",
25988                        "signal_name": "increment",
25989                        "workflow_sequence": 2,
25990                        "payload_codec": DEFAULT_CODEC,
25991                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
25992                    }),
25993                    raw: HashMap::new(),
25994                },
25995                HistoryEvent {
25996                    event_type: "SignalReceived".to_string(),
25997                    payload: json!({
25998                        "signal_id": "rust-signal-3",
25999                        "signal_name": "set",
26000                        "workflow_sequence": 3,
26001                        "payload_codec": DEFAULT_CODEC,
26002                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
26003                    }),
26004                    raw: HashMap::new(),
26005                },
26006            ],
26007            history_export: None,
26008            run_status: Some("completed".to_string()),
26009        };
26010
26011        let result = worker.execute_query_task(task).await.expect("query result");
26012        assert_eq!(result.into_json().expect("query projection"), json!(0));
26013    }
26014
26015    #[tokio::test]
26016    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
26017        let worker = replay_counter_worker();
26018        let running_history = json!([
26019            {
26020                "type": "ActivityCompleted",
26021                "payload": {
26022                    "sequence": 1,
26023                    "activity_type": "load-counter",
26024                    "payload_codec": DEFAULT_CODEC,
26025                    "result": fixture_envelope(json!("loaded"))
26026                }
26027            },
26028            {
26029                "type": "SignalWaitOpened",
26030                "payload": {
26031                    "sequence": 3,
26032                    "signal_name": "increment"
26033                }
26034            },
26035            {
26036                "type": "SignalReceived",
26037                "payload": {
26038                    "signal_id": "signal-3",
26039                    "signal_name": "increment",
26040                    "workflow_sequence": 2,
26041                    "payload_codec": DEFAULT_CODEC,
26042                    "arguments": fixture_envelope(json!([3]))
26043                }
26044            },
26045            {
26046                "type": "SignalApplied",
26047                "payload": {
26048                    "sequence": 3,
26049                    "signal_id": "signal-3",
26050                    "signal_name": "increment",
26051                    "payload_codec": DEFAULT_CODEC,
26052                    "value": fixture_envelope(json!([3]))
26053                }
26054            }
26055        ]);
26056
26057        let running = worker
26058            .execute_query_task(replay_counter_query(
26059                "current",
26060                running_history.clone(),
26061                "running",
26062            ))
26063            .await
26064            .expect("running replay query");
26065        assert_eq!(
26066            running.clone().into_json().expect("query projection"),
26067            json!({"loaded": "loaded", "count": 3, "finished": false})
26068        );
26069
26070        let detached = worker
26071            .execute_query_task(replay_counter_query(
26072                "detached-mutation",
26073                running_history.clone(),
26074                "running",
26075            ))
26076            .await
26077            .expect("query mutates only its detached state clone");
26078        assert_eq!(detached.into_json().expect("query projection"), json!(999));
26079        let failed = worker
26080            .execute_query_task(replay_counter_query(
26081                "failed-mutation",
26082                running_history.clone(),
26083                "running",
26084            ))
26085            .await
26086            .expect_err("failed query");
26087        assert_eq!(failed.reason, "query_rejected");
26088        let unchanged = worker
26089            .execute_query_task(replay_counter_query("current", running_history, "running"))
26090            .await
26091            .expect("later query reconstructs unchanged state");
26092        assert_eq!(unchanged, running);
26093
26094        let restarted_worker = replay_counter_worker();
26095        let empty_arguments = fixture_envelope(json!([]));
26096        let loaded_result = fixture_envelope(json!("loaded"));
26097        let signal_three = fixture_blob(json!([3]));
26098        let signal_five = fixture_blob(json!([5]));
26099        let restarted_task: QueryTask = serde_json::from_value(json!({
26100            "query_task_id": "query-after-restart",
26101            "workflow_id": "counter-1",
26102            "run_id": "run-counter-1",
26103            "workflow_type": "replay-counter",
26104            "query_name": "current",
26105            "payload_codec": DEFAULT_CODEC,
26106            "workflow_arguments": empty_arguments.clone(),
26107            "query_arguments": empty_arguments,
26108            "history_events": [],
26109            "history_export": {
26110                "payloads": {"codec": DEFAULT_CODEC},
26111                "history_events": [
26112                    {
26113                        "type": "ActivityCompleted",
26114                        "payload": {
26115                            "sequence": 1,
26116                            "activity_type": "load-counter",
26117                            "payload_codec": DEFAULT_CODEC,
26118                            "result": null
26119                        }
26120                    },
26121                    {
26122                        "type": "SignalWaitOpened",
26123                        "payload": {
26124                            "sequence": 3,
26125                            "signal_name": "increment"
26126                        }
26127                    },
26128                    {
26129                        "type": "SignalReceived",
26130                        "payload": {
26131                            "signal_id": "signal-3",
26132                            "signal_name": "increment",
26133                            "workflow_sequence": 2
26134                        }
26135                    },
26136                    {
26137                        "type": "SignalApplied",
26138                        "payload": {
26139                            "sequence": 3,
26140                            "signal_id": "signal-3",
26141                            "signal_name": "increment"
26142                        }
26143                    },
26144                    {
26145                        "type": "SignalWaitOpened",
26146                        "payload": {
26147                            "sequence": 5,
26148                            "signal_name": "increment"
26149                        }
26150                    },
26151                    {
26152                        "type": "SignalReceived",
26153                        "payload": {
26154                            "signal_id": "signal-5",
26155                            "signal_name": "increment",
26156                            "workflow_sequence": 4
26157                        }
26158                    },
26159                    {
26160                        "type": "SignalApplied",
26161                        "payload": {
26162                            "sequence": 5,
26163                            "signal_id": "signal-5",
26164                            "signal_name": "increment"
26165                        }
26166                    }
26167                ],
26168                "activities": [{
26169                    "sequence": 1,
26170                    "activity_type": "load-counter",
26171                    "payload_codec": DEFAULT_CODEC,
26172                    "result": loaded_result
26173                }],
26174                "signals": [
26175                    {
26176                        "id": "signal-3",
26177                        "name": "increment",
26178                        "workflow_sequence": 2,
26179                        "payload_codec": DEFAULT_CODEC,
26180                        "arguments": signal_three
26181                    },
26182                    {
26183                        "id": "signal-5",
26184                        "name": "increment",
26185                        "workflow_sequence": 4,
26186                        "payload_codec": DEFAULT_CODEC,
26187                        "arguments": signal_five
26188                    }
26189                ]
26190            },
26191            "run_status": "completed"
26192        }))
26193        .expect("cold replay query task");
26194        let completed = restarted_worker
26195            .execute_query_task(restarted_task)
26196            .await
26197            .expect("completed cold replay query");
26198        assert_eq!(
26199            completed.into_json().expect("query projection"),
26200            json!({"loaded": "loaded", "count": 8, "finished": true})
26201        );
26202    }
26203
26204    #[tokio::test]
26205    async fn replayed_query_replay_failures_are_machine_readable() {
26206        let worker = replay_counter_worker();
26207        let task = replay_counter_query(
26208            "current",
26209            json!([{
26210                "type": "ActivityCompleted",
26211                "payload": {
26212                    "sequence": 1,
26213                    "payload_codec": DEFAULT_CODEC,
26214                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
26215                }
26216            }]),
26217            "running",
26218        );
26219        let failure = worker
26220            .execute_query_task(task)
26221            .await
26222            .expect_err("invalid replay history payload");
26223        assert_eq!(failure.reason, "query_payload_decode_failed");
26224        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
26225        assert!(failure.message.contains("invalid_payload_framing"));
26226    }
26227
26228    #[tokio::test]
26229    async fn query_task_restores_compact_history_from_export() {
26230        let client = Client::new("http://127.0.0.1:8080").expect("client");
26231        let mut worker = Worker::new(client, "rust-workers");
26232        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26233        worker.register_query("counter", "current", |ctx, _args| async move {
26234            Ok(json!(ctx.signals("increment")[0][0]))
26235        });
26236        let empty_arguments = fixture_envelope(json!([]));
26237        let exported_signal = fixture_blob(json!([9]));
26238        let task: QueryTask = serde_json::from_value(json!({
26239            "query_task_id": "query-export",
26240            "workflow_type": "counter",
26241            "query_name": "current",
26242            "payload_codec": DEFAULT_CODEC,
26243            "workflow_arguments": empty_arguments.clone(),
26244            "query_arguments": empty_arguments,
26245            "history_events": [],
26246            "history_export": {
26247                "payloads": {"codec": DEFAULT_CODEC},
26248                "history_events": [{
26249                    "type": "SignalReceived",
26250                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
26251                }],
26252                "signals": [{
26253                    "id": "signal-export",
26254                    "name": "increment",
26255                    "status": "applied",
26256                    "workflow_sequence": 1,
26257                    "payload_codec": DEFAULT_CODEC,
26258                    "arguments": exported_signal
26259                }]
26260            }
26261        }))
26262        .expect("query task");
26263
26264        let result = worker.execute_query_task(task).await.expect("query result");
26265        assert_eq!(result.into_json().expect("query projection"), json!(9));
26266    }
26267
26268    #[tokio::test]
26269    async fn query_task_failures_have_stable_reasons() {
26270        let client = Client::new("http://127.0.0.1:8080").expect("client");
26271        let mut worker = Worker::new(client, "rust-workers");
26272        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26273        worker.register_query(
26274            "counter",
26275            "current",
26276            |_ctx, _args| async move { Ok(json!(0)) },
26277        );
26278
26279        let base_task = QueryTask {
26280            query_task_id: "query-errors".to_string(),
26281            query_task_attempt: 1,
26282            lease_owner: None,
26283            workflow_id: Some("counter-errors".to_string()),
26284            run_id: Some("run-errors".to_string()),
26285            workflow_type: "counter".to_string(),
26286            query_name: "missing".to_string(),
26287            payload_codec: DEFAULT_CODEC.to_string(),
26288            workflow_arguments: Some(fixture_envelope(json!([]))),
26289            query_arguments: Some(fixture_envelope(json!([]))),
26290            history_events: Vec::new(),
26291            history_export: None,
26292            run_status: Some("running".to_string()),
26293        };
26294
26295        let unknown = worker
26296            .execute_query_task(base_task.clone())
26297            .await
26298            .expect_err("unknown query");
26299        assert_eq!(unknown.reason, "rejected_unknown_query");
26300
26301        let mut malformed = base_task;
26302        malformed.query_name = "current".to_string();
26303        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
26304        let malformed = worker
26305            .execute_query_task(malformed)
26306            .await
26307            .expect_err("malformed payload");
26308        assert_eq!(malformed.reason, "query_payload_decode_failed");
26309
26310        let client = Client::new("http://127.0.0.1:8080").expect("client");
26311        let mut unavailable_worker = Worker::new(client, "rust-workers");
26312        unavailable_worker
26313            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26314        let empty_arguments = fixture_envelope(json!([]));
26315        let unavailable_task: QueryTask = serde_json::from_value(json!({
26316            "query_task_id": "query-unavailable",
26317            "workflow_type": "counter",
26318            "query_name": "current",
26319            "payload_codec": DEFAULT_CODEC,
26320            "workflow_arguments": empty_arguments.clone(),
26321            "query_arguments": empty_arguments
26322        }))
26323        .expect("query task");
26324        let unavailable = unavailable_worker
26325            .execute_query_task(unavailable_task)
26326            .await
26327            .expect_err("query handler unavailable");
26328        assert_eq!(unavailable.reason, "query_handler_unavailable");
26329    }
26330
26331    #[tokio::test]
26332    async fn client_query_decodes_result_and_typed_failure() {
26333        let server = MockWorkerServer::start();
26334        let client = Client::builder(server.base_url())
26335            .timeout(Duration::from_secs(2))
26336            .build()
26337            .expect("client");
26338
26339        let result = client
26340            .query_workflow("counter-1", "current", json!([]))
26341            .await
26342            .expect("query result");
26343        assert_eq!(result, json!({"count": 8}));
26344
26345        let error = client
26346            .query_workflow("counter-1", "missing", json!([]))
26347            .await
26348            .expect_err("unknown query");
26349        let Error::QueryFailed(failure) = error else {
26350            panic!("expected typed query failure");
26351        };
26352        assert_eq!(failure.status, 404);
26353        assert_eq!(failure.reason, "rejected_unknown_query");
26354    }
26355
26356    #[tokio::test]
26357    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
26358        let server = MockWorkerServer::start();
26359        let client = Client::builder(server.base_url())
26360            .timeout(Duration::from_secs(2))
26361            .build()
26362            .expect("client");
26363        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
26364
26365        client
26366            .start_workflow(
26367                "typed.echo",
26368                "rust-workers",
26369                "typed-start",
26370                arguments.clone(),
26371            )
26372            .await
26373            .expect("typed workflow start");
26374        assert_eq!(
26375            decode_wire_avro_value(
26376                &server.request_body("/api/workflows")["input"],
26377                DEFAULT_CODEC,
26378            )
26379            .expect("typed start input"),
26380            arguments
26381        );
26382
26383        client
26384            .signal_workflow("typed-1", "changed", arguments.clone())
26385            .await
26386            .expect("typed signal");
26387        assert_eq!(
26388            decode_wire_avro_value(
26389                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
26390                DEFAULT_CODEC,
26391            )
26392            .expect("typed signal input"),
26393            arguments
26394        );
26395
26396        assert_eq!(
26397            client
26398                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
26399                .await
26400                .expect("typed query"),
26401            typed_fidelity_probe()
26402        );
26403        assert_eq!(
26404            decode_wire_avro_value(
26405                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
26406                DEFAULT_CODEC,
26407            )
26408            .expect("typed query input"),
26409            arguments
26410        );
26411
26412        assert_eq!(
26413            client
26414                .update_workflow_avro_value(
26415                    "typed-1",
26416                    "replace",
26417                    arguments.clone(),
26418                    Some("typed-request"),
26419                )
26420                .await
26421                .expect("typed update"),
26422            typed_fidelity_probe()
26423        );
26424        let update = server.request_body("/api/workflows/typed-1/update/replace");
26425        assert_eq!(update["request_id"], "typed-request");
26426        assert_eq!(
26427            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
26428            arguments
26429        );
26430
26431        let handle = WorkflowHandle {
26432            client: client.clone(),
26433            workflow_id: "typed-1".to_string(),
26434            run_id: Some("run-typed-1".to_string()),
26435            workflow_type: "typed.echo".to_string(),
26436        };
26437        assert_eq!(
26438            handle
26439                .result_avro_value(WorkflowResultOptions::default())
26440                .await
26441                .expect("typed workflow result"),
26442            typed_fidelity_probe()
26443        );
26444
26445        client
26446            .complete_activity_task(
26447                "activity-typed",
26448                "attempt-typed",
26449                "rust-worker",
26450                typed_fidelity_probe(),
26451                DEFAULT_CODEC,
26452            )
26453            .await
26454            .expect("typed activity completion");
26455        assert_eq!(
26456            decode_wire_avro_value(
26457                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
26458                    ["result"],
26459                DEFAULT_CODEC,
26460            )
26461            .expect("typed activity result"),
26462            typed_fidelity_probe()
26463        );
26464        client
26465            .fail_activity_task(
26466                "activity-typed",
26467                "attempt-typed",
26468                "rust-worker",
26469                "typed failure",
26470                true,
26471            )
26472            .await
26473            .expect("activity failure");
26474    }
26475
26476    #[tokio::test]
26477    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
26478        let server = MockWorkerServer::start();
26479        let client = Client::builder(server.base_url())
26480            .timeout(Duration::from_secs(2))
26481            .build()
26482            .expect("client");
26483
26484        let options = WorkflowCommandOptions::new()
26485            .reason("cleanup requested")
26486            .request_id("cancel-17");
26487        let cancelled = client
26488            .cancel_workflow("wf-lifecycle", options)
26489            .await
26490            .expect("instance cancellation");
26491        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
26492        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
26493        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
26494        assert_eq!(
26495            server.request_body("/api/workflows/wf-lifecycle/cancel"),
26496            json!({"reason":"cleanup requested","request_id":"cancel-17"})
26497        );
26498
26499        let terminated = client
26500            .terminate_workflow(
26501                "wf-lifecycle",
26502                WorkflowCommandOptions::new().reason("forced stop"),
26503            )
26504            .await
26505            .expect("instance termination");
26506        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
26507        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
26508
26509        client
26510            .cancel_workflow_run(
26511                "wf-lifecycle",
26512                "run-current",
26513                WorkflowCommandOptions::default(),
26514            )
26515            .await
26516            .expect("selected run cancellation");
26517        client
26518            .terminate_workflow_run(
26519                "wf-lifecycle",
26520                "run-current",
26521                WorkflowCommandOptions::default(),
26522            )
26523            .await
26524            .expect("selected run termination");
26525
26526        for (command, error) in [
26527            (
26528                WorkflowCommandKind::Cancel,
26529                client
26530                    .cancel_workflow_run(
26531                        "wf-lifecycle",
26532                        "run-stale",
26533                        WorkflowCommandOptions::default(),
26534                    )
26535                    .await
26536                    .expect_err("stale cancellation must be rejected"),
26537            ),
26538            (
26539                WorkflowCommandKind::Terminate,
26540                client
26541                    .terminate_workflow_run(
26542                        "wf-lifecycle",
26543                        "run-stale",
26544                        WorkflowCommandOptions::default(),
26545                    )
26546                    .await
26547                    .expect_err("stale termination must be rejected"),
26548            ),
26549        ] {
26550            let Error::WorkflowCommandRejected(rejection) = error else {
26551                panic!("expected typed command rejection");
26552            };
26553            assert_eq!(rejection.command, command);
26554            assert_eq!(rejection.status, 409);
26555            assert_eq!(rejection.reason, "historical_run_command_rejected");
26556            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
26557            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
26558        }
26559    }
26560
26561    #[tokio::test]
26562    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
26563        let server = MockWorkerServer::start();
26564        let client = Client::builder(server.base_url())
26565            .timeout(Duration::from_secs(2))
26566            .build()
26567            .expect("client");
26568
26569        let result = client
26570            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
26571            .await
26572            .expect("redrive accepted");
26573        assert_eq!(result.workflow_id, "wf-lifecycle");
26574        assert_eq!(result.source_run_id, "run-failed");
26575        assert_eq!(result.run_id, "run-successor");
26576        assert_eq!(result.resume_step_sequence, 2);
26577        assert_eq!(
26578            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
26579            json!({"request_id":"retry-1"})
26580        );
26581
26582        let repeated = client
26583            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
26584            .await
26585            .expect("idempotent redrive response accepted");
26586        assert_eq!(repeated.run_id, "run-successor");
26587
26588        let error = client
26589            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
26590            .await
26591            .expect_err("completed run must be rejected");
26592        let Error::Http { status, body } = error else {
26593            panic!("expected HTTP redrive rejection");
26594        };
26595        assert_eq!(status.as_u16(), 409);
26596        assert!(body.contains("run_not_failed"));
26597        assert_eq!(
26598            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
26599            json!({})
26600        );
26601
26602        let handle = WorkflowHandle {
26603            client: client.clone(),
26604            workflow_id: "wf-lifecycle".to_string(),
26605            run_id: Some("run-failed".to_string()),
26606            workflow_type: "test".to_string(),
26607        };
26608        assert_eq!(
26609            handle.redrive(None).await.expect("handle redrive").run_id,
26610            "run-successor"
26611        );
26612        let missing_run = WorkflowHandle {
26613            run_id: None,
26614            ..handle
26615        };
26616        assert!(matches!(
26617            missing_run.redrive(None).await,
26618            Err(Error::Codec(_))
26619        ));
26620    }
26621
26622    #[tokio::test]
26623    async fn workflow_start_options_send_server_enforced_deadlines() {
26624        let server = MockWorkerServer::start();
26625        let client = Client::builder(server.base_url())
26626            .timeout(Duration::from_secs(2))
26627            .build()
26628            .expect("client");
26629
26630        let handle = client
26631            .start_workflow_with_options(
26632                "rust.timeout",
26633                "rust-timeouts",
26634                "wf-start-options",
26635                WorkflowStartOptions::new()
26636                    .execution_timeout_seconds(30)
26637                    .run_timeout_seconds(1),
26638                json!([]),
26639            )
26640            .await
26641            .expect("workflow start");
26642
26643        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
26644        let body = server.request_body("/api/workflows");
26645        assert_eq!(body["execution_timeout_seconds"], 30);
26646        assert_eq!(body["run_timeout_seconds"], 1);
26647
26648        let invalid = client
26649            .start_workflow_with_options(
26650                "rust.timeout",
26651                "rust-timeouts",
26652                "wf-invalid-options",
26653                WorkflowStartOptions::new()
26654                    .execution_timeout_seconds(1)
26655                    .run_timeout_seconds(2),
26656                json!([]),
26657            )
26658            .await
26659            .expect_err("invalid deadline ordering");
26660        assert!(invalid
26661            .to_string()
26662            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
26663    }
26664
26665    #[tokio::test]
26666    async fn workflow_result_returns_each_typed_terminal_outcome() {
26667        let server = MockWorkerServer::start();
26668        let client = Client::builder(server.base_url())
26669            .timeout(Duration::from_secs(2))
26670            .build()
26671            .expect("client");
26672        let options = WorkflowResultOptions {
26673            poll_interval: Duration::ZERO,
26674            timeout: Duration::from_secs(1),
26675        };
26676
26677        let failed = WorkflowHandle {
26678            client: client.clone(),
26679            workflow_id: "wf-failed".to_string(),
26680            run_id: Some("run-failed".to_string()),
26681            workflow_type: "failure".to_string(),
26682        }
26683        .result(options)
26684        .await
26685        .expect_err("failed outcome");
26686        let Error::WorkflowFailed(failure) = failed else {
26687            panic!("expected WorkflowFailed");
26688        };
26689        assert_eq!(failure.workflow_id, "wf-failed");
26690        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
26691        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
26692        assert_eq!(failure.failure_category.as_deref(), Some("application"));
26693        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
26694        assert_eq!(
26695            failure.exception_class.as_deref(),
26696            Some("billing::PaymentError")
26697        );
26698        assert_eq!(failure.non_retryable, Some(true));
26699
26700        for (workflow_id, expected_kind, expected_reason) in [
26701            (
26702                "wf-cancelled",
26703                WorkflowTerminalKind::Cancelled,
26704                "cleanup requested",
26705            ),
26706            (
26707                "wf-terminated",
26708                WorkflowTerminalKind::Terminated,
26709                "forced stop",
26710            ),
26711            (
26712                "wf-timed-out",
26713                WorkflowTerminalKind::TimedOut,
26714                "run_timeout",
26715            ),
26716        ] {
26717            let error = WorkflowHandle {
26718                client: client.clone(),
26719                workflow_id: workflow_id.to_string(),
26720                run_id: None,
26721                workflow_type: "terminal".to_string(),
26722            }
26723            .result(options)
26724            .await
26725            .expect_err("typed terminal outcome");
26726            let outcome = match error {
26727                Error::WorkflowCancelled(outcome) => outcome,
26728                Error::WorkflowTerminated(outcome) => outcome,
26729                Error::WorkflowTimedOut(outcome) => outcome,
26730                other => panic!("unexpected terminal error: {other}"),
26731            };
26732            assert_eq!(outcome.kind, expected_kind);
26733            assert_eq!(outcome.workflow_id, workflow_id);
26734            assert_eq!(outcome.reason, expected_reason);
26735        }
26736
26737        let wait_timeout = WorkflowHandle {
26738            client,
26739            workflow_id: "wf-waiting".to_string(),
26740            run_id: Some("run-waiting".to_string()),
26741            workflow_type: "waiting".to_string(),
26742        }
26743        .result(WorkflowResultOptions {
26744            poll_interval: Duration::ZERO,
26745            timeout: Duration::ZERO,
26746        })
26747        .await
26748        .expect_err("client wait timeout");
26749        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
26750            panic!("expected typed client timeout");
26751        };
26752        assert_eq!(timeout.reason, "result_wait_timeout");
26753        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
26754        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
26755    }
26756
26757    #[tokio::test]
26758    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
26759        let server = MockWorkerServer::start();
26760        let client = Client::builder(server.base_url())
26761            .timeout(Duration::from_secs(2))
26762            .build()
26763            .expect("client");
26764
26765        let handle = WorkflowHandle {
26766            client,
26767            workflow_id: "wf-selected".to_string(),
26768            run_id: Some("run-selected".to_string()),
26769            workflow_type: "selected".to_string(),
26770        };
26771        let options = WorkflowResultOptions {
26772            poll_interval: Duration::ZERO,
26773            timeout: Duration::from_secs(1),
26774        };
26775
26776        let current = handle
26777            .result(options)
26778            .await
26779            .expect("instance result follows the current run");
26780        assert_eq!(current, json!("current run output"));
26781
26782        let error = handle
26783            .result_selected_run(options)
26784            .await
26785            .expect_err("the selected run is cancelled even though the current run completed");
26786
26787        let Error::WorkflowCancelled(outcome) = error else {
26788            panic!("expected selected run cancellation");
26789        };
26790        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
26791        assert_eq!(outcome.reason, "selected run cancelled");
26792        assert_eq!(
26793            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
26794            1
26795        );
26796        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
26797    }
26798
26799    #[tokio::test]
26800    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
26801        let server = MockWorkerServer::draining_polls();
26802        let client = Client::builder(server.base_url())
26803            .timeout(Duration::from_secs(2))
26804            .build()
26805            .expect("client");
26806
26807        let workflow = client
26808            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
26809            .await
26810            .expect("workflow drain response");
26811        let activity = client
26812            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
26813            .await
26814            .expect("activity drain response");
26815        let query = client
26816            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
26817            .await
26818            .expect("query drain response");
26819
26820        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
26821            assert_eq!(
26822                outcome,
26823                WorkerPollOutcome::Stop {
26824                    poll_status: Some("draining".to_string()),
26825                    reason: Some("worker_draining".to_string()),
26826                }
26827            );
26828        }
26829
26830        assert!(client
26831            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
26832            .await
26833            .expect("compatibility poll")
26834            .is_none());
26835    }
26836
26837    #[tokio::test]
26838    async fn managed_worker_honors_drain_stop_for_every_task_family() {
26839        let server = MockWorkerServer::draining_polls();
26840        let client = Client::builder(server.base_url())
26841            .timeout(Duration::from_secs(2))
26842            .build()
26843            .expect("client");
26844
26845        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
26846            .worker_id("draining-workflow-worker")
26847            .poll_timeout(Duration::ZERO);
26848        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
26849        workflow_worker
26850            .run()
26851            .await
26852            .expect("workflow drain is a clean stop");
26853
26854        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
26855            .worker_id("draining-activity-worker")
26856            .poll_timeout(Duration::ZERO);
26857        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
26858        activity_worker
26859            .run()
26860            .await
26861            .expect("activity drain is a clean stop");
26862
26863        let mut query_worker = Worker::new(client, "rust-workers")
26864            .worker_id("draining-query-worker")
26865            .poll_timeout(Duration::ZERO);
26866        query_worker.register_query("counter", "current", |_ctx, _args| async {
26867            Ok(Value::Null)
26868        });
26869        query_worker
26870            .run()
26871            .await
26872            .expect("query drain is a clean stop");
26873    }
26874
26875    #[tokio::test]
26876    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
26877        let server = MockWorkerServer::start();
26878        let client = Client::builder(server.base_url())
26879            .timeout(Duration::from_secs(2))
26880            .build()
26881            .expect("client");
26882
26883        let details: Value = serde_json::from_str(include_str!(
26884            "../tests/fixtures/activity-heartbeat-progress.json"
26885        ))
26886        .expect("heartbeat progress fixture");
26887        // Every individual field fits Server's progress contract, while the
26888        // obsolete encoded envelope exceeded its 191-character string limit.
26889        assert!(
26890            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
26891                .unwrap()["blob"]
26892                .as_str()
26893                .unwrap()
26894                .len()
26895                > 191
26896        );
26897        let heartbeat = client
26898            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
26899            .await
26900            .expect("cancellation heartbeat");
26901        assert!(heartbeat.cancel_requested);
26902        assert!(heartbeat.should_stop());
26903        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
26904        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
26905        let heartbeat_body =
26906            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
26907        assert_eq!(heartbeat_body["details"], details);
26908        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
26909        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
26910
26911        let error = client
26912            .complete_activity_task(
26913                "activity-cancel",
26914                "attempt-cancel",
26915                "rust-worker",
26916                json!({"late":true}),
26917                DEFAULT_CODEC,
26918            )
26919            .await
26920            .expect_err("late completion must be refused");
26921        assert!(activity_task_rejection_is_final(&error));
26922        let Error::ActivityTaskRejected(rejection) = error else {
26923            panic!("expected typed activity rejection");
26924        };
26925        assert_eq!(rejection.status, 409);
26926        assert_eq!(rejection.reason, "run_cancelled");
26927        assert!(rejection.cancel_requested);
26928        assert_eq!(rejection.can_continue, Some(false));
26929    }
26930
26931    #[tokio::test]
26932    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
26933        let server = MockWorkerServer::cancelled_activity();
26934        let client = Client::builder(server.base_url())
26935            .timeout(Duration::from_secs(2))
26936            .build()
26937            .expect("client");
26938        let cancellation_observed = Arc::new(AtomicBool::new(false));
26939        let observed = Arc::clone(&cancellation_observed);
26940        let mut worker = Worker::new(client.clone(), "rust-workers")
26941            .worker_id("rust-cancel-worker")
26942            .poll_timeout(Duration::from_millis(10));
26943        worker.register_activity("cancel-aware", move |ctx, _args| {
26944            let observed = Arc::clone(&observed);
26945            async move {
26946                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
26947                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
26948                Ok(json!({"late":"completion"}))
26949            }
26950        });
26951
26952        assert_eq!(
26953            worker.run_once().await.expect("cancelled attempt handled"),
26954            1
26955        );
26956        assert!(cancellation_observed.load(Ordering::SeqCst));
26957        assert_eq!(
26958            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
26959            1
26960        );
26961
26962        let mut restarted = Worker::new(client, "rust-workers")
26963            .worker_id("rust-cancel-worker-restarted")
26964            .poll_timeout(Duration::from_millis(10));
26965        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
26966        assert_eq!(
26967            restarted
26968                .run_once()
26969                .await
26970                .expect("replacement worker continues polling"),
26971            0
26972        );
26973    }
26974
26975    #[tokio::test]
26976    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
26977        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"}"#;
26978        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
26979        let client = Client::builder(server.base_url())
26980            .timeout(Duration::from_secs(2))
26981            .build()
26982            .expect("client");
26983
26984        let direct_error = client
26985            .complete_workflow_task(
26986                "workflow-timeout-task",
26987                "timeout-worker",
26988                3,
26989                vec![json!({
26990                    "type": "complete_workflow",
26991                    "result": fixture_envelope(Value::Null)
26992                })],
26993            )
26994            .await
26995            .expect_err("the low-level client preserves the completion rejection");
26996        let Error::Http { status, body } = direct_error else {
26997            panic!("expected the original HTTP completion rejection");
26998        };
26999        assert_eq!(status, reqwest::StatusCode::CONFLICT);
27000        assert_eq!(
27001            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
27002            "run_timed_out"
27003        );
27004
27005        let mut worker = Worker::new(client, "rust-workers")
27006            .worker_id("timeout-worker")
27007            .poll_timeout(Duration::from_millis(10));
27008        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
27009            Ok(json!({"late": "result"}))
27010        });
27011
27012        assert_eq!(
27013            worker
27014                .run_once()
27015                .await
27016                .expect("authoritative selected-run timeout settles the tick"),
27017            1
27018        );
27019        assert_eq!(
27020            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
27021            2,
27022            "both the direct client proof and managed worker must see the rejection"
27023        );
27024    }
27025
27026    #[tokio::test]
27027    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
27028        for (name, status, response) in [
27029            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
27030            (
27031                "command was recorded",
27032                "409 Conflict",
27033                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27034            ),
27035            (
27036                "lease conflict",
27037                "409 Conflict",
27038                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
27039            ),
27040            (
27041                "nonterminal run",
27042                "409 Conflict",
27043                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
27044            ),
27045            (
27046                "different selected run",
27047                "409 Conflict",
27048                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"}"#,
27049            ),
27050            (
27051                "different task attempt",
27052                "409 Conflict",
27053                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27054            ),
27055            (
27056                "authentication failure",
27057                "401 Unauthorized",
27058                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27059            ),
27060            (
27061                "authorization failure",
27062                "403 Forbidden",
27063                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27064            ),
27065            (
27066                "protocol failure",
27067                "400 Bad Request",
27068                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
27069            ),
27070            (
27071                "malformed command",
27072                "422 Unprocessable Entity",
27073                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27074            ),
27075            (
27076                "transient server failure",
27077                "503 Service Unavailable",
27078                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27079            ),
27080        ] {
27081            let server = MockWorkerServer::workflow_completion(status, response);
27082            let client = Client::builder(server.base_url())
27083                .timeout(Duration::from_secs(2))
27084                .build()
27085                .expect("client");
27086            let mut worker = Worker::new(client, "rust-workers")
27087                .worker_id("timeout-worker")
27088                .poll_timeout(Duration::from_millis(10));
27089            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
27090                Ok(json!({"late": "result"}))
27091            });
27092
27093            let error = worker
27094                .run_once()
27095                .await
27096                .expect_err(&format!("{name} must remain an error"));
27097            assert!(
27098                matches!(error, Error::Http { .. } | Error::Protocol(_)),
27099                "{name} returned an unexpected error variant: {error}"
27100            );
27101        }
27102    }
27103
27104    #[tokio::test]
27105    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
27106        let server = MockWorkerServer::start();
27107        let client = Client::builder(server.base_url())
27108            .worker_token(Some("worker-secret".to_string()))
27109            .namespace("orders")
27110            .timeout(Duration::from_secs(2))
27111            .build()
27112            .expect("client");
27113        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
27114
27115        let result = client
27116            .deregister_worker_registration("worker/α space")
27117            .await
27118            .expect("deregister worker registration");
27119
27120        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
27121        assert_eq!(
27122            server.worker_protocol_for(path).as_deref(),
27123            Some(WORKER_PROTOCOL_VERSION)
27124        );
27125        assert_eq!(server.control_protocol_for(path), None);
27126        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
27127        assert_eq!(
27128            server.authorization_for(path).as_deref(),
27129            Some("Bearer worker-secret")
27130        );
27131        assert_eq!(
27132            result,
27133            WorkerDeregistrationEnvelope {
27134                worker_id: "deregistered-worker".to_string(),
27135                outcome: "deregistered".to_string(),
27136                recovered_workflow_task_count: 2,
27137            }
27138        );
27139    }
27140
27141    #[tokio::test]
27142    async fn low_level_registration_rejects_update_validators_before_transport() {
27143        let server = MockWorkerServer::start();
27144        let client = Client::builder(server.base_url())
27145            .timeout(Duration::from_secs(2))
27146            .build()
27147            .expect("client");
27148
27149        for update_validators in [json!(["approve"]), json!("approve")] {
27150            let error = client
27151                .register_worker_with_command_contracts(
27152                    "validator-claiming-worker",
27153                    "rust-workers",
27154                    vec!["orders".to_string()],
27155                    vec![],
27156                    1,
27157                    1,
27158                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27159                    json!({
27160                        "orders": {
27161                            "queries": ["current"],
27162                            "updates": ["approve"],
27163                            "update_validators": update_validators,
27164                        },
27165                    }),
27166                )
27167                .await
27168                .expect_err("unsupported validator claims must fail before registration");
27169
27170            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
27171                panic!("expected typed unsupported-validator failure");
27172            };
27173            assert_eq!(workflow_type, "orders");
27174        }
27175        assert_eq!(server.request_count("/api/worker/register"), 0);
27176    }
27177
27178    #[tokio::test]
27179    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
27180        let server = MockWorkerServer::start();
27181        let client = Client::builder(server.base_url())
27182            .timeout(Duration::from_secs(2))
27183            .build()
27184            .expect("client");
27185        let mut worker = Worker::new(client, "rust-workers");
27186        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
27187        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
27188        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
27189        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
27190        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
27191        worker
27192            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
27193            .expect("declare workflow signals");
27194
27195        worker.register().await.expect("register handler contracts");
27196
27197        let declaration =
27198            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
27199        let expected_contracts = json!([
27200            {
27201                "name": "a-avro",
27202                "parameters": [{
27203                    "name": "args", "position": 0, "required": false,
27204                    "variadic": true, "type": null, "allows_null": true,
27205                    "default_available": false, "default": null,
27206                }],
27207            },
27208            {
27209                "name": "z-json",
27210                "parameters": [{
27211                    "name": "args", "position": 0, "required": false,
27212                    "variadic": true, "type": null, "allows_null": true,
27213                    "default_available": false, "default": null,
27214                }],
27215            },
27216        ]);
27217        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
27218        assert_eq!(declaration["query_contracts"], expected_contracts);
27219        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
27220        assert_eq!(declaration["update_contracts"], expected_contracts);
27221        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
27222        assert_eq!(declaration["signal_contracts"], expected_contracts);
27223        assert_eq!(declaration["update_validators"], json!([]));
27224    }
27225
27226    #[tokio::test]
27227    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
27228        let server = MockWorkerServer::start();
27229        let client = Client::new(server.base_url()).expect("client");
27230        let mut worker = Worker::new(client, "rust-workers");
27231        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
27232        assert!(worker
27233            .declare_workflow_signals("missing", &["finish"])
27234            .is_err());
27235        worker
27236            .declare_workflow_signals("orders", &["finish"])
27237            .unwrap();
27238        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
27239            assert!(worker.declare_workflow_signals("orders", names).is_err());
27240        }
27241        worker.register().await.unwrap();
27242        assert_eq!(
27243            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
27244                ["signals"],
27245            json!(["finish"])
27246        );
27247        worker.declare_workflow_signals("orders", &[]).unwrap();
27248        worker.register().await.unwrap();
27249        let registrations = server.request_bodies("/api/worker/register");
27250        assert_eq!(
27251            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
27252            json!([])
27253        );
27254        assert_eq!(
27255            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
27256            json!([])
27257        );
27258    }
27259
27260    #[tokio::test]
27261    async fn low_level_registration_preserves_query_and_update_contracts() {
27262        let server = MockWorkerServer::start();
27263        let client = Client::builder(server.base_url())
27264            .timeout(Duration::from_secs(2))
27265            .build()
27266            .expect("client");
27267        let contracts = json!({
27268            "orders": {
27269                "queries": ["current"],
27270                "updates": ["approve"],
27271                "update_validators": [],
27272            },
27273            "payments": {
27274                "queries": ["status"],
27275                "updates": ["capture"],
27276            },
27277        });
27278
27279        client
27280            .register_worker_with_command_contracts(
27281                "command-worker",
27282                "rust-workers",
27283                vec!["orders".to_string(), "payments".to_string()],
27284                vec![],
27285                1,
27286                1,
27287                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27288                contracts.clone(),
27289            )
27290            .await
27291            .expect("query and update contracts must remain supported");
27292
27293        assert_eq!(
27294            server.request_body("/api/worker/register")["workflow_command_contracts"],
27295            contracts
27296        );
27297        assert!(server
27298            .request_body("/api/worker/register")
27299            .get("workflow_definition_fingerprints")
27300            .is_none());
27301    }
27302
27303    #[tokio::test]
27304    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
27305        let server = MockWorkerServer::start();
27306        let client = Client::builder(server.base_url())
27307            .timeout(Duration::from_secs(2))
27308            .build()
27309            .expect("client");
27310        let mut worker = Worker::new(client.clone(), "rust-workers");
27311        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27312
27313        assert!(worker
27314            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
27315            .is_err());
27316        assert!(worker
27317            .set_workflow_definition_sources("orders", &[])
27318            .is_err());
27319        worker
27320            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
27321            .expect("embed workflow source");
27322        worker.register().await.expect("register worker");
27323        let first = server.request_bodies("/api/worker/register")[0]
27324            ["workflow_definition_fingerprints"]["orders"]
27325            .as_str()
27326            .expect("source-backed fingerprint")
27327            .to_string();
27328        assert!(first.starts_with("sha256:"));
27329
27330        worker
27331            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
27332            .expect("change embedded helper source");
27333        worker.register().await.expect("register changed source");
27334        let changed = server.request_bodies("/api/worker/register")[1]
27335            ["workflow_definition_fingerprints"]["orders"]
27336            .as_str()
27337            .expect("changed fingerprint")
27338            .to_string();
27339        assert_ne!(first, changed);
27340
27341        let mut replacement =
27342            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
27343        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27344        replacement
27345            .register()
27346            .await
27347            .expect("register replacement handler");
27348        assert_eq!(
27349            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
27350            json!({})
27351        );
27352    }
27353
27354    #[tokio::test]
27355    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
27356        let server = MockWorkerServer::start();
27357        let control_only = Client::builder(server.base_url())
27358            .control_token(Some("control-secret".to_string()))
27359            .build()
27360            .expect("control client");
27361
27362        let error = control_only
27363            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27364            .await
27365            .expect_err("control token must not authorize a worker request");
27366        assert!(matches!(
27367            error,
27368            Error::MissingRoleCredentials { role: "worker", .. }
27369        ));
27370        assert_eq!(server.request_count("/api/worker/register"), 0);
27371
27372        let worker_only = Client::builder(server.base_url())
27373            .worker_token(Some("worker-secret".to_string()))
27374            .build()
27375            .expect("worker client");
27376        let error = worker_only
27377            .health()
27378            .await
27379            .expect_err("worker token must not authorize a control request");
27380        assert!(matches!(
27381            error,
27382            Error::MissingRoleCredentials {
27383                role: "control",
27384                ..
27385            }
27386        ));
27387        assert_eq!(server.request_count("/api/health"), 0);
27388    }
27389
27390    #[tokio::test]
27391    async fn shared_token_supports_worker_and_control_planes() {
27392        let server = MockWorkerServer::start();
27393        let client = Client::builder(server.base_url())
27394            .token(Some("shared-secret".to_string()))
27395            .build()
27396            .expect("client");
27397
27398        client.health().await.expect("control request");
27399        client
27400            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27401            .await
27402            .expect("worker request");
27403
27404        assert_eq!(
27405            server.authorization_for("/api/health").as_deref(),
27406            Some("Bearer shared-secret")
27407        );
27408        assert_eq!(
27409            server.control_protocol_for("/api/health").as_deref(),
27410            Some(CONTROL_PLANE_VERSION)
27411        );
27412        assert_eq!(
27413            server.authorization_for("/api/worker/register").as_deref(),
27414            Some("Bearer shared-secret")
27415        );
27416        assert_eq!(
27417            server
27418                .worker_protocol_for("/api/worker/register")
27419                .as_deref(),
27420            Some(WORKER_PROTOCOL_VERSION)
27421        );
27422    }
27423
27424    #[tokio::test]
27425    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
27426        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
27427        let server = MockWorkerServer::start();
27428        let client = Client::builder(server.base_url())
27429            .timeout(Duration::from_secs(2))
27430            .build()
27431            .expect("client");
27432
27433        client
27434            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
27435            .await
27436            .expect("register");
27437        client
27438            .heartbeat_worker("capture-worker", 1, 1)
27439            .await
27440            .expect("heartbeat");
27441        client
27442            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27443            .await
27444            .expect("workflow poll");
27445        client
27446            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27447            .await
27448            .expect("activity poll");
27449
27450        for path in [
27451            "/api/worker/register",
27452            "/api/worker/heartbeat",
27453            "/api/worker/workflow-tasks/poll",
27454            "/api/worker/activity-tasks/poll",
27455        ] {
27456            assert_eq!(
27457                server.worker_protocol_for(path).as_deref(),
27458                Some(WORKER_PROTOCOL_VERSION),
27459                "unexpected protocol for {path}"
27460            );
27461        }
27462
27463        assert_eq!(
27464            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
27465            1
27466        );
27467        assert_eq!(
27468            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
27469            500
27470        );
27471        assert_eq!(
27472            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
27473            1
27474        );
27475        assert!(
27476            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
27477                .as_str()
27478                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
27479        );
27480        assert!(
27481            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
27482                .as_str()
27483                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
27484        );
27485        let registration = server.request_body("/api/worker/register");
27486        for optional in [
27487            "cooperative_cancellation",
27488            "local_activities",
27489            "worker_sessions",
27490            "sticky_execution",
27491        ] {
27492            assert!(!registration["capabilities"]
27493                .as_array()
27494                .is_some_and(|capabilities| capabilities
27495                    .iter()
27496                    .any(|capability| capability.as_str() == Some(optional))));
27497        }
27498    }
27499
27500    #[tokio::test]
27501    async fn explicit_previous_worker_protocol_preserves_headers() {
27502        let server = MockWorkerServer::start();
27503        let client = Client::builder(server.base_url())
27504            .worker_protocol_version(WorkerProtocolVersion::V119)
27505            .timeout(Duration::from_secs(2))
27506            .build()
27507            .expect("client");
27508        client
27509            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
27510            .await
27511            .expect("register");
27512        client
27513            .heartbeat_worker("legacy-worker", 1, 1)
27514            .await
27515            .expect("heartbeat");
27516        client
27517            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
27518            .await
27519            .expect("workflow poll");
27520        client
27521            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
27522            .await
27523            .expect("activity poll");
27524        client
27525            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
27526            .await
27527            .expect("query poll");
27528        client
27529            .deregister_worker_registration("legacy-worker")
27530            .await
27531            .expect("deregister");
27532        for path in [
27533            "/api/worker/register",
27534            "/api/worker/heartbeat",
27535            "/api/worker/workflow-tasks/poll",
27536            "/api/worker/activity-tasks/poll",
27537            "/api/worker/query-tasks/poll",
27538            "/api/worker/registrations/legacy-worker",
27539        ] {
27540            assert_eq!(
27541                server.worker_protocol_for(path).as_deref(),
27542                Some("1.19"),
27543                "{path}"
27544            );
27545            assert_eq!(server.control_protocol_for(path), None, "{path}");
27546        }
27547    }
27548
27549    #[tokio::test]
27550    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
27551        let server = MockWorkerServer::start();
27552        let client = Client::builder(server.base_url())
27553            .worker_protocol_version(WorkerProtocolVersion::V119)
27554            .timeout(Duration::from_secs(2))
27555            .build()
27556            .expect("client");
27557        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
27558        let error = worker
27559            .register()
27560            .await
27561            .expect_err("legacy cooperation must be refused");
27562        assert!(matches!(
27563            error,
27564            Error::CooperativeCancellationUnavailable(_)
27565        ));
27566        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
27567    }
27568
27569    #[tokio::test]
27570    async fn query_task_endpoints_send_the_selected_worker_protocol() {
27571        let server = MockWorkerServer::start();
27572        let client = Client::builder(server.base_url())
27573            .timeout(Duration::from_secs(2))
27574            .build()
27575            .expect("client");
27576
27577        client
27578            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27579            .await
27580            .expect("query poll");
27581        client
27582            .complete_query_task(
27583                "query-capture",
27584                "capture-worker",
27585                1,
27586                json!(8),
27587                DEFAULT_CODEC,
27588            )
27589            .await
27590            .expect("query complete");
27591        client
27592            .fail_query_task(
27593                "query-capture",
27594                "capture-worker",
27595                1,
27596                "failed",
27597                "query_rejected",
27598                "QueryFailed",
27599            )
27600            .await
27601            .expect("query fail");
27602
27603        for path in [
27604            "/api/worker/query-tasks/poll",
27605            "/api/worker/query-tasks/query-capture/complete",
27606            "/api/worker/query-tasks/query-capture/fail",
27607        ] {
27608            assert_eq!(
27609                server.worker_protocol_for(path).as_deref(),
27610                Some(WORKER_PROTOCOL_VERSION),
27611                "unexpected protocol for {path}"
27612            );
27613        }
27614
27615        assert_eq!(
27616            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
27617            1
27618        );
27619        assert!(
27620            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
27621                .as_str()
27622                .is_some_and(|id| id.starts_with("rust-query-poll-"))
27623        );
27624    }
27625
27626    #[tokio::test]
27627    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
27628        let server = MockWorkerServer::transient_worker_failures();
27629        let client = Client::builder(server.base_url())
27630            .timeout(Duration::from_secs(2))
27631            .build()
27632            .expect("client");
27633
27634        client
27635            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27636            .await
27637            .expect("workflow poll retry");
27638        client
27639            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27640            .await
27641            .expect("activity poll retry");
27642        client
27643            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27644            .await
27645            .expect("query poll retry");
27646
27647        for path in [
27648            "/api/worker/workflow-tasks/poll",
27649            "/api/worker/activity-tasks/poll",
27650            "/api/worker/query-tasks/poll",
27651        ] {
27652            let bodies = server.request_bodies(path);
27653            assert_eq!(bodies.len(), 2, "{path} must be retried once");
27654            assert_eq!(
27655                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
27656                "{path} must preserve the request binding across retry"
27657            );
27658        }
27659    }
27660
27661    #[tokio::test]
27662    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
27663        let server = MockWorkerServer::consecutive_poll_failures(2);
27664        let client = Client::builder(server.base_url())
27665            .timeout(Duration::from_secs(2))
27666            .build()
27667            .expect("client");
27668        let mut worker = Worker::new(client, "capture")
27669            .worker_id("capture-worker")
27670            .poll_timeout(Duration::from_millis(10))
27671            .retry_policy(WorkerRetryPolicy {
27672                max_retries: 2,
27673                initial_backoff: Duration::from_millis(1),
27674                max_backoff: Duration::from_millis(1),
27675            });
27676        worker.register_workflow(
27677            "capture.workflow",
27678            |_ctx, _input| async move { Ok(Value::Null) },
27679        );
27680        worker.register_activity(
27681            "capture.activity",
27682            |_ctx, _input| async move { Ok(Value::Null) },
27683        );
27684        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
27685            Ok(Value::Null)
27686        });
27687
27688        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
27689
27690        for path in [
27691            "/api/worker/workflow-tasks/poll",
27692            "/api/worker/activity-tasks/poll",
27693            "/api/worker/query-tasks/poll",
27694        ] {
27695            let bodies = server.request_bodies(path);
27696            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
27697            assert!(
27698                bodies
27699                    .iter()
27700                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
27701                "{path} must preserve one request binding across every retry"
27702            );
27703        }
27704    }
27705
27706    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
27707        let reason = if unavailable {
27708            "storage_admission_unavailable"
27709        } else {
27710            "storage_pressure"
27711        };
27712        let mut body = json!({
27713            "reason": reason,
27714            "storage_state": if unavailable { "fenced" } else { "draining" },
27715            "retryable": true,
27716            "retry_after_seconds": 1,
27717        });
27718        if !mid_poll {
27719            body["request_admitted"] = json!(false);
27720        }
27721        if let Some(id) = poll_id {
27722            body["task"] = Value::Null;
27723            body["poll_status"] = json!(reason);
27724            body["poll_request_id"] = json!(id);
27725            body["retry_same_poll_request_id"] = json!(true);
27726            body["claim_admitted"] = json!(false);
27727        }
27728        body
27729    }
27730
27731    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
27732        let operation = match path {
27733            "/api/worker/register" => "register_worker",
27734            "/api/worker/heartbeat" => "heartbeat_worker",
27735            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
27736            "/api/worker/activity-tasks/poll" => "poll_activity_task",
27737            "/api/worker/query-tasks/poll" => "poll_query_task",
27738            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
27739            _ => return None,
27740        };
27741        let request: Value = serde_json::from_str(request).ok()?;
27742        let mut response = json!({
27743            "reason": "backend_unavailable",
27744            "operation": operation,
27745            "outcome": "unknown",
27746            "retryable": true,
27747            "retry_after_seconds": 1,
27748            "worker_id": request["worker_id"],
27749            "task_queue": request.get("task_queue"),
27750        });
27751        if path.ends_with("/poll") {
27752            response["task"] = Value::Null;
27753            response["poll_status"] = json!("backend_unavailable");
27754            response["poll_request_id"] = request["poll_request_id"].clone();
27755            response["retry_same_poll_request_id"] = json!(true);
27756        }
27757        Some(response)
27758    }
27759
27760    fn backend_retry_override(
27761        path: &str,
27762        request: &str,
27763        number: usize,
27764    ) -> Option<(&'static str, String)> {
27765        if number > 8 {
27766            return None;
27767        }
27768        Some((
27769            "503 Service Unavailable",
27770            backend_refusal(path, request)?.to_string(),
27771        ))
27772    }
27773
27774    fn backend_unavailable_override(
27775        path: &str,
27776        request: &str,
27777        _number: usize,
27778    ) -> Option<(&'static str, String)> {
27779        Some((
27780            "503 Service Unavailable",
27781            backend_refusal(path, request)?.to_string(),
27782        ))
27783    }
27784
27785    fn storage_worker(server: &MockWorkerServer) -> Worker {
27786        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
27787            .worker_id("storage-worker")
27788            .retry_policy(WorkerRetryPolicy {
27789                max_retries: 1,
27790                initial_backoff: Duration::from_millis(1),
27791                max_backoff: Duration::from_millis(1),
27792            })
27793    }
27794
27795    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
27796        let requests = server.requests.lock().expect("requests");
27797        let bodies: Vec<_> = requests
27798            .iter()
27799            .filter(|request| request.path == path)
27800            .map(|request| &request.body)
27801            .collect();
27802        assert_eq!(bodies.len(), count, "{path}");
27803        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
27804    }
27805
27806    #[test]
27807    fn backend_recovery_requires_the_explicit_worker_contract() {
27808        for (path, operation) in [
27809            ("/worker/register", "register_worker"),
27810            ("/worker/heartbeat", "heartbeat_worker"),
27811            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
27812            ("/worker/activity-tasks/poll", "poll_activity_task"),
27813            ("/worker/query-tasks/poll", "poll_query_task"),
27814            (
27815                "/worker/update-validation-tasks/poll",
27816                "poll_update_validation_task",
27817            ),
27818        ] {
27819            let poll_id = path.ends_with("/poll").then_some("same-poll");
27820            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
27821            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
27822                .expect("worker operation");
27823            assert_eq!(body["operation"], operation);
27824            let error = Error::Http {
27825                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27826                body: body.to_string(),
27827            };
27828            assert_eq!(
27829                worker_backend_unavailable_retry_after(&error, path, poll_id),
27830                Some(Duration::from_secs(1))
27831            );
27832            assert!(!worker_operation_is_retryable(&error));
27833            for (field, value) in [
27834                ("operation", json!("wrong_operation")),
27835                ("outcome", json!("completed")),
27836                ("retryable", json!(false)),
27837                ("retry_after_seconds", json!(0)),
27838                ("worker_id", json!("")),
27839            ] {
27840                let mut invalid = body.clone();
27841                invalid[field] = value;
27842                let error = Error::Http {
27843                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27844                    body: invalid.to_string(),
27845                };
27846                assert!(
27847                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
27848                    "{path}: {field}"
27849                );
27850                assert!(!worker_operation_is_retryable(&error));
27851            }
27852            if let Some(poll_id) = poll_id {
27853                for (field, value) in [
27854                    ("poll_request_id", json!("wrong-poll")),
27855                    ("poll_status", json!("empty")),
27856                    ("task", json!({"task_id":"claimed"})),
27857                    ("retry_same_poll_request_id", json!(false)),
27858                ] {
27859                    let mut invalid = body.clone();
27860                    invalid[field] = value;
27861                    let error = Error::Http {
27862                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27863                        body: invalid.to_string(),
27864                    };
27865                    assert!(
27866                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
27867                            .is_none(),
27868                        "{path}: {field}"
27869                    );
27870                }
27871            }
27872            let error = Error::Http {
27873                status: reqwest::StatusCode::UNAUTHORIZED,
27874                body: body.to_string(),
27875            };
27876            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
27877            assert!(!worker_operation_is_retryable(&error));
27878        }
27879    }
27880
27881    #[tokio::test]
27882    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
27883        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27884            request_override: Some(backend_retry_override),
27885            ..MockWorkerBehavior::default()
27886        });
27887        let mut worker =
27888            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27889        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27890        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
27891        worker.register_query("backend.workflow", "state", |_, _| async {
27892            Ok(Value::Null)
27893        });
27894        worker.register().await.expect("registration recovery");
27895        worker
27896            .client
27897            .heartbeat_worker("storage-worker", 1, 1)
27898            .await
27899            .expect("heartbeat recovery");
27900        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
27901        for path in [
27902            "/api/worker/register",
27903            "/api/worker/heartbeat",
27904            "/api/worker/workflow-tasks/poll",
27905            "/api/worker/activity-tasks/poll",
27906            "/api/worker/query-tasks/poll",
27907        ] {
27908            assert_identical_requests(&server, path, 9);
27909        }
27910    }
27911
27912    #[tokio::test]
27913    async fn backend_recovery_wait_stops_with_worker() {
27914        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27915            request_override: Some(backend_unavailable_override),
27916            ..MockWorkerBehavior::default()
27917        });
27918        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
27919            max_retries: 1,
27920            initial_backoff: Duration::from_secs(2),
27921            max_backoff: Duration::from_secs(2),
27922        });
27923        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27924        let started = tokio::time::Instant::now();
27925        let _ = tokio::time::timeout(
27926            Duration::from_secs(1),
27927            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
27928        )
27929        .await
27930        .expect("shutdown interrupts backend wait");
27931        assert!(started.elapsed() < Duration::from_secs(1));
27932        assert!(server.request_count("/api/worker/register") >= 1);
27933    }
27934
27935    #[test]
27936    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
27937        for unavailable in [false, true] {
27938            for mid_poll in [false, true] {
27939                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
27940                let error = Error::Http {
27941                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27942                    body: body.to_string(),
27943                };
27944                assert_eq!(
27945                    worker_storage_admission_retry_after(&error, Some("same-poll")),
27946                    Some(Duration::from_secs(1))
27947                );
27948                assert!(
27949                    !worker_operation_is_retryable(&error),
27950                    "storage is not a bounded generic retry"
27951                );
27952                for (field, value) in [
27953                    ("poll_request_id", json!("wrong-poll")),
27954                    ("task", json!({"task_id":"claimed"})),
27955                    ("retryable", json!(false)),
27956                    ("retry_after_seconds", json!(0)),
27957                    ("retry_after_seconds", json!(true)),
27958                    ("retry_after_seconds", json!(1.0)),
27959                    ("storage_state", json!("normal")),
27960                    ("poll_status", json!("empty")),
27961                    ("claim_admitted", json!(true)),
27962                    ("retry_same_poll_request_id", json!(false)),
27963                    ("request_admitted", json!(true)),
27964                ] {
27965                    let mut invalid = body.clone();
27966                    invalid[field] = value;
27967                    let error = Error::Http {
27968                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27969                        body: invalid.to_string(),
27970                    };
27971                    assert!(
27972                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
27973                        "{field}"
27974                    );
27975                }
27976            }
27977        }
27978        let body = storage_refusal(None, false, false);
27979        let error = Error::Http {
27980            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27981            body: body.to_string(),
27982        };
27983        assert!(worker_storage_admission_retry_after(&error, None).is_some());
27984        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
27985        let error = Error::Http {
27986            status: reqwest::StatusCode::FORBIDDEN,
27987            body: body.to_string(),
27988        };
27989        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27990        let body = storage_refusal(None, false, true);
27991        let error = Error::Http {
27992            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27993            body: body.to_string(),
27994        };
27995        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27996    }
27997
27998    #[tokio::test]
27999    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
28000        for unavailable in [false, true] {
28001            for mid_poll in [false, true] {
28002                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28003                    poll_failures_per_path: 1,
28004                    storage_refusals: 7,
28005                    storage_path: Some("/poll"),
28006                    storage_unavailable: unavailable,
28007                    storage_mid_poll: mid_poll,
28008                    ..MockWorkerBehavior::default()
28009                });
28010                let mut worker = storage_worker(&server);
28011                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
28012                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
28013                for path in [
28014                    "/api/worker/workflow-tasks/poll",
28015                    "/api/worker/activity-tasks/poll",
28016                    "/api/worker/query-tasks/poll",
28017                ] {
28018                    assert_identical_requests(&server, path, 9);
28019                }
28020            }
28021        }
28022    }
28023
28024    #[tokio::test]
28025    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
28026        struct CountedBody(Arc<AtomicUsize>);
28027        impl Serialize for CountedBody {
28028            fn serialize<S: Serializer>(
28029                &self,
28030                serializer: S,
28031            ) -> std::result::Result<S::Ok, S::Error> {
28032                let count = self.0.fetch_add(1, Ordering::SeqCst);
28033                json!({"serialization":count,"lease_owner":"worker","attempt":7})
28034                    .serialize(serializer)
28035            }
28036        }
28037        for path in [
28038            "/api/worker/register",
28039            "/api/worker/heartbeat",
28040            "/api/worker/workflow-tasks/storage-task/complete",
28041            "/api/worker/workflow-tasks/storage-task/fail",
28042            "/api/worker/activity-tasks/storage-task/complete",
28043            "/api/worker/activity-tasks/storage-task/fail",
28044            "/api/worker/activity-tasks/storage-task/heartbeat",
28045            "/api/worker/query-tasks/storage-task/complete",
28046            "/api/worker/query-tasks/storage-task/fail",
28047        ] {
28048            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28049                storage_refusals: 7,
28050                storage_path: Some(path),
28051                ..MockWorkerBehavior::default()
28052            });
28053            let worker =
28054                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28055            let calls = Arc::new(AtomicUsize::new(0));
28056            let _: Value = worker
28057                .client
28058                .request_json(
28059                    reqwest::Method::POST,
28060                    &path[4..],
28061                    RequestProtocol::DefaultWorker,
28062                    Some(&CountedBody(Arc::clone(&calls))),
28063                )
28064                .await
28065                .expect("prepared request recovery");
28066            assert_eq!(calls.load(Ordering::SeqCst), 1);
28067            assert_identical_requests(&server, path, 8);
28068        }
28069        for worker_scope in [false, true] {
28070            let path = if worker_scope {
28071                "/api/health"
28072            } else {
28073                "/api/worker/register"
28074            };
28075            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28076                storage_refusals: usize::MAX,
28077                storage_path: Some(path),
28078                ..MockWorkerBehavior::default()
28079            });
28080            let worker = storage_worker(&server);
28081            let client = worker.client.clone();
28082            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
28083            let error = if worker_scope {
28084                worker
28085                    .client
28086                    .health()
28087                    .await
28088                    .expect_err("control plane is not retried")
28089            } else {
28090                client
28091                    .request_json::<Value, Value>(
28092                        reqwest::Method::POST,
28093                        "/worker/register",
28094                        RequestProtocol::DefaultWorker,
28095                        Some(&json!({})),
28096                    )
28097                    .await
28098                    .expect_err("direct client is not retried")
28099            };
28100            assert!(worker_storage_admission_body(&error).is_some());
28101            assert_eq!(server.request_count(path), 1);
28102        }
28103    }
28104
28105    #[tokio::test]
28106    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
28107        for fail in [false, true] {
28108            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28109                storage_activity: true,
28110                storage_refusals: 7,
28111                storage_path: Some("/storage-activity/"),
28112                ..MockWorkerBehavior::default()
28113            });
28114            let mut worker = storage_worker(&server);
28115            let calls = Arc::new(AtomicUsize::new(0));
28116            let observed = Arc::clone(&calls);
28117            worker.register_activity("storage.activity", move |ctx, _| {
28118                let calls = Arc::clone(&observed);
28119                async move {
28120                    calls.fetch_add(1, Ordering::SeqCst);
28121                    ctx.heartbeat(json!({"step":2})).await?;
28122                    if fail {
28123                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
28124                    } else {
28125                        Ok(json!({"receipt":true}))
28126                    }
28127                }
28128            });
28129            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
28130            assert_eq!(calls.load(Ordering::SeqCst), 1);
28131            assert_identical_requests(
28132                &server,
28133                "/api/worker/activity-tasks/storage-activity/heartbeat",
28134                8,
28135            );
28136            let suffix = if fail { "fail" } else { "complete" };
28137            assert_identical_requests(
28138                &server,
28139                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
28140                8,
28141            );
28142            let other = if fail { "complete" } else { "fail" };
28143            assert_eq!(
28144                server.request_count(&format!(
28145                    "/api/worker/activity-tasks/storage-activity/{other}"
28146                )),
28147                0
28148            );
28149        }
28150    }
28151
28152    #[tokio::test]
28153    async fn storage_waits_are_interruptible_without_false_activity_failure() {
28154        for path in [
28155            "/api/worker/register",
28156            "/api/worker/heartbeat",
28157            "/api/worker/activity-tasks/poll",
28158            "/api/worker/activity-tasks/storage-activity/heartbeat",
28159            "/api/worker/activity-tasks/storage-activity/complete",
28160        ] {
28161            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28162                storage_activity: true,
28163                storage_refusals: usize::MAX,
28164                storage_path: Some(path),
28165                ..MockWorkerBehavior::default()
28166            });
28167            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28168            worker.register_activity("storage.activity", |ctx, _| async move {
28169                ctx.heartbeat(json!({"step":2})).await?;
28170                Ok(json!({"receipt":true}))
28171            });
28172            let shutdown = async {
28173                while server.request_count(path) == 0 {
28174                    tokio::time::sleep(Duration::from_millis(1)).await;
28175                }
28176            };
28177            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
28178                .await
28179                .expect("shutdown interrupts admission");
28180            assert!(
28181                result.is_err(),
28182                "a refused operation must not appear acknowledged: {path}, {result:?}"
28183            );
28184            assert_eq!(server.request_count(path), 1);
28185            assert_eq!(
28186                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
28187                0
28188            );
28189            assert_eq!(
28190                server.request_count("/api/worker/registrations/mock-worker"),
28191                usize::from(!path.ends_with("/register"))
28192            );
28193        }
28194    }
28195
28196    #[tokio::test]
28197    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
28198        for fail in [false, true] {
28199            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28200                storage_query: true,
28201                storage_refusals: 7,
28202                storage_path: Some("/storage-query/"),
28203                ..MockWorkerBehavior::default()
28204            });
28205            let mut worker = storage_worker(&server);
28206            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
28207            let calls = Arc::new(AtomicUsize::new(0));
28208            let observed = Arc::clone(&calls);
28209            worker.register_query("storage.workflow", "state", move |_, _| {
28210                let calls = Arc::clone(&observed);
28211                async move {
28212                    calls.fetch_add(1, Ordering::SeqCst);
28213                    if fail {
28214                        Err(Error::WorkerLoop("intentional query failure".to_string()))
28215                    } else {
28216                        Ok(json!({"state":"waiting"}))
28217                    }
28218                }
28219            });
28220            assert_eq!(worker.run_once().await.expect("query settled"), 1);
28221            assert_eq!(calls.load(Ordering::SeqCst), 1);
28222            let suffix = if fail { "fail" } else { "complete" };
28223            assert_identical_requests(
28224                &server,
28225                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
28226                8,
28227            );
28228            let other = if fail { "complete" } else { "fail" };
28229            assert_eq!(
28230                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
28231                0
28232            );
28233        }
28234    }
28235
28236    #[tokio::test]
28237    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
28238        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28239            storage_refusals: 7,
28240            storage_path: Some("/poll"),
28241            unauthorized_polls: true,
28242            ..MockWorkerBehavior::default()
28243        });
28244        let error = storage_worker(&server)
28245            .run_once()
28246            .await
28247            .expect_err("auth remains terminal");
28248        assert!(matches!(
28249            error,
28250            Error::Http {
28251                status: reqwest::StatusCode::UNAUTHORIZED,
28252                ..
28253            }
28254        ));
28255        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
28256
28257        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28258            storage_refusals: 7,
28259            storage_path: Some("/activity-cancel/complete"),
28260            ..MockWorkerBehavior::default()
28261        });
28262        let worker =
28263            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28264        let error = worker
28265            .client
28266            .complete_activity_task(
28267                "activity-cancel",
28268                "attempt-cancel",
28269                "worker",
28270                json!({}),
28271                DEFAULT_CODEC,
28272            )
28273            .await
28274            .expect_err("cancellation remains terminal");
28275        assert!(activity_task_rejection_is_final(&error));
28276        assert_identical_requests(
28277            &server,
28278            "/api/worker/activity-tasks/activity-cancel/complete",
28279            8,
28280        );
28281
28282        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28283            storage_refusals: usize::MAX,
28284            storage_path: Some("/poll"),
28285            storage_wrong_poll_id: true,
28286            ..MockWorkerBehavior::default()
28287        });
28288        assert!(storage_worker(&server).run_once().await.is_err());
28289        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28290    }
28291
28292    #[tokio::test]
28293    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
28294        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28295            storage_refusals: usize::MAX,
28296            storage_path: Some("/poll"),
28297            ..MockWorkerBehavior::default()
28298        });
28299        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28300        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
28301        let run = tokio::spawn(async move { worker.run().await });
28302        tokio::time::timeout(Duration::from_secs(2), async {
28303            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
28304                tokio::time::sleep(Duration::from_millis(1)).await;
28305            }
28306        })
28307        .await
28308        .expect("poll started");
28309        run.abort();
28310        assert!(run.await.expect_err("cancelled run").is_cancelled());
28311        tokio::time::sleep(Duration::from_millis(250)).await;
28312        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
28313    }
28314
28315    #[tokio::test]
28316    async fn query_protocol_rejection_from_older_server_is_typed() {
28317        let server = MockWorkerServer::reject_query_protocol();
28318        let client = Client::builder(server.base_url())
28319            .timeout(Duration::from_secs(2))
28320            .build()
28321            .expect("client");
28322
28323        let error = client
28324            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
28325            .await
28326            .expect_err("server below query protocol floor must reject");
28327        let Error::Protocol(failure) = error else {
28328            panic!("expected typed protocol failure");
28329        };
28330
28331        assert_eq!(failure.status, 400);
28332        assert_eq!(failure.reason, "unsupported_protocol_version");
28333        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
28334        assert_eq!(
28335            failure.requested_version.as_deref(),
28336            Some(WORKER_PROTOCOL_VERSION)
28337        );
28338        assert_eq!(
28339            server
28340                .worker_protocol_for("/api/worker/query-tasks/poll")
28341                .as_deref(),
28342            Some(WORKER_PROTOCOL_VERSION)
28343        );
28344    }
28345
28346    #[tokio::test]
28347    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
28348        let server = MockWorkerServer::reject_query_protocol();
28349        let client = Client::builder(server.base_url())
28350            .timeout(Duration::from_secs(2))
28351            .build()
28352            .expect("client");
28353        let mut worker = Worker::new(client, "rust-workers")
28354            .worker_id("baseline-worker")
28355            .poll_timeout(Duration::from_millis(10));
28356
28357        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
28358            Ok(Value::Null)
28359        });
28360
28361        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
28362        assert_eq!(
28363            server
28364                .worker_protocol_for("/api/worker/workflow-tasks/poll")
28365                .as_deref(),
28366            Some(WORKER_PROTOCOL_VERSION)
28367        );
28368        assert_eq!(
28369            server.worker_protocol_for("/api/worker/query-tasks/poll"),
28370            None,
28371            "a worker without query handlers must not use the query-task endpoint"
28372        );
28373    }
28374
28375    #[tokio::test]
28376    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
28377        let server = MockWorkerServer::reject_query_completion();
28378        let client = Client::builder(server.base_url())
28379            .timeout(Duration::from_secs(2))
28380            .build()
28381            .expect("client");
28382
28383        let error = client
28384            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
28385            .await
28386            .expect_err("expired completion must be rejected");
28387        let Error::QueryFailed(failure) = error else {
28388            panic!("expected typed query failure");
28389        };
28390        assert_eq!(failure.status, 409);
28391        assert_eq!(failure.reason, "query_task_timed_out");
28392
28393        let mut worker = Worker::new(client, "rust-workers")
28394            .worker_id("late-worker")
28395            .poll_timeout(Duration::from_millis(10));
28396        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28397        worker.register_query(
28398            "counter",
28399            "current",
28400            |_ctx, _args| async move { Ok(json!(8)) },
28401        );
28402
28403        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
28404        assert_eq!(
28405            worker
28406                .run_once()
28407                .await
28408                .expect("worker continues after late completion"),
28409            0
28410        );
28411        assert_eq!(
28412            server.request_count("/api/worker/query-tasks/query-late/complete"),
28413            2
28414        );
28415        assert_eq!(
28416            server.request_count("/api/worker/query-tasks/query-late/fail"),
28417            0,
28418            "a server completion rejection must not be reported as an encoding failure"
28419        );
28420    }
28421
28422    #[tokio::test]
28423    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
28424        let server = MockWorkerServer::start();
28425        let client = Client::builder(server.base_url())
28426            .timeout(Duration::from_secs(2))
28427            .build()
28428            .expect("client");
28429        let mut worker = Worker::new(client, "rust-workers")
28430            .worker_id("joined-worker")
28431            .poll_timeout(Duration::from_millis(10));
28432        worker.register_workflow(
28433            "joined.workflow",
28434            |_ctx, _input| async move { Ok(Value::Null) },
28435        );
28436        worker.register_activity(
28437            "joined.activity",
28438            |_ctx, _input| async move { Ok(Value::Null) },
28439        );
28440        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
28441            Ok(Value::Null)
28442        });
28443
28444        worker
28445            .run_until(tokio::time::sleep(Duration::from_millis(20)))
28446            .await
28447            .expect("normal shutdown");
28448
28449        let deregistration_path = "/api/worker/registrations/mock-worker";
28450        assert_eq!(server.request_count(deregistration_path), 1);
28451        for poll_path in [
28452            "/api/worker/workflow-tasks/poll",
28453            "/api/worker/activity-tasks/poll",
28454            "/api/worker/query-tasks/poll",
28455        ] {
28456            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
28457        }
28458        assert_eq!(
28459            server.captured_paths().last().map(String::as_str),
28460            Some(deregistration_path),
28461            "deregistration must start only after every poller has joined"
28462        );
28463    }
28464
28465    #[tokio::test]
28466    async fn registration_failure_does_not_deregister() {
28467        let server = MockWorkerServer::rejected_registration();
28468        let client = Client::builder(server.base_url())
28469            .timeout(Duration::from_secs(2))
28470            .build()
28471            .expect("client");
28472        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
28473
28474        let error = worker
28475            .run_until(async {})
28476            .await
28477            .expect_err("registration must fail");
28478        assert!(matches!(
28479            error,
28480            Error::Http {
28481                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28482                ..
28483            }
28484        ));
28485        assert!(server
28486            .captured_paths()
28487            .iter()
28488            .all(|path| !path.starts_with("/api/worker/registrations/")));
28489    }
28490
28491    #[tokio::test]
28492    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
28493        let server = MockWorkerServer::rejected_registration_protocol();
28494        let client = Client::builder(server.base_url())
28495            .timeout(Duration::from_secs(2))
28496            .build()
28497            .expect("client");
28498        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
28499
28500        let error = worker
28501            .run_until(async {})
28502            .await
28503            .expect_err("a protocol 1.16 server must reject this worker");
28504        let Error::Protocol(failure) = error else {
28505            panic!("expected typed protocol rejection");
28506        };
28507        assert_eq!(failure.reason, "unsupported_protocol_version");
28508        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
28509        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
28510        assert_eq!(
28511            server
28512                .worker_protocol_for("/api/worker/register")
28513                .as_deref(),
28514            Some(WORKER_PROTOCOL_VERSION)
28515        );
28516    }
28517
28518    #[tokio::test]
28519    async fn declined_registration_does_not_deregister() {
28520        let server = MockWorkerServer::declined_registration();
28521        let client = Client::builder(server.base_url())
28522            .timeout(Duration::from_secs(2))
28523            .build()
28524            .expect("client");
28525        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
28526
28527        let error = worker
28528            .run_until(async {})
28529            .await
28530            .expect_err("declined registration must fail");
28531        assert!(matches!(error, Error::WorkerLoop(_)));
28532        assert!(error.to_string().contains("was not accepted"));
28533        assert!(server
28534            .captured_paths()
28535            .iter()
28536            .all(|path| !path.starts_with("/api/worker/registrations/")));
28537    }
28538
28539    #[tokio::test]
28540    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
28541        let server = MockWorkerServer::rejected_deregistration();
28542        let client = Client::builder(server.base_url())
28543            .timeout(Duration::from_secs(2))
28544            .build()
28545            .expect("client");
28546        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
28547
28548        let error = worker
28549            .run_until(async {})
28550            .await
28551            .expect_err("deregistration must fail");
28552        assert!(matches!(
28553            error,
28554            Error::Http {
28555                status: reqwest::StatusCode::FORBIDDEN,
28556                ..
28557            }
28558        ));
28559        assert_eq!(
28560            server.request_count("/api/worker/registrations/mock-worker"),
28561            1
28562        );
28563    }
28564
28565    #[tokio::test]
28566    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
28567        let server = MockWorkerServer::rejected_deregistration_protocol();
28568        let client = Client::builder(server.base_url())
28569            .timeout(Duration::from_secs(2))
28570            .build()
28571            .expect("client");
28572        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
28573
28574        let error = worker
28575            .run_until(async {})
28576            .await
28577            .expect_err("protocol rejection must fail shutdown");
28578        let Error::Protocol(failure) = error else {
28579            panic!("expected typed protocol failure");
28580        };
28581        assert_eq!(failure.reason, "unsupported_protocol_version");
28582        assert_eq!(
28583            failure.requested_version.as_deref(),
28584            Some(WORKER_PROTOCOL_VERSION)
28585        );
28586        assert_eq!(
28587            server.request_count("/api/worker/registrations/mock-worker"),
28588            1
28589        );
28590    }
28591
28592    #[tokio::test]
28593    async fn primary_poller_error_retains_deregistration_failure_context() {
28594        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
28595        let client = Client::builder(server.base_url())
28596            .timeout(Duration::from_secs(2))
28597            .build()
28598            .expect("client");
28599        let mut worker = Worker::new(client, "rust-workers")
28600            .worker_id("combined-failure")
28601            .poll_timeout(Duration::from_millis(10));
28602        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
28603            Ok(Value::Null)
28604        });
28605
28606        let error = worker
28607            .run()
28608            .await
28609            .expect_err("worker and cleanup must fail");
28610        let summary = error.to_string();
28611        assert!(summary.contains("authentication_failed"));
28612        assert!(summary.contains("worker cannot deregister"));
28613        let Error::WorkerShutdown {
28614            primary,
28615            deregistration,
28616        } = error
28617        else {
28618            panic!("expected combined worker shutdown error");
28619        };
28620        assert!(matches!(
28621            *primary,
28622            Error::Http {
28623                status: reqwest::StatusCode::UNAUTHORIZED,
28624                ..
28625            }
28626        ));
28627        assert!(matches!(
28628            *deregistration,
28629            Error::Http {
28630                status: reqwest::StatusCode::FORBIDDEN,
28631                ..
28632            }
28633        ));
28634        assert_eq!(
28635            server.request_count("/api/worker/registrations/mock-worker"),
28636            1
28637        );
28638    }
28639
28640    #[tokio::test]
28641    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
28642        let server = MockWorkerServer::start();
28643        let client = Client::builder(server.base_url())
28644            .timeout(Duration::from_secs(2))
28645            .build()
28646            .expect("client");
28647        let mut worker = Worker::new(client, "rust-workers")
28648            .worker_id("activity-only-worker")
28649            .poll_timeout(Duration::from_millis(10));
28650
28651        worker.register_activity(
28652            "activity.only",
28653            |_ctx, _args| async move { Ok(Value::Null) },
28654        );
28655
28656        worker.run_until(async {}).await.expect("run worker");
28657    }
28658
28659    #[tokio::test]
28660    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
28661        let server = MockWorkerServer::start();
28662        let client = Client::builder(server.base_url())
28663            .timeout(Duration::from_secs(2))
28664            .build()
28665            .expect("client");
28666        let mut worker = Worker::new(client, "rust-workers")
28667            .worker_id("workflow-only-worker")
28668            .poll_timeout(Duration::from_millis(10));
28669
28670        worker.register_workflow(
28671            "workflow.only",
28672            |_ctx, _input| async move { Ok(Value::Null) },
28673        );
28674
28675        worker.run_until(async {}).await.expect("run worker");
28676    }
28677
28678    #[tokio::test]
28679    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
28680        let server = MockWorkerServer::start();
28681        let client = Client::builder(server.base_url())
28682            .timeout(Duration::from_secs(2))
28683            .build()
28684            .expect("client");
28685        let observations = Arc::new(Mutex::new(Vec::new()));
28686        let observed = Arc::clone(&observations);
28687        let mut worker = Worker::new(client, "rust-workers")
28688            .worker_id("observed-heartbeat-worker")
28689            .poll_timeout(Duration::from_millis(10))
28690            .on_worker_heartbeat(move |observation| {
28691                observed
28692                    .lock()
28693                    .expect("heartbeat observations")
28694                    .push(observation.clone());
28695            });
28696
28697        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
28698            Ok(Value::Null)
28699        });
28700        let acknowledged = Arc::clone(&observations);
28701        worker
28702            .run_until(async move {
28703                tokio::time::timeout(Duration::from_secs(2), async move {
28704                    loop {
28705                        if !acknowledged
28706                            .lock()
28707                            .expect("heartbeat observations")
28708                            .is_empty()
28709                        {
28710                            break;
28711                        }
28712                        tokio::time::sleep(Duration::from_millis(1)).await;
28713                    }
28714                })
28715                .await
28716                .expect("heartbeat acknowledgement within timeout");
28717            })
28718            .await
28719            .expect("run worker");
28720
28721        let observations = observations.lock().expect("heartbeat observations");
28722        let first = observations.first().expect("heartbeat acknowledgement");
28723        assert_eq!(first.worker_id, "observed-heartbeat-worker");
28724        assert_eq!(first.task_queue, "rust-workers");
28725        assert!(first.acknowledged_at_unix_millis > 0);
28726        assert_eq!(first.acknowledgement, json!({}));
28727    }
28728
28729    #[tokio::test]
28730    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
28731        let server = MockWorkerServer::delayed_heartbeat_worker();
28732        let client = Client::builder(server.base_url())
28733            .timeout(Duration::from_secs(3))
28734            .build()
28735            .expect("client");
28736        let observations = Arc::new(Mutex::new(Vec::new()));
28737        let observed = Arc::clone(&observations);
28738        let mut worker = Worker::new(client, "rust-snapshot-workers")
28739            .worker_id("rust-snapshot-worker")
28740            .poll_timeout(Duration::from_millis(10))
28741            .on_worker_heartbeat(move |observation| {
28742                observed
28743                    .lock()
28744                    .expect("heartbeat observations")
28745                    .push(observation.clone());
28746            });
28747
28748        worker.register_workflow("snapshot", |ctx, _input| async move {
28749            ctx.wait_signal("finish").await?;
28750            Ok(json!({"status": "finished"}))
28751        });
28752        worker.register_query("snapshot", "current", |ctx, _args| async move {
28753            Ok(json!(ctx
28754                .signals("increment")
28755                .iter()
28756                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28757                .sum::<i64>()))
28758        });
28759        worker.register_activity("cancel-aware", |_ctx, _args| async move {
28760            Ok(json!({"late": "completion"}))
28761        });
28762
28763        worker
28764            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
28765            .await
28766            .expect("delayed heartbeat must allow a clean worker shutdown");
28767
28768        let observations = observations.lock().expect("heartbeat observations");
28769        assert!(
28770            observations.len() >= 3,
28771            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
28772        );
28773        assert!(
28774            observations.windows(2).all(|pair| {
28775                pair[1].acknowledged_at_unix_millis
28776                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28777                    >= 850
28778            }),
28779            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
28780        );
28781        drop(observations);
28782
28783        let heartbeat_times = server.request_times("/api/worker/heartbeat");
28784        let delayed_request_at = *heartbeat_times
28785            .get(1)
28786            .expect("intentionally delayed heartbeat request");
28787        let delay_window_start = delayed_request_at + Duration::from_millis(100);
28788        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
28789        for path in [
28790            "/api/worker/workflow-tasks/poll",
28791            "/api/worker/activity-tasks/poll",
28792            "/api/worker/query-tasks/poll",
28793        ] {
28794            assert!(
28795                server
28796                    .request_times(path)
28797                    .iter()
28798                    .any(|received_at| *received_at >= delay_window_start
28799                        && *received_at <= delay_window_end),
28800                "{path} must keep polling while a heartbeat acknowledgement is delayed"
28801            );
28802        }
28803        assert!(
28804            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
28805            "workflow work must be settled"
28806        );
28807        assert!(
28808            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
28809            "activity work must be settled"
28810        );
28811        assert!(
28812            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
28813            "query work must be settled"
28814        );
28815    }
28816
28817    #[tokio::test]
28818    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
28819        let server = MockWorkerServer::heartbeat_retry_worker();
28820        let client = Client::builder(server.base_url())
28821            .timeout(Duration::from_secs(2))
28822            .build()
28823            .expect("client");
28824        let observations = Arc::new(Mutex::new(Vec::new()));
28825        let observed = Arc::clone(&observations);
28826        let worker = Worker::new(client, "rust-workers")
28827            .worker_id("heartbeat-retry-worker")
28828            .retry_policy(WorkerRetryPolicy {
28829                max_retries: 1,
28830                initial_backoff: Duration::from_millis(300),
28831                max_backoff: Duration::from_millis(300),
28832            })
28833            .on_worker_heartbeat(move |observation| {
28834                observed
28835                    .lock()
28836                    .expect("heartbeat observations")
28837                    .push(observation.clone());
28838            });
28839
28840        worker
28841            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
28842            .await
28843            .expect("retryable heartbeat failure must remain bounded and recover");
28844
28845        let observations = observations.lock().expect("heartbeat observations");
28846        assert!(observations.len() >= 3, "heartbeat retry must recover");
28847        assert!(
28848            observations.windows(2).all(|pair| {
28849                pair[1]
28850                    .acknowledged_at_unix_millis
28851                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28852                    >= 850
28853            }),
28854            "a successful retry must start a fresh advertised cadence: {observations:?}"
28855        );
28856        assert_eq!(
28857            server.request_count("/api/worker/heartbeat"),
28858            observations.len() + 1,
28859            "one retryable failure must add exactly one bounded request"
28860        );
28861    }
28862
28863    #[tokio::test]
28864    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
28865        let server = MockWorkerServer::waiting_query_worker();
28866        let client = Client::builder(server.base_url())
28867            .timeout(Duration::from_secs(2))
28868            .build()
28869            .expect("client");
28870        let observations = Arc::new(Mutex::new(Vec::new()));
28871        let observed = Arc::clone(&observations);
28872        let mut worker = Worker::new(client, "rust-snapshot-workers")
28873            .worker_id("rust-snapshot-worker")
28874            .poll_timeout(Duration::from_millis(10))
28875            .on_worker_heartbeat(move |observation| {
28876                observed
28877                    .lock()
28878                    .expect("heartbeat observations")
28879                    .push(observation.clone());
28880            });
28881
28882        worker.register_workflow("snapshot", |ctx, _input| async move {
28883            ctx.wait_signal("finish").await?;
28884            Ok(json!({"status": "finished"}))
28885        });
28886        worker.register_query("snapshot", "current", |ctx, _args| async move {
28887            let current = ctx
28888                .signals("increment")
28889                .iter()
28890                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28891                .sum::<i64>();
28892            Ok(json!(current))
28893        });
28894        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
28895        worker
28896            .declare_workflow_signals("snapshot", &["finish"])
28897            .expect("declare finish signal");
28898
28899        worker
28900            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
28901            .await
28902            .expect("pending workflow and query poller must remain live until shutdown");
28903
28904        assert!(
28905            observations.lock().expect("heartbeat observations").len() >= 4,
28906            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
28907        );
28908        assert!(
28909            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
28910            "workflow polling must continue after empty replay acknowledgements"
28911        );
28912        assert!(
28913            server.request_count("/api/worker/query-tasks/poll") >= 2,
28914            "query polling must continue after serving the current query"
28915        );
28916        assert_eq!(
28917            server.request_body("/api/worker/register")["capabilities"],
28918            json!([
28919                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
28920                DURABLE_SELECTION_CAPABILITY,
28921                MEMO_UPSERTS_CAPABILITY,
28922                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
28923                QUERY_TASKS_CAPABILITY,
28924                WORKFLOW_UPDATES_CAPABILITY,
28925                MESSAGE_STREAMS_CAPABILITY
28926            ])
28927        );
28928        assert_eq!(
28929            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
28930            json!({
28931                "queries": ["current"],
28932                "query_contracts": [{
28933                    "name": "current",
28934                    "parameters": [{
28935                        "name": "args", "position": 0, "required": false,
28936                        "variadic": true, "type": null, "allows_null": true,
28937                        "default_available": false, "default": null,
28938                    }],
28939                }],
28940                "signals": ["finish"],
28941                "signal_contracts": [{
28942                    "name": "finish",
28943                    "parameters": [{
28944                        "name": "args", "position": 0, "required": false,
28945                        "variadic": true, "type": null, "allows_null": true,
28946                        "default_available": false, "default": null,
28947                    }],
28948                }],
28949                "updates": ["replace"],
28950                "update_contracts": [{
28951                    "name": "replace",
28952                    "parameters": [{
28953                        "name": "args", "position": 0, "required": false,
28954                        "variadic": true, "type": null, "allows_null": true,
28955                        "default_available": false, "default": null,
28956                    }],
28957                }],
28958                "update_validators": [],
28959            })
28960        );
28961
28962        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
28963        assert_eq!(
28964            opened["commands"],
28965            json!([{
28966                "type": "open_signal_wait",
28967                "signal_name": "finish",
28968            }])
28969        );
28970
28971        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
28972            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
28973            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
28974            let failure = server.request_body(&fail_path);
28975            assert_eq!(
28976                failure["failure"]["type"],
28977                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
28978            );
28979            assert_eq!(server.request_count(&completion_path), 0);
28980        }
28981
28982        let query_completion =
28983            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
28984        assert_eq!(query_completion["result"], json!(8));
28985
28986        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
28987        assert_eq!(
28988            server.request_count(terminal_path),
28989            1,
28990            "the matching signal must settle the workflow exactly once"
28991        );
28992        let terminal = server.request_body(terminal_path);
28993        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
28994        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
28995        assert_eq!(
28996            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
28997                .expect("terminal workflow result"),
28998            json!({"status": "finished"})
28999        );
29000    }
29001
29002    #[tokio::test]
29003    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
29004        let server = MockWorkerServer::transient_worker_failures();
29005        let client = Client::builder(server.base_url())
29006            .timeout(Duration::from_secs(2))
29007            .build()
29008            .expect("client");
29009        let mut worker = Worker::new(client, "rust-workers")
29010            .worker_id("retry-worker")
29011            .poll_timeout(Duration::from_millis(10))
29012            .retry_policy(WorkerRetryPolicy {
29013                max_retries: 2,
29014                initial_backoff: Duration::from_millis(1),
29015                max_backoff: Duration::from_millis(1),
29016            });
29017        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29018        worker.register_activity(
29019            "counter.activity",
29020            |_ctx, _input| async move { Ok(Value::Null) },
29021        );
29022        worker.register_query(
29023            "counter",
29024            "current",
29025            |_ctx, _args| async move { Ok(json!(8)) },
29026        );
29027
29028        worker
29029            .run_until(tokio::time::sleep(Duration::from_millis(75)))
29030            .await
29031            .expect("transient failures must not stop the worker");
29032
29033        for path in [
29034            "/api/worker/heartbeat",
29035            "/api/worker/workflow-tasks/poll",
29036            "/api/worker/activity-tasks/poll",
29037            "/api/worker/query-tasks/poll",
29038        ] {
29039            assert!(
29040                server.request_count(path) >= 2,
29041                "{path} must continue after its transient failure"
29042            );
29043        }
29044    }
29045
29046    #[tokio::test]
29047    async fn worker_continues_after_long_poll_capacity_backpressure() {
29048        let server = MockWorkerServer::capacity_limited_activity_poll();
29049        let client = Client::builder(server.base_url())
29050            .timeout(Duration::from_secs(2))
29051            .build()
29052            .expect("client");
29053        let mut worker = Worker::new(client, "rust-workers")
29054            .worker_id("capacity-worker")
29055            .poll_timeout(Duration::from_millis(10))
29056            .retry_policy(WorkerRetryPolicy {
29057                max_retries: 0,
29058                initial_backoff: Duration::from_millis(1),
29059                max_backoff: Duration::from_millis(1),
29060            });
29061        worker.register_activity("capacity.activity", |_ctx, _input| async move {
29062            Ok(json!({"handled": true}))
29063        });
29064
29065        worker
29066            .run_until(tokio::time::sleep(Duration::from_millis(50)))
29067            .await
29068            .expect("capacity backpressure must not stop the worker");
29069
29070        assert!(
29071            server.request_count("/api/worker/activity-tasks/poll") >= 2,
29072            "the activity poller must continue after capacity backpressure"
29073        );
29074        assert_eq!(
29075            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
29076            1,
29077            "the worker must complete work returned after capacity recovers"
29078        );
29079    }
29080
29081    #[test]
29082    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
29083        let capacity = Error::Http {
29084            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29085            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
29086        };
29087        assert_eq!(
29088            worker_poll_capacity_retry_after(&capacity),
29089            Some(Duration::from_secs(3))
29090        );
29091
29092        let rejected_capacity = Error::Http {
29093            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29094            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
29095        };
29096        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
29097        assert!(!worker_operation_is_retryable(&rejected_capacity));
29098
29099        let ordinary_rate_limit = Error::Http {
29100            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29101            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
29102                .to_string(),
29103        };
29104        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
29105        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
29106    }
29107
29108    #[tokio::test]
29109    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
29110        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29111            poll_failures_per_path: 8,
29112            heartbeat_failures: 8,
29113            ..MockWorkerBehavior::default()
29114        });
29115        let client = Client::builder(server.base_url())
29116            .timeout(Duration::from_secs(2))
29117            .build()
29118            .expect("client");
29119        let acknowledgements = Arc::new(AtomicUsize::new(0));
29120        let observed = Arc::clone(&acknowledgements);
29121        let mut worker = Worker::new(client, "rust-workers")
29122            .recover_transient_outages(true)
29123            .poll_timeout(Duration::from_millis(10))
29124            .retry_policy(WorkerRetryPolicy {
29125                max_retries: 2,
29126                initial_backoff: Duration::from_millis(2),
29127                max_backoff: Duration::from_millis(5),
29128            })
29129            .on_worker_heartbeat(move |_| {
29130                observed.fetch_add(1, Ordering::SeqCst);
29131            });
29132        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29133        worker.register_activity(
29134            "counter.activity",
29135            |_ctx, _input| async move { Ok(Value::Null) },
29136        );
29137        worker.register_query("counter", "current", |_ctx, _args| async move {
29138            Ok(Value::Null)
29139        });
29140
29141        worker
29142            .run_until(tokio::time::sleep(Duration::from_millis(500)))
29143            .await
29144            .expect("a recoverable outage must not stop the service worker");
29145
29146        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
29147        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
29148        for path in [
29149            "/api/worker/workflow-tasks/poll",
29150            "/api/worker/activity-tasks/poll",
29151            "/api/worker/query-tasks/poll",
29152        ] {
29153            let bodies = server.request_bodies(path);
29154            assert!(bodies.len() >= 10, "{path} must resume after recovery");
29155            let first = &bodies[0]["poll_request_id"];
29156            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
29157            for body in &bodies[..9] {
29158                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
29159            }
29160            assert_ne!(&bodies[9]["poll_request_id"], first);
29161            let times = server.request_times(path);
29162            for pair in times[..9].windows(2) {
29163                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
29164            }
29165        }
29166    }
29167
29168    #[tokio::test]
29169    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
29170        for heartbeat_outage in [false, true] {
29171            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29172                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
29173                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
29174                ..MockWorkerBehavior::default()
29175            });
29176            let client = Client::builder(server.base_url()).build().expect("client");
29177            let mut worker = Worker::new(client, "rust-workers")
29178                .recover_transient_outages(true)
29179                .retry_policy(WorkerRetryPolicy {
29180                    max_retries: 1,
29181                    initial_backoff: Duration::from_secs(5),
29182                    max_backoff: Duration::from_secs(5),
29183                });
29184            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29185            let started = Instant::now();
29186            worker
29187                .run_until(tokio::time::sleep(Duration::from_millis(200)))
29188                .await
29189                .expect("shutdown during an outage is a normal stop");
29190            assert!(started.elapsed() < Duration::from_secs(1));
29191            let path = if heartbeat_outage {
29192                "/api/worker/heartbeat"
29193            } else {
29194                "/api/worker/workflow-tasks/poll"
29195            };
29196            assert_eq!(server.request_count(path), 1);
29197            assert_eq!(
29198                server.request_count("/api/worker/registrations/mock-worker"),
29199                1
29200            );
29201        }
29202    }
29203
29204    #[tokio::test]
29205    async fn worker_outage_recovery_keeps_run_once_bounded() {
29206        let server = MockWorkerServer::unavailable_polls();
29207        let client = Client::builder(server.base_url()).build().expect("client");
29208        let mut worker = Worker::new(client, "rust-workers")
29209            .recover_transient_outages(true)
29210            .retry_policy(WorkerRetryPolicy {
29211                max_retries: 2,
29212                initial_backoff: Duration::from_millis(1),
29213                max_backoff: Duration::from_millis(1),
29214            });
29215        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29216        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
29217        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
29218    }
29219
29220    #[tokio::test]
29221    async fn worker_outage_recovery_respects_disabled_retries() {
29222        let server = MockWorkerServer::unavailable_polls();
29223        let client = Client::builder(server.base_url()).build().expect("client");
29224        let mut worker = Worker::new(client, "rust-workers")
29225            .recover_transient_outages(true)
29226            .retry_policy(WorkerRetryPolicy {
29227                max_retries: 0,
29228                ..WorkerRetryPolicy::default()
29229            });
29230        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29231        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
29232        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29233    }
29234
29235    #[tokio::test]
29236    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
29237        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29238            heartbeat_failures: usize::MAX,
29239            unauthorized_polls: true,
29240            ..MockWorkerBehavior::default()
29241        });
29242        let client = Client::builder(server.base_url()).build().expect("client");
29243        let mut worker = Worker::new(client, "rust-workers")
29244            .recover_transient_outages(true)
29245            .retry_policy(WorkerRetryPolicy {
29246                max_retries: 1,
29247                initial_backoff: Duration::from_secs(5),
29248                max_backoff: Duration::from_secs(5),
29249            });
29250        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29251        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
29252            .await
29253            .expect("fatal poll errors must interrupt heartbeat recovery")
29254            .expect_err("authentication failure is terminal");
29255        assert!(
29256            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
29257        );
29258        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29259    }
29260
29261    #[tokio::test]
29262    async fn worker_bounds_transport_retries() {
29263        let server = MockWorkerServer::unavailable_polls();
29264        let client = Client::builder(server.base_url())
29265            .timeout(Duration::from_secs(2))
29266            .build()
29267            .expect("client");
29268        let mut worker = Worker::new(client, "rust-workers")
29269            .worker_id("bounded-retry-worker")
29270            .poll_timeout(Duration::from_millis(10))
29271            .retry_policy(WorkerRetryPolicy {
29272                max_retries: 2,
29273                initial_backoff: Duration::from_millis(1),
29274                max_backoff: Duration::from_millis(1),
29275            });
29276        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29277
29278        let error = worker.run().await.expect_err("retry bound must terminate");
29279        assert!(matches!(error, Error::Transport(_)));
29280        assert_eq!(
29281            server.request_count("/api/worker/workflow-tasks/poll"),
29282            3,
29283            "one initial request plus exactly two retries"
29284        );
29285    }
29286
29287    #[tokio::test]
29288    async fn worker_retry_policy_can_disable_poll_retries() {
29289        let server = MockWorkerServer::unavailable_polls();
29290        let client = Client::builder(server.base_url())
29291            .timeout(Duration::from_secs(2))
29292            .build()
29293            .expect("client");
29294        let mut worker = Worker::new(client, "rust-workers")
29295            .worker_id("no-retry-worker")
29296            .poll_timeout(Duration::from_millis(10))
29297            .retry_policy(WorkerRetryPolicy {
29298                max_retries: 0,
29299                initial_backoff: Duration::from_millis(1),
29300                max_backoff: Duration::from_millis(1),
29301            });
29302        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29303
29304        let error = worker
29305            .run_once()
29306            .await
29307            .expect_err("disabled retries must return the first transport failure");
29308        assert!(matches!(error, Error::Transport(_)));
29309        assert_eq!(
29310            server.request_count("/api/worker/workflow-tasks/poll"),
29311            1,
29312            "max_retries=0 must send only the initial request"
29313        );
29314    }
29315
29316    #[tokio::test]
29317    async fn worker_does_not_retry_authentication_failures() {
29318        let server = MockWorkerServer::unauthorized_polls();
29319        let client = Client::builder(server.base_url())
29320            .timeout(Duration::from_secs(2))
29321            .build()
29322            .expect("client");
29323        let mut worker = Worker::new(client, "rust-workers")
29324            .worker_id("unauthorized-worker")
29325            .recover_transient_outages(true)
29326            .poll_timeout(Duration::from_millis(10));
29327        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29328
29329        let error = worker
29330            .run()
29331            .await
29332            .expect_err("authentication must terminate");
29333        let Error::Http { status, body } = error else {
29334            panic!("expected stable HTTP authentication error");
29335        };
29336        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
29337        assert!(body.contains("authentication_failed"));
29338        assert_eq!(
29339            server.request_count("/api/worker/workflow-tasks/poll"),
29340            1,
29341            "authentication failures must not be retried"
29342        );
29343    }
29344
29345    #[test]
29346    fn duplicate_registration_keeps_the_original_workflow() {
29347        let client = Client::new("http://127.0.0.1:9").expect("client");
29348        let mut worker = Worker::new(client, "registration-tests");
29349        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29350        let original = Arc::clone(&worker.workflows["same"].execute);
29351        worker
29352            .set_workflow_definition_sources("same", &["first workflow source"])
29353            .expect("source identity");
29354        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
29355        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
29356        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
29357        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
29358    }
29359
29360    #[test]
29361    fn duplicate_registration_keeps_the_original_activity() {
29362        let client = Client::new("http://127.0.0.1:9").expect("client");
29363        let mut worker = Worker::new(client, "registration-tests");
29364        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
29365        let original = Arc::clone(&worker.activities["same"]);
29366        worker.register_activity_avro_value("same", |_ctx, _input| async {
29367            Ok(AvroValue::String("second".into()))
29368        });
29369        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
29370    }
29371
29372    #[test]
29373    fn duplicate_registration_keeps_original_query_and_update_handlers() {
29374        let client = Client::new("http://127.0.0.1:9").expect("client");
29375        let mut worker = Worker::new(client, "registration-tests");
29376        worker.register_query("orders", "same", |_ctx, _input| async {
29377            Ok(json!("first"))
29378        });
29379        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
29380            panic!("snapshot query");
29381        };
29382        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
29383            Ok(json!("second"))
29384        });
29385        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
29386            panic!("duplicate replaced the query adapter");
29387        };
29388        assert!(Arc::ptr_eq(&original, retained));
29389        worker.register_update("orders", "same", |_ctx, _input| async {
29390            Ok(json!("first"))
29391        });
29392        let original = Arc::clone(&worker.updates["orders"]["same"]);
29393        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
29394            Ok(AvroValue::Null)
29395        });
29396        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
29397    }
29398
29399    #[tokio::test]
29400    async fn duplicate_registration_fails_before_server_contact() {
29401        let server = MockWorkerServer::start();
29402        let client = Client::builder(server.base_url()).build().expect("client");
29403        let mut worker =
29404            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
29405        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29406        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
29407        let error = worker
29408            .run_once()
29409            .await
29410            .expect_err("ambiguous worker must not poll");
29411        assert!(
29412            error.to_string().contains("duplicate_registration"),
29413            "{error}"
29414        );
29415        assert!(server.requests.lock().expect("requests").is_empty());
29416    }
29417
29418    #[derive(Clone, Debug)]
29419    struct CapturedRequest {
29420        headers: String,
29421        method: String,
29422        path: String,
29423        authorization: Option<String>,
29424        namespace: Option<String>,
29425        worker_protocol: Option<String>,
29426        control_protocol: Option<String>,
29427        body: String,
29428        received_at: Instant,
29429    }
29430
29431    struct MockWorkerServer {
29432        addr: SocketAddr,
29433        stop: Arc<AtomicBool>,
29434        requests: Arc<Mutex<Vec<CapturedRequest>>>,
29435        thread: Option<thread::JoinHandle<()>>,
29436    }
29437
29438    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
29439
29440    #[derive(Clone, Copy, Default)]
29441    struct MockWorkerBehavior {
29442        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
29443        request_override: Option<RequestOverride>,
29444        storage_refusals: usize,
29445        storage_path: Option<&'static str>,
29446        storage_unavailable: bool,
29447        storage_mid_poll: bool,
29448        storage_activity: bool,
29449        storage_query: bool,
29450        storage_wrong_poll_id: bool,
29451        reject_query_protocol: bool,
29452        reject_query_completion: bool,
29453        waiting_query_worker: bool,
29454        decline_registration: bool,
29455        complete_named_signal: bool,
29456        poll_failures_per_path: usize,
29457        long_poll_capacity_responses_per_path: usize,
29458        heartbeat_failures: usize,
29459        heartbeat_failure_request: Option<usize>,
29460        delayed_heartbeat_request: Option<usize>,
29461        heartbeat_response_delay: Duration,
29462        concurrent_requests: bool,
29463        unauthorized_polls: bool,
29464        reject_registration: bool,
29465        reject_registration_protocol: bool,
29466        reject_deregistration: bool,
29467        reject_deregistration_protocol: bool,
29468        cancelled_activity: bool,
29469        draining_polls: bool,
29470        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
29471        workflow_completion_status: Option<&'static str>,
29472        workflow_completion_body: Option<&'static str>,
29473    }
29474
29475    impl MockWorkerServer {
29476        fn start() -> Self {
29477            Self::start_with_behavior(MockWorkerBehavior::default())
29478        }
29479
29480        fn reject_query_protocol() -> Self {
29481            Self::start_with_behavior(MockWorkerBehavior {
29482                reject_query_protocol: true,
29483                ..MockWorkerBehavior::default()
29484            })
29485        }
29486
29487        fn reject_query_completion() -> Self {
29488            Self::start_with_behavior(MockWorkerBehavior {
29489                reject_query_completion: true,
29490                ..MockWorkerBehavior::default()
29491            })
29492        }
29493
29494        fn waiting_query_worker() -> Self {
29495            Self::start_with_behavior(MockWorkerBehavior {
29496                waiting_query_worker: true,
29497                complete_named_signal: true,
29498                ..MockWorkerBehavior::default()
29499            })
29500        }
29501
29502        fn transient_worker_failures() -> Self {
29503            Self::start_with_behavior(MockWorkerBehavior {
29504                poll_failures_per_path: 1,
29505                heartbeat_failures: 1,
29506                ..MockWorkerBehavior::default()
29507            })
29508        }
29509
29510        fn consecutive_poll_failures(count: usize) -> Self {
29511            Self::start_with_behavior(MockWorkerBehavior {
29512                poll_failures_per_path: count,
29513                ..MockWorkerBehavior::default()
29514            })
29515        }
29516
29517        fn capacity_limited_activity_poll() -> Self {
29518            Self::start_with_behavior(MockWorkerBehavior {
29519                long_poll_capacity_responses_per_path: 1,
29520                ..MockWorkerBehavior::default()
29521            })
29522        }
29523
29524        fn delayed_heartbeat_worker() -> Self {
29525            Self::start_with_behavior(MockWorkerBehavior {
29526                waiting_query_worker: true,
29527                delayed_heartbeat_request: Some(2),
29528                heartbeat_response_delay: Duration::from_millis(1_500),
29529                concurrent_requests: true,
29530                cancelled_activity: true,
29531                ..MockWorkerBehavior::default()
29532            })
29533        }
29534
29535        fn heartbeat_retry_worker() -> Self {
29536            Self::start_with_behavior(MockWorkerBehavior {
29537                waiting_query_worker: true,
29538                heartbeat_failure_request: Some(2),
29539                concurrent_requests: true,
29540                ..MockWorkerBehavior::default()
29541            })
29542        }
29543
29544        fn unavailable_polls() -> Self {
29545            Self::start_with_behavior(MockWorkerBehavior {
29546                poll_failures_per_path: usize::MAX,
29547                ..MockWorkerBehavior::default()
29548            })
29549        }
29550
29551        fn unauthorized_polls() -> Self {
29552            Self::start_with_behavior(MockWorkerBehavior {
29553                unauthorized_polls: true,
29554                ..MockWorkerBehavior::default()
29555            })
29556        }
29557
29558        fn rejected_registration() -> Self {
29559            Self::start_with_behavior(MockWorkerBehavior {
29560                reject_registration: true,
29561                ..MockWorkerBehavior::default()
29562            })
29563        }
29564
29565        fn rejected_registration_protocol() -> Self {
29566            Self::start_with_behavior(MockWorkerBehavior {
29567                reject_registration_protocol: true,
29568                ..MockWorkerBehavior::default()
29569            })
29570        }
29571
29572        fn declined_registration() -> Self {
29573            Self::start_with_behavior(MockWorkerBehavior {
29574                decline_registration: true,
29575                ..MockWorkerBehavior::default()
29576            })
29577        }
29578
29579        fn rejected_deregistration() -> Self {
29580            Self::start_with_behavior(MockWorkerBehavior {
29581                reject_deregistration: true,
29582                ..MockWorkerBehavior::default()
29583            })
29584        }
29585
29586        fn rejected_deregistration_protocol() -> Self {
29587            Self::start_with_behavior(MockWorkerBehavior {
29588                reject_deregistration_protocol: true,
29589                ..MockWorkerBehavior::default()
29590            })
29591        }
29592
29593        fn unauthorized_polls_and_rejected_deregistration() -> Self {
29594            Self::start_with_behavior(MockWorkerBehavior {
29595                unauthorized_polls: true,
29596                reject_deregistration: true,
29597                ..MockWorkerBehavior::default()
29598            })
29599        }
29600
29601        fn cancelled_activity() -> Self {
29602            Self::start_with_behavior(MockWorkerBehavior {
29603                cancelled_activity: true,
29604                ..MockWorkerBehavior::default()
29605            })
29606        }
29607
29608        fn draining_polls() -> Self {
29609            Self::start_with_behavior(MockWorkerBehavior {
29610                draining_polls: true,
29611                ..MockWorkerBehavior::default()
29612            })
29613        }
29614
29615        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
29616            Self::start_with_behavior(MockWorkerBehavior {
29617                invalid_task_payload_codec: Some(codec),
29618                ..MockWorkerBehavior::default()
29619            })
29620        }
29621
29622        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
29623            Self::start_with_behavior(MockWorkerBehavior {
29624                workflow_completion_status: Some(status),
29625                workflow_completion_body: Some(body),
29626                ..MockWorkerBehavior::default()
29627            })
29628        }
29629
29630        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
29631            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
29632            listener
29633                .set_nonblocking(true)
29634                .expect("configure mock listener");
29635            let addr = listener.local_addr().expect("mock server address");
29636            let stop = Arc::new(AtomicBool::new(false));
29637            let server_stop = Arc::clone(&stop);
29638            let requests = Arc::new(Mutex::new(Vec::new()));
29639            let server_requests = Arc::clone(&requests);
29640            let thread = thread::spawn(move || {
29641                let mut request_threads = Vec::new();
29642                while !server_stop.load(Ordering::SeqCst) {
29643                    match listener.accept() {
29644                        Ok((mut stream, _)) => {
29645                            if behavior.concurrent_requests {
29646                                let requests = Arc::clone(&server_requests);
29647                                request_threads.push(thread::spawn(move || {
29648                                    handle_mock_worker_request(&mut stream, &requests, behavior)
29649                                }));
29650                            } else {
29651                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
29652                            }
29653                        }
29654                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
29655                            let mut index = 0;
29656                            while index < request_threads.len() {
29657                                if request_threads[index].is_finished() {
29658                                    request_threads
29659                                        .swap_remove(index)
29660                                        .join()
29661                                        .expect("join mock request");
29662                                } else {
29663                                    index += 1;
29664                                }
29665                            }
29666                            thread::sleep(Duration::from_millis(5));
29667                        }
29668                        Err(_) => break,
29669                    }
29670                }
29671                for request_thread in request_threads {
29672                    request_thread.join().expect("join mock request");
29673                }
29674            });
29675
29676            Self {
29677                addr,
29678                stop,
29679                requests,
29680                thread: Some(thread),
29681            }
29682        }
29683
29684        fn base_url(&self) -> String {
29685            format!("http://{}", self.addr)
29686        }
29687
29688        fn worker_protocol_for(&self, path: &str) -> Option<String> {
29689            self.requests
29690                .lock()
29691                .expect("captured requests")
29692                .iter()
29693                .find(|request| request.path == path)
29694                .and_then(|request| request.worker_protocol.clone())
29695        }
29696
29697        fn control_protocol_for(&self, path: &str) -> Option<String> {
29698            self.requests
29699                .lock()
29700                .expect("captured requests")
29701                .iter()
29702                .find(|request| request.path == path)
29703                .and_then(|request| request.control_protocol.clone())
29704        }
29705
29706        fn method_for(&self, path: &str) -> Option<String> {
29707            self.requests
29708                .lock()
29709                .expect("captured requests")
29710                .iter()
29711                .find(|request| request.path == path)
29712                .map(|request| request.method.clone())
29713        }
29714
29715        fn authorization_for(&self, path: &str) -> Option<String> {
29716            self.requests
29717                .lock()
29718                .expect("captured requests")
29719                .iter()
29720                .find(|request| request.path == path)
29721                .and_then(|request| request.authorization.clone())
29722        }
29723
29724        fn namespace_for(&self, path: &str) -> Option<String> {
29725            self.requests
29726                .lock()
29727                .expect("captured requests")
29728                .iter()
29729                .find(|request| request.path == path)
29730                .and_then(|request| request.namespace.clone())
29731        }
29732
29733        fn request_count(&self, path: &str) -> usize {
29734            self.requests
29735                .lock()
29736                .expect("captured requests")
29737                .iter()
29738                .filter(|request| request.path == path)
29739                .count()
29740        }
29741
29742        fn captured_paths(&self) -> Vec<String> {
29743            self.requests
29744                .lock()
29745                .expect("captured requests")
29746                .iter()
29747                .map(|request| request.path.clone())
29748                .collect()
29749        }
29750
29751        fn request_times(&self, path: &str) -> Vec<Instant> {
29752            self.requests
29753                .lock()
29754                .expect("captured requests")
29755                .iter()
29756                .filter(|request| request.path == path)
29757                .map(|request| request.received_at)
29758                .collect()
29759        }
29760
29761        fn request_body(&self, path: &str) -> Value {
29762            let requests = self.requests.lock().expect("captured requests");
29763            let body = &requests
29764                .iter()
29765                .find(|request| request.path == path)
29766                .unwrap_or_else(|| panic!("missing request for {path}"))
29767                .body;
29768            serde_json::from_str(body).unwrap_or_else(|error| {
29769                panic!("invalid JSON request body for {path}: {error}: {body:?}")
29770            })
29771        }
29772
29773        fn request_bodies(&self, path: &str) -> Vec<Value> {
29774            self.requests
29775                .lock()
29776                .expect("captured requests")
29777                .iter()
29778                .filter(|request| request.path == path)
29779                .map(|request| {
29780                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
29781                        panic!(
29782                            "invalid JSON request body for {path}: {error}: {:?}",
29783                            request.body
29784                        )
29785                    })
29786                })
29787                .collect()
29788        }
29789    }
29790
29791    impl Drop for MockWorkerServer {
29792        fn drop(&mut self) {
29793            self.stop.store(true, Ordering::SeqCst);
29794            let _ = TcpStream::connect(self.addr);
29795
29796            if let Some(thread) = self.thread.take() {
29797                thread.join().expect("join mock server");
29798            }
29799        }
29800    }
29801
29802    fn handle_mock_worker_request(
29803        stream: &mut TcpStream,
29804        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
29805        behavior: MockWorkerBehavior,
29806    ) {
29807        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
29808        let mut buffer = [0_u8; 8192];
29809        let mut request = Vec::new();
29810
29811        loop {
29812            match stream.read(&mut buffer) {
29813                Ok(0) => break,
29814                Ok(read) => {
29815                    request.extend_from_slice(&buffer[..read]);
29816                    if mock_request_is_complete(&request) {
29817                        break;
29818                    }
29819                }
29820                Err(error)
29821                    if matches!(
29822                        error.kind(),
29823                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
29824                    ) =>
29825                {
29826                    break;
29827                }
29828                Err(_) => return,
29829            }
29830        }
29831
29832        let request = String::from_utf8_lossy(&request);
29833        let body = request
29834            .split_once("\r\n\r\n")
29835            .map(|(_, body)| body)
29836            .unwrap_or_default();
29837        let path = request
29838            .lines()
29839            .next()
29840            .and_then(|line| line.split_whitespace().nth(1))
29841            .unwrap_or_default();
29842        let method = request
29843            .lines()
29844            .next()
29845            .and_then(|line| line.split_whitespace().next())
29846            .unwrap_or_default();
29847        let authorization = request.lines().find_map(|line| {
29848            let (name, value) = line.split_once(':')?;
29849            name.eq_ignore_ascii_case("Authorization")
29850                .then(|| value.trim().to_string())
29851        });
29852        let namespace = request.lines().find_map(|line| {
29853            let (name, value) = line.split_once(':')?;
29854            name.eq_ignore_ascii_case("X-Namespace")
29855                .then(|| value.trim().to_string())
29856        });
29857        let worker_protocol = request.lines().find_map(|line| {
29858            let (name, value) = line.split_once(':')?;
29859            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
29860                .then(|| value.trim().to_string())
29861        });
29862        let control_protocol = request.lines().find_map(|line| {
29863            let (name, value) = line.split_once(':')?;
29864            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
29865                .then(|| value.trim().to_string())
29866        });
29867        let request_number = {
29868            let mut requests = requests.lock().expect("captured requests");
29869            requests.push(CapturedRequest {
29870                headers: request
29871                    .split_once("\r\n\r\n")
29872                    .map_or("", |(headers, _)| headers)
29873                    .to_owned(),
29874                method: method.to_string(),
29875                path: path.to_string(),
29876                authorization,
29877                namespace,
29878                worker_protocol: worker_protocol.clone(),
29879                control_protocol,
29880                body: body.to_string(),
29881                received_at: Instant::now(),
29882            });
29883            requests
29884                .iter()
29885                .filter(|request| request.path == path)
29886                .count()
29887        };
29888
29889        if let Some(response) = behavior
29890            .request_override
29891            .and_then(|handler| handler(path, body, request_number))
29892        {
29893            write_mock_response(stream, response.0, &response.1);
29894            return;
29895        }
29896        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
29897            write_mock_response(stream, response.0, &response.1);
29898            return;
29899        }
29900        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
29901            return;
29902        }
29903        let pressure_path = behavior
29904            .storage_path
29905            .is_some_and(|part| path.contains(part));
29906        let prior_failures = if path.ends_with("/poll") {
29907            behavior.poll_failures_per_path
29908        } else {
29909            0
29910        };
29911        if pressure_path
29912            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
29913        {
29914            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
29915            let poll_id = path
29916                .ends_with("/poll")
29917                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
29918            let mut refusal = storage_refusal(
29919                poll_id,
29920                behavior.storage_unavailable,
29921                behavior.storage_mid_poll,
29922            );
29923            if behavior.storage_wrong_poll_id {
29924                refusal["poll_request_id"] = json!("wrong-poll");
29925            }
29926            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
29927            return;
29928        }
29929        if path.contains("/storage-task/")
29930            || path.contains("/storage-activity/")
29931            || path.contains("/storage-query/")
29932        {
29933            write_mock_response(stream, "200 OK", "{}");
29934            return;
29935        }
29936        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
29937            write_mock_response(stream, "200 OK", &json!({"task":{
29938                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
29939                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
29940                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29941                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29942                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
29943            }}).to_string());
29944            return;
29945        }
29946        if behavior.storage_activity
29947            && path == "/api/worker/activity-tasks/poll"
29948            && request_number == 1
29949        {
29950            write_mock_response(stream, "200 OK", &json!({"task":{
29951                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
29952                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29953                "attempt_number":7, "lease_owner":"storage-worker"
29954            }}).to_string());
29955            return;
29956        }
29957
29958        if path == "/api/worker/register" {
29959            if behavior.reject_registration_protocol {
29960                write_mock_response(
29961                    stream,
29962                    "400 Bad Request",
29963                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
29964                );
29965                return;
29966            }
29967            if behavior.reject_registration {
29968                write_mock_response(
29969                    stream,
29970                    "503 Service Unavailable",
29971                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
29972                );
29973                return;
29974            }
29975        }
29976
29977        if path.starts_with("/api/worker/registrations/") {
29978            if behavior.reject_deregistration_protocol {
29979                write_mock_response(
29980                    stream,
29981                    "400 Bad Request",
29982                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
29983                );
29984            } else if behavior.reject_deregistration {
29985                write_mock_response(
29986                    stream,
29987                    "403 Forbidden",
29988                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
29989                );
29990            } else {
29991                write_mock_response(
29992                    stream,
29993                    "200 OK",
29994                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
29995                );
29996            }
29997            return;
29998        }
29999
30000        let is_poll = matches!(
30001            path,
30002            "/api/worker/workflow-tasks/poll"
30003                | "/api/worker/activity-tasks/poll"
30004                | "/api/worker/query-tasks/poll"
30005        );
30006        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
30007            write_mock_response(
30008                stream,
30009                "429 Too Many Requests",
30010                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
30011            );
30012            return;
30013        }
30014        if is_poll && request_number <= behavior.poll_failures_per_path {
30015            return;
30016        }
30017        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
30018            return;
30019        }
30020        if path == "/api/worker/heartbeat"
30021            && behavior.heartbeat_failure_request == Some(request_number)
30022        {
30023            return;
30024        }
30025        if path == "/api/worker/heartbeat"
30026            && behavior.delayed_heartbeat_request == Some(request_number)
30027        {
30028            thread::sleep(behavior.heartbeat_response_delay);
30029        }
30030        if behavior.unauthorized_polls && is_poll {
30031            write_mock_response(
30032                stream,
30033                "401 Unauthorized",
30034                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
30035            );
30036            return;
30037        }
30038        if behavior.draining_polls && is_poll {
30039            write_mock_response(
30040                stream,
30041                "409 Conflict",
30042                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
30043            );
30044            return;
30045        }
30046
30047        if let Some(codec_case) = behavior.invalid_task_payload_codec {
30048            if is_poll && request_number == 1 {
30049                let mut task = match path {
30050                    "/api/worker/workflow-tasks/poll" => json!({
30051                        "task_id": "codec-workflow",
30052                        "workflow_type": "codec.workflow",
30053                        "payload_codec": DEFAULT_CODEC,
30054                        "workflow_task_attempt": 1,
30055                        "lease_owner": "codec-worker"
30056                    }),
30057                    "/api/worker/activity-tasks/poll" => json!({
30058                        "task_id": "codec-activity",
30059                        "activity_attempt_id": "codec-activity-attempt",
30060                        "activity_type": "codec.activity",
30061                        "payload_codec": DEFAULT_CODEC,
30062                        "attempt_number": 1,
30063                        "lease_owner": "codec-worker"
30064                    }),
30065                    "/api/worker/query-tasks/poll" => json!({
30066                        "query_task_id": "codec-query",
30067                        "query_task_attempt": 1,
30068                        "workflow_type": "codec.workflow",
30069                        "query_name": "known",
30070                        "payload_codec": DEFAULT_CODEC,
30071                        "lease_owner": "codec-worker"
30072                    }),
30073                    _ => unreachable!("is_poll limits task codec probe paths"),
30074                };
30075                codec_case.apply(&mut task);
30076                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
30077                return;
30078            }
30079
30080            if matches!(
30081                path,
30082                "/api/worker/workflow-tasks/codec-workflow/fail"
30083                    | "/api/worker/activity-tasks/codec-activity/fail"
30084                    | "/api/worker/query-tasks/codec-query/fail"
30085            ) {
30086                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
30087                return;
30088            }
30089        }
30090
30091        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
30092            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
30093            let body = format!(
30094                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
30095            );
30096            write_mock_response(stream, "400 Bad Request", &body);
30097            return;
30098        }
30099
30100        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
30101        {
30102            write_mock_response(
30103                stream,
30104                "409 Conflict",
30105                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
30106            );
30107            return;
30108        }
30109
30110        if behavior.workflow_completion_status.is_some()
30111            && path == "/api/worker/workflow-tasks/poll"
30112            && request_number == 1
30113        {
30114            write_mock_response(
30115                stream,
30116                "200 OK",
30117                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"}}"#,
30118            );
30119            return;
30120        }
30121
30122        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
30123            if let (Some(status), Some(body)) = (
30124                behavior.workflow_completion_status,
30125                behavior.workflow_completion_body,
30126            ) {
30127                write_mock_response(stream, status, body);
30128                return;
30129            }
30130        }
30131
30132        if behavior.waiting_query_worker {
30133            if behavior.complete_named_signal
30134                && path == "/api/worker/workflow-tasks/poll"
30135                && request_number == 1
30136            {
30137                let body = json!({
30138                    "task": {
30139                        "task_id": "snapshot-open",
30140                        "workflow_id": "snapshot-1",
30141                        "run_id": "snapshot-run-1",
30142                        "workflow_type": "snapshot",
30143                        "payload_codec": DEFAULT_CODEC,
30144                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30145                            .expect("Avro workflow arguments"),
30146                        "history_events": [],
30147                        "workflow_task_attempt": 1,
30148                        "lease_owner": "rust-snapshot-worker"
30149                    }
30150                })
30151                .to_string();
30152                write_mock_response(stream, "200 OK", &body);
30153                return;
30154            }
30155
30156            let signal_request = request_number - usize::from(behavior.complete_named_signal);
30157            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
30158            if path == "/api/worker/workflow-tasks/poll"
30159                && signal_request >= 1
30160                && signal_request <= signal_request_limit
30161            {
30162                let finish = behavior.complete_named_signal && signal_request == 3;
30163                let amounts = if signal_request == 1 {
30164                    vec![3]
30165                } else {
30166                    vec![3, 5]
30167                };
30168                let task_id = if signal_request == 1 {
30169                    "snapshot-wait-3"
30170                } else if finish {
30171                    "snapshot-finish"
30172                } else {
30173                    "snapshot-wait-5"
30174                };
30175                let mut history_events = std::iter::once(json!({
30176                    "event_type": "SignalWaitOpened",
30177                    "payload": {"sequence": 1, "signal_name": "finish"}
30178                }))
30179                .chain(amounts.iter().enumerate().map(|(index, amount)| {
30180                    json!({
30181                        "event_type": "SignalReceived",
30182                        "payload": {
30183                            "signal_id": format!("increment-{amount}"),
30184                            "signal_name": "increment",
30185                            "workflow_sequence": index + 2,
30186                            "payload_codec": DEFAULT_CODEC,
30187                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30188                                .expect("Avro signal envelope")
30189                        }
30190                    })
30191                }))
30192                .collect::<Vec<_>>();
30193                let (resume_id, resume_name, resume_arguments) = if finish {
30194                    history_events.push(json!({
30195                        "event_type": "SignalReceived",
30196                        "payload": {
30197                            "signal_id": "finish",
30198                            "signal_name": "finish",
30199                            "workflow_sequence": 4,
30200                            "payload_codec": DEFAULT_CODEC,
30201                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30202                                .expect("Avro finish signal envelope")
30203                        }
30204                    }));
30205                    (
30206                        "finish".to_string(),
30207                        "finish".to_string(),
30208                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
30209                            .expect("Avro finish resume signal"),
30210                    )
30211                } else {
30212                    let amount = amounts.last().expect("amount");
30213                    (
30214                        format!("increment-{amount}"),
30215                        "increment".to_string(),
30216                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30217                            .expect("Avro increment resume signal"),
30218                    )
30219                };
30220                let body = json!({
30221                    "task": {
30222                        "task_id": task_id,
30223                        "workflow_id": "snapshot-1",
30224                        "run_id": "snapshot-run-1",
30225                        "workflow_type": "snapshot",
30226                        "payload_codec": DEFAULT_CODEC,
30227                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30228                            .expect("Avro workflow arguments"),
30229                        "history_events": history_events,
30230                        "workflow_task_attempt": 1,
30231                        "workflow_signal_id": resume_id,
30232                        "signal_name": resume_name,
30233                        "signal_arguments": resume_arguments,
30234                        "lease_owner": "rust-snapshot-worker"
30235                    }
30236                })
30237                .to_string();
30238                write_mock_response(stream, "200 OK", &body);
30239                return;
30240            }
30241
30242            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
30243                let history_events = [3, 5]
30244                    .into_iter()
30245                    .enumerate()
30246                    .map(|(index, amount)| {
30247                        json!({
30248                            "event_type": "SignalReceived",
30249                            "payload": {
30250                                "signal_id": format!("increment-{amount}"),
30251                                "signal_name": "increment",
30252                                "workflow_sequence": index + 2,
30253                                "payload_codec": DEFAULT_CODEC,
30254                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30255                                    .expect("Avro query signal envelope")
30256                            }
30257                        })
30258                    })
30259                    .collect::<Vec<_>>();
30260                let body = json!({
30261                    "task": {
30262                        "query_task_id": "snapshot-current",
30263                        "query_task_attempt": 1,
30264                        "lease_owner": "rust-snapshot-worker",
30265                        "workflow_id": "snapshot-1",
30266                        "run_id": "snapshot-run-1",
30267                        "workflow_type": "snapshot",
30268                        "query_name": "current",
30269                        "payload_codec": DEFAULT_CODEC,
30270                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30271                            .expect("Avro workflow arguments"),
30272                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30273                            .expect("Avro query arguments"),
30274                        "history_events": history_events,
30275                        "run_status": "waiting"
30276                    }
30277                })
30278                .to_string();
30279                write_mock_response(stream, "200 OK", &body);
30280                return;
30281            }
30282
30283            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
30284                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
30285            {
30286                write_mock_response(
30287                    stream,
30288                    "200 OK",
30289                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
30290                );
30291                return;
30292            }
30293
30294            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
30295                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
30296                return;
30297            }
30298
30299            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
30300                write_mock_response(
30301                    stream,
30302                    "200 OK",
30303                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
30304                );
30305                return;
30306            }
30307
30308            if path == "/api/worker/query-tasks/snapshot-current/complete" {
30309                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
30310                return;
30311            }
30312        }
30313
30314        if matches!(
30315            path,
30316            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
30317        ) {
30318            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30319                .expect("typed mock result");
30320            let body = json!({
30321                "result": typed_fidelity_probe().into_json().expect("result projection"),
30322                "result_envelope": result,
30323            })
30324            .to_string();
30325            write_mock_response(stream, "200 OK", &body);
30326            return;
30327        }
30328
30329        if path == "/api/workflows/typed-1" {
30330            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30331                .expect("typed mock result");
30332            let body = json!({
30333                "workflow_id": "typed-1",
30334                "run_id": "run-typed-1",
30335                "workflow_type": "typed.echo",
30336                "status": "completed",
30337                "output": typed_fidelity_probe().into_json().expect("output projection"),
30338                "output_envelope": result,
30339            })
30340            .to_string();
30341            write_mock_response(stream, "200 OK", &body);
30342            return;
30343        }
30344
30345        let (status, body) = match path {
30346            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
30347            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
30348            "/api/workflows" => (
30349                "201 Created",
30350                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
30351            ),
30352            "/api/worker/register" if behavior.decline_registration => (
30353                "200 OK",
30354                r#"{"worker_id":"declined-worker","registered":false}"#,
30355            ),
30356            "/api/worker/register" if behavior.waiting_query_worker => (
30357                "200 OK",
30358                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
30359            ),
30360            "/api/worker/register" => (
30361                "200 OK",
30362                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
30363            ),
30364            "/api/worker/heartbeat" => ("200 OK", "{}"),
30365            "/api/worker/activity-tasks/poll"
30366                if behavior.cancelled_activity && request_number == 1 =>
30367            {
30368                (
30369                    "200 OK",
30370                    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"}}"#,
30371                )
30372            }
30373            "/api/worker/activity-tasks/poll"
30374                if behavior.long_poll_capacity_responses_per_path > 0
30375                    && request_number
30376                        == behavior
30377                            .long_poll_capacity_responses_per_path
30378                            .saturating_add(1) =>
30379            {
30380                (
30381                    "200 OK",
30382                    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"}}"#,
30383                )
30384            }
30385            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
30386                ("200 OK", r#"{"task":null}"#)
30387            }
30388            "/api/worker/query-tasks/poll"
30389                if behavior.reject_query_completion && request_number == 1 =>
30390            {
30391                (
30392                    "200 OK",
30393                    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"}}"#,
30394                )
30395            }
30396            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
30397            "/api/worker/query-tasks/query-capture/complete"
30398            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
30399            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
30400                "200 OK",
30401                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
30402            ),
30403            "/api/worker/activity-tasks/activity-cancel/complete" => (
30404                "409 Conflict",
30405                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
30406            ),
30407            "/api/worker/activity-tasks/activity-typed/complete"
30408            | "/api/worker/activity-tasks/activity-typed/fail"
30409            | "/api/worker/activity-tasks/capacity-activity/complete"
30410            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
30411            "/api/workflows/counter-1/query/current" => (
30412                "200 OK",
30413                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
30414            ),
30415            "/api/workflows/counter-1/query/missing" => (
30416                "404 Not Found",
30417                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
30418            ),
30419            "/api/workflows/wf-lifecycle/cancel" => (
30420                "200 OK",
30421                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
30422            ),
30423            "/api/workflows/wf-lifecycle/terminate" => (
30424                "200 OK",
30425                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
30426            ),
30427            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
30428                "200 OK",
30429                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
30430            ),
30431            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
30432                "200 OK",
30433                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
30434            ),
30435            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
30436                "202 Accepted",
30437                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
30438            ),
30439            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
30440                "200 OK",
30441                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}"#,
30442            ),
30443            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
30444                "409 Conflict",
30445                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
30446            ),
30447            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
30448            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
30449                "409 Conflict",
30450                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
30451            ),
30452            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
30453                "200 OK",
30454                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"}]}}"#,
30455            ),
30456            "/api/workflows/wf-cancelled" => (
30457                "200 OK",
30458                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
30459            ),
30460            "/api/workflows/wf-terminated" => (
30461                "200 OK",
30462                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
30463            ),
30464            "/api/workflows/wf-timed-out" => (
30465                "200 OK",
30466                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
30467            ),
30468            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
30469                "200 OK",
30470                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
30471            ),
30472            "/api/workflows/wf-selected" => (
30473                "200 OK",
30474                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
30475            ),
30476            "/api/workflows/wf-selected/runs/run-selected" => (
30477                "200 OK",
30478                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
30479            ),
30480            _ => ("404 Not Found", r#"{"message":"not found"}"#),
30481        };
30482        write_mock_response(stream, status, body);
30483    }
30484
30485    fn mock_request_is_complete(request: &[u8]) -> bool {
30486        let Some(header_end) = request
30487            .windows(4)
30488            .position(|window| window == b"\r\n\r\n")
30489            .map(|position| position + 4)
30490        else {
30491            return false;
30492        };
30493        let headers = String::from_utf8_lossy(&request[..header_end]);
30494        let content_length = headers.lines().find_map(|line| {
30495            let (name, value) = line.split_once(':')?;
30496            name.eq_ignore_ascii_case("content-length")
30497                .then(|| value.trim().parse::<usize>().ok())
30498                .flatten()
30499        });
30500
30501        request.len() >= header_end + content_length.unwrap_or(0)
30502    }
30503
30504    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
30505        let response = format!(
30506            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
30507            body.len()
30508        );
30509
30510        let _ = stream.write_all(response.as_bytes());
30511        let _ = stream.flush();
30512    }
30513
30514    fn activity_completion_backend_recovery(
30515        path: &str,
30516        _body: &str,
30517        request_number: usize,
30518    ) -> Option<(&'static str, String)> {
30519        match path {
30520            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
30521                "200 OK",
30522                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(),
30523            )),
30524            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
30525                "503 Service Unavailable",
30526                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(),
30527            )),
30528            "/api/worker/activity-tasks/recover-activity/complete" => Some((
30529                "200 OK",
30530                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30531            )),
30532            _ => None,
30533        }
30534    }
30535
30536    fn workflow_completion_backend_recovery(
30537        path: &str,
30538        _body: &str,
30539        request_number: usize,
30540    ) -> Option<(&'static str, String)> {
30541        match path {
30542            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
30543                "200 OK",
30544                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
30545            )),
30546            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
30547                "503 Service Unavailable",
30548                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(),
30549            )),
30550            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
30551                "200 OK",
30552                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30553            )),
30554            _ => None,
30555        }
30556    }
30557
30558    fn workflow_completion_lock_pressure(
30559        path: &str,
30560        body: &str,
30561        request_number: usize,
30562    ) -> Option<(&'static str, String)> {
30563        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
30564            return Some((
30565                "503 Service Unavailable",
30566                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
30567                    "outcome":"deferred", "recorded":false, "retryable":true,
30568                    "retry_after_seconds":1, "task_id":"recover-workflow",
30569                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
30570                    "backend":{"driver":"sqlite", "lock_pressure":true}})
30571                .to_string(),
30572            ));
30573        }
30574        workflow_completion_backend_recovery(path, body, request_number)
30575    }
30576
30577    fn workflow_completion_lock_pressure_forever(
30578        path: &str,
30579        body: &str,
30580        request_number: usize,
30581    ) -> Option<(&'static str, String)> {
30582        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
30583            return workflow_completion_lock_pressure(path, body, 1);
30584        }
30585        workflow_completion_lock_pressure(path, body, request_number)
30586    }
30587
30588    fn workflow_completion_lock_pressure_then_expired(
30589        path: &str,
30590        body: &str,
30591        request_number: usize,
30592    ) -> Option<(&'static str, String)> {
30593        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30594            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
30595                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
30596        }
30597        workflow_completion_lock_pressure(path, body, request_number)
30598    }
30599
30600    fn workflow_completion_lock_pressure_then_slow(
30601        path: &str,
30602        body: &str,
30603        request_number: usize,
30604    ) -> Option<(&'static str, String)> {
30605        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30606            thread::sleep(Duration::from_secs(2));
30607        }
30608        workflow_completion_lock_pressure(path, body, request_number)
30609    }
30610
30611    fn workflow_completion_pressure_then_backend_loss(
30612        path: &str,
30613        body: &str,
30614        request_number: usize,
30615    ) -> Option<(&'static str, String)> {
30616        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30617            return Some((
30618                "503 Service Unavailable",
30619                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
30620                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
30621                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
30622                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
30623                .to_string(),
30624            ));
30625        }
30626        workflow_completion_lock_pressure(path, body, request_number)
30627    }
30628
30629    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
30630        let client = Client::builder(server.base_url())
30631            .timeout(Duration::from_secs(4))
30632            .build()
30633            .unwrap();
30634        let mut worker = Worker::new(client, "recover-queue")
30635            .worker_id("recover-worker")
30636            .poll_timeout(Duration::from_millis(10));
30637        worker.register_workflow("recover.workflow", move |_ctx, _args| {
30638            let calls = Arc::clone(&calls);
30639            async move {
30640                calls.fetch_add(1, Ordering::SeqCst);
30641                Ok(json!("done"))
30642            }
30643        });
30644        worker
30645    }
30646
30647    #[tokio::test]
30648    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
30649        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30650            request_override: Some(workflow_completion_lock_pressure_forever),
30651            ..MockWorkerBehavior::default()
30652        });
30653        let calls = Arc::new(AtomicUsize::new(0));
30654        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30655            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30656        worker
30657            .client
30658            .worker_storage_admission
30659            .as_mut()
30660            .unwrap()
30661            .workflow_completion_retry_deadline =
30662            Some(tokio::time::Instant::now() + Duration::from_millis(250));
30663        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
30664            .await
30665            .unwrap();
30666        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30667        assert_eq!(calls.load(Ordering::SeqCst), 1);
30668        assert_eq!(
30669            server
30670                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30671                .len(),
30672            1
30673        );
30674    }
30675
30676    #[tokio::test]
30677    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
30678        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30679            request_override: Some(workflow_completion_lock_pressure_then_slow),
30680            ..MockWorkerBehavior::default()
30681        });
30682        let calls = Arc::new(AtomicUsize::new(0));
30683        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30684            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30685        let start = tokio::time::Instant::now();
30686        worker
30687            .client
30688            .worker_storage_admission
30689            .as_mut()
30690            .unwrap()
30691            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
30692        assert!(matches!(
30693            worker.poll_workflow_once().await,
30694            Err(Error::Timeout)
30695        ));
30696        assert!(start.elapsed() < Duration::from_secs(2));
30697        assert_eq!(calls.load(Ordering::SeqCst), 1);
30698        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30699        assert_eq!(bodies.len(), 2);
30700        assert_eq!(bodies[0], bodies[1]);
30701    }
30702
30703    #[tokio::test]
30704    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
30705        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30706            request_override: Some(workflow_completion_pressure_then_backend_loss),
30707            ..MockWorkerBehavior::default()
30708        });
30709        let calls = Arc::new(AtomicUsize::new(0));
30710        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30711            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30712        let start = tokio::time::Instant::now();
30713        worker
30714            .client
30715            .worker_storage_admission
30716            .as_mut()
30717            .unwrap()
30718            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
30719        let result = worker.poll_workflow_once().await;
30720        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30721        assert!(start.elapsed() < Duration::from_secs(2));
30722        assert_eq!(calls.load(Ordering::SeqCst), 1);
30723        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30724        assert_eq!(bodies.len(), 2);
30725        assert_eq!(bodies[0], bodies[1]);
30726    }
30727
30728    #[tokio::test]
30729    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
30730        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30731            request_override: Some(workflow_completion_lock_pressure_forever),
30732            ..MockWorkerBehavior::default()
30733        });
30734        let calls = Arc::new(AtomicUsize::new(0));
30735        let stop = Arc::new(AtomicBool::new(false));
30736        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
30737            .with_storage_admission(Arc::clone(&stop));
30738        let shutdown = async {
30739            while server
30740                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30741                .is_empty()
30742            {
30743                tokio::time::sleep(Duration::from_millis(10)).await;
30744            }
30745            stop.store(true, Ordering::SeqCst);
30746        };
30747        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
30748            tokio::join!(worker.poll_workflow_once(), shutdown)
30749        })
30750        .await
30751        .unwrap();
30752        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30753        assert_eq!(calls.load(Ordering::SeqCst), 1);
30754        assert_eq!(
30755            server
30756                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30757                .len(),
30758            1
30759        );
30760    }
30761
30762    #[tokio::test]
30763    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
30764        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30765            request_override: Some(workflow_completion_lock_pressure_then_expired),
30766            ..MockWorkerBehavior::default()
30767        });
30768        let calls = Arc::new(AtomicUsize::new(0));
30769        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
30770        let result = worker.run_once().await;
30771        assert!(
30772            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
30773        );
30774        assert_eq!(calls.load(Ordering::SeqCst), 1);
30775        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30776        assert_eq!(bodies.len(), 2);
30777        assert_eq!(bodies[0], bodies[1]);
30778        assert!(server
30779            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
30780            .is_empty());
30781    }
30782
30783    #[tokio::test]
30784    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
30785        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30786            request_override: Some(workflow_completion_lock_pressure),
30787            ..MockWorkerBehavior::default()
30788        });
30789        let client = Client::builder(server.base_url())
30790            .timeout(Duration::from_secs(2))
30791            .build()
30792            .unwrap();
30793        let calls = Arc::new(AtomicUsize::new(0));
30794        let mut worker = Worker::new(client, "recover-queue")
30795            .worker_id("recover-worker")
30796            .recover_transient_outages(true)
30797            .poll_timeout(Duration::from_millis(10))
30798            .retry_policy(WorkerRetryPolicy {
30799                max_retries: 1,
30800                initial_backoff: Duration::from_millis(10),
30801                max_backoff: Duration::from_millis(10),
30802            });
30803        worker.register_workflow("recover.workflow", {
30804            let calls = Arc::clone(&calls);
30805            move |_ctx, _args| {
30806                let calls = Arc::clone(&calls);
30807                async move {
30808                    calls.fetch_add(1, Ordering::SeqCst);
30809                    Ok(json!("done"))
30810                }
30811            }
30812        });
30813        let start = tokio::time::Instant::now();
30814        assert_eq!(worker.run_once().await.unwrap(), 1);
30815        assert!(start.elapsed() >= Duration::from_secs(1));
30816        assert_eq!(calls.load(Ordering::SeqCst), 1);
30817        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30818        assert_eq!(bodies.len(), 2);
30819        assert_eq!(bodies[0], bodies[1]);
30820    }
30821
30822    #[test]
30823    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
30824        let path = "/worker/workflow-tasks/recover-workflow/complete";
30825        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
30826        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
30827            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
30828            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
30829            "backend":{"driver":"sqlite", "lock_pressure":true}});
30830        let error = |body: Value| Error::Http {
30831            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30832            body: body.to_string(),
30833        };
30834        assert_eq!(
30835            worker_deferred_workflow_completion_retry_after(
30836                &error(response.clone()),
30837                path,
30838                Some(&request)
30839            ),
30840            Some(Duration::from_secs(1))
30841        );
30842        for (field, value) in [
30843            ("reason", json!("backend_unavailable")),
30844            ("operation", json!("complete_activity_task")),
30845            ("task_id", json!("other-task")),
30846            ("lease_owner", json!("other-owner")),
30847            ("workflow_task_attempt", json!(4)),
30848            ("recorded", json!(true)),
30849            ("recorded", Value::Null),
30850            ("recorded", json!("false")),
30851            ("retryable", json!(false)),
30852            ("retry_after_seconds", json!(0)),
30853            ("retry_after_seconds", json!(-1)),
30854            ("retry_after_seconds", json!(1.0)),
30855            ("retry_after_seconds", json!("1")),
30856            ("retry_after_seconds", json!(6)),
30857            ("backend", json!({"lock_pressure":false})),
30858        ] {
30859            let mut invalid = response.clone();
30860            invalid[field] = value;
30861            assert_eq!(
30862                worker_deferred_workflow_completion_retry_after(
30863                    &error(invalid),
30864                    path,
30865                    Some(&request)
30866                ),
30867                None,
30868                "invalid {field}"
30869            );
30870        }
30871        for field in [
30872            "reason",
30873            "operation",
30874            "task_id",
30875            "lease_owner",
30876            "workflow_task_attempt",
30877            "recorded",
30878            "retryable",
30879            "retry_after_seconds",
30880            "backend",
30881        ] {
30882            let mut missing = response.clone();
30883            missing.as_object_mut().unwrap().remove(field);
30884            assert_eq!(
30885                worker_deferred_workflow_completion_retry_after(
30886                    &error(missing),
30887                    path,
30888                    Some(&request)
30889                ),
30890                None,
30891                "missing {field}"
30892            );
30893        }
30894        assert_eq!(
30895            worker_deferred_workflow_completion_retry_after(
30896                &error(response.clone()),
30897                "/worker/activity-tasks/recover-workflow/complete",
30898                Some(&request)
30899            ),
30900            None
30901        );
30902        assert_eq!(
30903            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
30904            None
30905        );
30906        let wrong_status = Error::Http {
30907            status: reqwest::StatusCode::CONFLICT,
30908            body: response.to_string(),
30909        };
30910        assert_eq!(
30911            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
30912            None
30913        );
30914    }
30915
30916    fn activity_completion_stale_after_backend_recovery(
30917        path: &str,
30918        body: &str,
30919        request_number: usize,
30920    ) -> Option<(&'static str, String)> {
30921        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
30922            return Some((
30923                "409 Conflict",
30924                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(),
30925            ));
30926        }
30927        activity_completion_backend_recovery(path, body, request_number)
30928    }
30929
30930    fn activity_completion_remains_unavailable(
30931        path: &str,
30932        body: &str,
30933        request_number: usize,
30934    ) -> Option<(&'static str, String)> {
30935        if path == "/api/worker/activity-tasks/recover-activity/complete" {
30936            return activity_completion_backend_recovery(path, body, 1);
30937        }
30938        activity_completion_backend_recovery(path, body, request_number)
30939    }
30940
30941    #[tokio::test]
30942    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
30943        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30944            request_override: Some(activity_completion_backend_recovery),
30945            ..MockWorkerBehavior::default()
30946        });
30947        let client = Client::builder(server.base_url())
30948            .timeout(Duration::from_secs(2))
30949            .build()
30950            .expect("client");
30951        let handler_calls = Arc::new(AtomicUsize::new(0));
30952        let mut worker = Worker::new(client, "recover-queue")
30953            .worker_id("recover-worker")
30954            .poll_timeout(Duration::from_millis(10));
30955        worker.register_activity("recover.activity", {
30956            let handler_calls = Arc::clone(&handler_calls);
30957            move |_ctx, _args| {
30958                let handler_calls = Arc::clone(&handler_calls);
30959                async move {
30960                    handler_calls.fetch_add(1, Ordering::SeqCst);
30961                    Ok(json!("done"))
30962                }
30963            }
30964        });
30965
30966        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30967        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30968        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30969        assert_eq!(bodies.len(), 2);
30970        assert_eq!(bodies[0], bodies[1]);
30971    }
30972
30973    #[tokio::test]
30974    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
30975        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30976            request_override: Some(workflow_completion_backend_recovery),
30977            ..MockWorkerBehavior::default()
30978        });
30979        let client = Client::builder(server.base_url())
30980            .timeout(Duration::from_secs(2))
30981            .build()
30982            .expect("client");
30983        let handler_calls = Arc::new(AtomicUsize::new(0));
30984        let mut worker = Worker::new(client, "recover-queue")
30985            .worker_id("recover-worker")
30986            .poll_timeout(Duration::from_millis(10));
30987        worker.register_workflow("recover.workflow", {
30988            let handler_calls = Arc::clone(&handler_calls);
30989            move |_ctx, _args| {
30990                let handler_calls = Arc::clone(&handler_calls);
30991                async move {
30992                    handler_calls.fetch_add(1, Ordering::SeqCst);
30993                    Ok(json!("done"))
30994                }
30995            }
30996        });
30997
30998        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
30999        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
31000        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
31001        assert_eq!(bodies.len(), 2);
31002        assert_eq!(bodies[0], bodies[1]);
31003    }
31004
31005    #[tokio::test]
31006    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
31007        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31008            request_override: Some(activity_completion_stale_after_backend_recovery),
31009            ..MockWorkerBehavior::default()
31010        });
31011        let client = Client::builder(server.base_url())
31012            .timeout(Duration::from_secs(2))
31013            .build()
31014            .expect("client");
31015        let handler_calls = Arc::new(AtomicUsize::new(0));
31016        let mut worker = Worker::new(client, "recover-queue")
31017            .worker_id("recover-worker")
31018            .poll_timeout(Duration::from_millis(10));
31019        worker.register_activity("recover.activity", {
31020            let handler_calls = Arc::clone(&handler_calls);
31021            move |_ctx, _args| {
31022                let handler_calls = Arc::clone(&handler_calls);
31023                async move {
31024                    handler_calls.fetch_add(1, Ordering::SeqCst);
31025                    Ok(json!("done"))
31026                }
31027            }
31028        });
31029
31030        assert_eq!(
31031            worker
31032                .run_once()
31033                .await
31034                .expect("authoritative stale outcome"),
31035            1
31036        );
31037        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
31038        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
31039        assert_eq!(bodies.len(), 2);
31040        assert_eq!(bodies[0], bodies[1]);
31041    }
31042
31043    #[test]
31044    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
31045        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
31046        let response = json!({
31047            "reason":"backend_unavailable", "operation":"complete_activity_task",
31048            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
31049            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
31050            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
31051        });
31052        let path = "/worker/activity-tasks/recover-activity/complete";
31053        let error = |body: Value| Error::Http {
31054            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
31055            body: body.to_string(),
31056        };
31057        assert_eq!(
31058            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
31059            Some(Duration::from_secs(1))
31060        );
31061
31062        for (field, invalid) in [
31063            ("operation", json!("poll_activity_task")),
31064            ("outcome", json!("rejected")),
31065            ("worker_id", json!("another-worker")),
31066            ("task_queue", json!("recover-queue")),
31067            ("retryable", json!(false)),
31068            ("retry_after_seconds", json!(0)),
31069            ("task_id", json!("another-task")),
31070            ("lease_owner", json!("another-worker")),
31071            ("activity_attempt_id", json!("another-attempt")),
31072        ] {
31073            let mut invalid_response = response.clone();
31074            invalid_response[field] = invalid;
31075            assert_eq!(
31076                worker_fenced_completion_retry_after(
31077                    &error(invalid_response),
31078                    path,
31079                    Some(&request)
31080                ),
31081                None,
31082                "must not retry mismatched {field}"
31083            );
31084        }
31085        assert_eq!(
31086            worker_fenced_completion_retry_after(&error(response), path, None),
31087            None
31088        );
31089    }
31090
31091    #[tokio::test]
31092    async fn shutdown_interrupts_fenced_completion_backend_wait() {
31093        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31094            request_override: Some(activity_completion_remains_unavailable),
31095            ..MockWorkerBehavior::default()
31096        });
31097        let client = Client::builder(server.base_url())
31098            .timeout(Duration::from_secs(2))
31099            .build()
31100            .expect("client");
31101        let stop = Arc::new(AtomicBool::new(false));
31102        let worker = Worker::new(client, "recover-queue")
31103            .worker_id("recover-worker")
31104            .with_storage_admission(Arc::clone(&stop));
31105        let completion = tokio::spawn(async move {
31106            worker
31107                .client
31108                .complete_activity_task(
31109                    "recover-activity",
31110                    "recover-attempt",
31111                    "recover-worker",
31112                    json!("done"),
31113                    DEFAULT_CODEC,
31114                )
31115                .await
31116        });
31117        let path = "/api/worker/activity-tasks/recover-activity/complete";
31118        tokio::time::timeout(Duration::from_secs(2), async {
31119            while server.request_count(path) == 0 {
31120                tokio::time::sleep(Duration::from_millis(10)).await;
31121            }
31122        })
31123        .await
31124        .expect("first completion request");
31125        stop.store(true, Ordering::SeqCst);
31126        let error = tokio::time::timeout(Duration::from_secs(1), completion)
31127            .await
31128            .expect("shutdown must interrupt retry wait")
31129            .expect("completion task")
31130            .expect_err("backend is still unavailable");
31131        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
31132        assert_eq!(server.request_count(path), 1);
31133    }
31134}